1
0
Fork 0
mirror of https://github.com/rharkor/caching-for-turbo.git synced 2025-06-09 17:44:48 +09:00
caching-for-turbo/dist/index.js
2024-06-13 14:53:45 +02:00

114799 lines
No EOL
3.7 MiB
Generated
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 87351:
/***/ (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;
});
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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.issue = exports.issueCommand = void 0;
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;
}
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 __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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
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));
const oidc_utils_1 = __nccwpck_require__(98041);
/**
* 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) {
return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));
}
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.issueFileCommand('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.
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
* Returns an empty string if the value is not defined.
*
* @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}`);
}
if (options && options.trimWhitespace === false) {
return val;
}
return val.trim();
}
exports.getInput = getInput;
/**
* Gets the values of an multiline input. Each value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string[]
*
*/
function getMultilineInput(name, options) {
const inputs = getInput(name, options)
.split('\n')
.filter(x => x !== '');
if (options && options.trimWhitespace === false) {
return inputs;
}
return inputs.map(input => input.trim());
}
exports.getMultilineInput = getMultilineInput;
/**
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
* The return value is also in boolean type.
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns boolean
*/
function getBooleanInput(name, options) {
const trueValue = ['true', 'True', 'TRUE'];
const falseValue = ['false', 'False', 'FALSE'];
const val = getInput(name, options);
if (trueValue.includes(val))
return true;
if (falseValue.includes(val))
return false;
throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
}
exports.getBooleanInput = getBooleanInput;
/**
* 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) {
const filePath = process.env['GITHUB_OUTPUT'] || '';
if (filePath) {
return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));
}
process.stdout.write(os.EOL);
command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(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()
* @param properties optional properties to add to the annotation.
*/
function error(message, properties = {}) {
command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.error = error;
/**
* Adds a warning issue
* @param message warning issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
function warning(message, properties = {}) {
command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.warning = warning;
/**
* Adds a notice issue
* @param message notice issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
function notice(message, properties = {}) {
command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.notice = notice;
/**
* 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) {
const filePath = process.env['GITHUB_STATE'] || '';
if (filePath) {
return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));
}
command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(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;
function getIDToken(aud) {
return __awaiter(this, void 0, void 0, function* () {
return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
}
exports.getIDToken = getIDToken;
/**
* Summary exports
*/
var summary_1 = __nccwpck_require__(81327);
Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } }));
/**
* @deprecated use core.summary
*/
var summary_2 = __nccwpck_require__(81327);
Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } }));
/**
* Path exports
*/
var path_utils_1 = __nccwpck_require__(2981);
Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } }));
Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } }));
Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }));
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 717:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
// For internal use, subject to change.
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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
// 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 uuid_1 = __nccwpck_require__(75840);
const utils_1 = __nccwpck_require__(5278);
function issueFileCommand(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.issueFileCommand = issueFileCommand;
function prepareKeyValueMessage(key, value) {
const delimiter = `ghadelimiter_${uuid_1.v4()}`;
const convertedValue = utils_1.toCommandValue(value);
// These should realistically never happen, but just in case someone finds a
// way to exploit uuid generation let's not allow keys or values that contain
// the delimiter.
if (key.includes(delimiter)) {
throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
}
if (convertedValue.includes(delimiter)) {
throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
}
return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
}
exports.prepareKeyValueMessage = prepareKeyValueMessage;
//# sourceMappingURL=file-command.js.map
/***/ }),
/***/ 98041:
/***/ (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());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OidcClient = void 0;
const http_client_1 = __nccwpck_require__(96255);
const auth_1 = __nccwpck_require__(35526);
const core_1 = __nccwpck_require__(42186);
class OidcClient {
static createHttpClient(allowRetry = true, maxRetry = 10) {
const requestOptions = {
allowRetries: allowRetry,
maxRetries: maxRetry
};
return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
}
static getRequestToken() {
const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
if (!token) {
throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
}
return token;
}
static getIDTokenUrl() {
const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
if (!runtimeUrl) {
throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
}
return runtimeUrl;
}
static getCall(id_token_url) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const httpclient = OidcClient.createHttpClient();
const res = yield httpclient
.getJson(id_token_url)
.catch(error => {
throw new Error(`Failed to get ID Token. \n
Error Code : ${error.statusCode}\n
Error Message: ${error.message}`);
});
const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
if (!id_token) {
throw new Error('Response json body do not have ID Token field');
}
return id_token;
});
}
static getIDToken(audience) {
return __awaiter(this, void 0, void 0, function* () {
try {
// New ID Token is requested from action service
let id_token_url = OidcClient.getIDTokenUrl();
if (audience) {
const encodedAudience = encodeURIComponent(audience);
id_token_url = `${id_token_url}&audience=${encodedAudience}`;
}
core_1.debug(`ID token url is ${id_token_url}`);
const id_token = yield OidcClient.getCall(id_token_url);
core_1.setSecret(id_token);
return id_token;
}
catch (error) {
throw new Error(`Error message: ${error.message}`);
}
});
}
}
exports.OidcClient = OidcClient;
//# sourceMappingURL=oidc-utils.js.map
/***/ }),
/***/ 2981:
/***/ (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;
});
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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
const path = __importStar(__nccwpck_require__(71017));
/**
* toPosixPath converts the given path to the posix form. On Windows, \\ will be
* replaced with /.
*
* @param pth. Path to transform.
* @return string Posix path.
*/
function toPosixPath(pth) {
return pth.replace(/[\\]/g, '/');
}
exports.toPosixPath = toPosixPath;
/**
* toWin32Path converts the given path to the win32 form. On Linux, / will be
* replaced with \\.
*
* @param pth. Path to transform.
* @return string Win32 path.
*/
function toWin32Path(pth) {
return pth.replace(/[/]/g, '\\');
}
exports.toWin32Path = toWin32Path;
/**
* toPlatformPath converts the given path to a platform-specific path. It does
* this by replacing instances of / and \ with the platform-specific path
* separator.
*
* @param pth The path to platformize.
* @return string The platform-specific path.
*/
function toPlatformPath(pth) {
return pth.replace(/[/\\]/g, path.sep);
}
exports.toPlatformPath = toPlatformPath;
//# sourceMappingURL=path-utils.js.map
/***/ }),
/***/ 81327:
/***/ (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());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
const os_1 = __nccwpck_require__(22037);
const fs_1 = __nccwpck_require__(57147);
const { access, appendFile, writeFile } = fs_1.promises;
exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
class Summary {
constructor() {
this._buffer = '';
}
/**
* Finds the summary file path from the environment, rejects if env var is not found or file does not exist
* Also checks r/w permissions.
*
* @returns step summary file path
*/
filePath() {
return __awaiter(this, void 0, void 0, function* () {
if (this._filePath) {
return this._filePath;
}
const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
if (!pathFromEnv) {
throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
}
try {
yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
}
catch (_a) {
throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
}
this._filePath = pathFromEnv;
return this._filePath;
});
}
/**
* Wraps content in an HTML tag, adding any HTML attributes
*
* @param {string} tag HTML tag to wrap
* @param {string | null} content content within the tag
* @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
*
* @returns {string} content wrapped in HTML element
*/
wrap(tag, content, attrs = {}) {
const htmlAttrs = Object.entries(attrs)
.map(([key, value]) => ` ${key}="${value}"`)
.join('');
if (!content) {
return `<${tag}${htmlAttrs}>`;
}
return `<${tag}${htmlAttrs}>${content}</${tag}>`;
}
/**
* Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
*
* @param {SummaryWriteOptions} [options] (optional) options for write operation
*
* @returns {Promise<Summary>} summary instance
*/
write(options) {
return __awaiter(this, void 0, void 0, function* () {
const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
const filePath = yield this.filePath();
const writeFunc = overwrite ? writeFile : appendFile;
yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
return this.emptyBuffer();
});
}
/**
* Clears the summary buffer and wipes the summary file
*
* @returns {Summary} summary instance
*/
clear() {
return __awaiter(this, void 0, void 0, function* () {
return this.emptyBuffer().write({ overwrite: true });
});
}
/**
* Returns the current summary buffer as a string
*
* @returns {string} string of summary buffer
*/
stringify() {
return this._buffer;
}
/**
* If the summary buffer is empty
*
* @returns {boolen} true if the buffer is empty
*/
isEmptyBuffer() {
return this._buffer.length === 0;
}
/**
* Resets the summary buffer without writing to summary file
*
* @returns {Summary} summary instance
*/
emptyBuffer() {
this._buffer = '';
return this;
}
/**
* Adds raw text to the summary buffer
*
* @param {string} text content to add
* @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
*
* @returns {Summary} summary instance
*/
addRaw(text, addEOL = false) {
this._buffer += text;
return addEOL ? this.addEOL() : this;
}
/**
* Adds the operating system-specific end-of-line marker to the buffer
*
* @returns {Summary} summary instance
*/
addEOL() {
return this.addRaw(os_1.EOL);
}
/**
* Adds an HTML codeblock to the summary buffer
*
* @param {string} code content to render within fenced code block
* @param {string} lang (optional) language to syntax highlight code
*
* @returns {Summary} summary instance
*/
addCodeBlock(code, lang) {
const attrs = Object.assign({}, (lang && { lang }));
const element = this.wrap('pre', this.wrap('code', code), attrs);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML list to the summary buffer
*
* @param {string[]} items list of items to render
* @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
*
* @returns {Summary} summary instance
*/
addList(items, ordered = false) {
const tag = ordered ? 'ol' : 'ul';
const listItems = items.map(item => this.wrap('li', item)).join('');
const element = this.wrap(tag, listItems);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML table to the summary buffer
*
* @param {SummaryTableCell[]} rows table rows
*
* @returns {Summary} summary instance
*/
addTable(rows) {
const tableBody = rows
.map(row => {
const cells = row
.map(cell => {
if (typeof cell === 'string') {
return this.wrap('td', cell);
}
const { header, data, colspan, rowspan } = cell;
const tag = header ? 'th' : 'td';
const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
return this.wrap(tag, data, attrs);
})
.join('');
return this.wrap('tr', cells);
})
.join('');
const element = this.wrap('table', tableBody);
return this.addRaw(element).addEOL();
}
/**
* Adds a collapsable HTML details element to the summary buffer
*
* @param {string} label text for the closed state
* @param {string} content collapsable content
*
* @returns {Summary} summary instance
*/
addDetails(label, content) {
const element = this.wrap('details', this.wrap('summary', label) + content);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML image tag to the summary buffer
*
* @param {string} src path to the image you to embed
* @param {string} alt text description of the image
* @param {SummaryImageOptions} options (optional) addition image attributes
*
* @returns {Summary} summary instance
*/
addImage(src, alt, options) {
const { width, height } = options || {};
const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML section heading element
*
* @param {string} text heading text
* @param {number | string} [level=1] (optional) the heading level, default: 1
*
* @returns {Summary} summary instance
*/
addHeading(text, level) {
const tag = `h${level}`;
const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
? tag
: 'h1';
const element = this.wrap(allowedTag, text);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML thematic break (<hr>) to the summary buffer
*
* @returns {Summary} summary instance
*/
addSeparator() {
const element = this.wrap('hr', null);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML line break (<br>) to the summary buffer
*
* @returns {Summary} summary instance
*/
addBreak() {
const element = this.wrap('br', null);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML blockquote to the summary buffer
*
* @param {string} text quote text
* @param {string} cite (optional) citation url
*
* @returns {Summary} summary instance
*/
addQuote(text, cite) {
const attrs = Object.assign({}, (cite && { cite }));
const element = this.wrap('blockquote', text, attrs);
return this.addRaw(element).addEOL();
}
/**
* Adds an HTML anchor tag to the summary buffer
*
* @param {string} text link text/content
* @param {string} href hyperlink
*
* @returns {Summary} summary instance
*/
addLink(text, href) {
const element = this.wrap('a', text, { href });
return this.addRaw(element).addEOL();
}
}
const _summary = new Summary();
/**
* @deprecated use `core.summary`
*/
exports.markdownSummary = _summary;
exports.summary = _summary;
//# sourceMappingURL=summary.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 }));
exports.toCommandProperties = exports.toCommandValue = void 0;
/**
* 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;
/**
*
* @param annotationProperties
* @returns The command properties to send with the actual annotation command
* See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
*/
function toCommandProperties(annotationProperties) {
if (!Object.keys(annotationProperties).length) {
return {};
}
return {
title: annotationProperties.title,
file: annotationProperties.file,
line: annotationProperties.startLine,
endLine: annotationProperties.endLine,
col: annotationProperties.startColumn,
endColumn: annotationProperties.endColumn
};
}
exports.toCommandProperties = toCommandProperties;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 35526:
/***/ (function(__unused_webpack_module, exports) {
"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());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;
class BasicCredentialHandler {
constructor(username, password) {
this.username = username;
this.password = password;
}
prepareRequest(options) {
if (!options.headers) {
throw Error('The request has no headers');
}
options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
}
// This handler cannot handle 401
canHandleAuthentication() {
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error('not implemented');
});
}
}
exports.BasicCredentialHandler = BasicCredentialHandler;
class BearerCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
if (!options.headers) {
throw Error('The request has no headers');
}
options.headers['Authorization'] = `Bearer ${this.token}`;
}
// This handler cannot handle 401
canHandleAuthentication() {
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error('not implemented');
});
}
}
exports.BearerCredentialHandler = BearerCredentialHandler;
class PersonalAccessTokenCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
if (!options.headers) {
throw Error('The request has no headers');
}
options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
}
// This handler cannot handle 401
canHandleAuthentication() {
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error('not implemented');
});
}
}
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
//# sourceMappingURL=auth.js.map
/***/ }),
/***/ 96255:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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;
};
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());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
const http = __importStar(__nccwpck_require__(13685));
const https = __importStar(__nccwpck_require__(95687));
const pm = __importStar(__nccwpck_require__(19835));
const tunnel = __importStar(__nccwpck_require__(74294));
const undici_1 = __nccwpck_require__(41773);
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));
var Headers;
(function (Headers) {
Headers["Accept"] = "accept";
Headers["ContentType"] = "content-type";
})(Headers || (exports.Headers = Headers = {}));
var MediaTypes;
(function (MediaTypes) {
MediaTypes["ApplicationJson"] = "application/json";
})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
function getProxyUrl(serverUrl) {
const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
return proxyUrl ? proxyUrl.href : '';
}
exports.getProxyUrl = getProxyUrl;
const HttpRedirectCodes = [
HttpCodes.MovedPermanently,
HttpCodes.ResourceMoved,
HttpCodes.SeeOther,
HttpCodes.TemporaryRedirect,
HttpCodes.PermanentRedirect
];
const HttpResponseRetryCodes = [
HttpCodes.BadGateway,
HttpCodes.ServiceUnavailable,
HttpCodes.GatewayTimeout
];
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
const ExponentialBackoffCeiling = 10;
const ExponentialBackoffTimeSlice = 5;
class HttpClientError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'HttpClientError';
this.statusCode = statusCode;
Object.setPrototypeOf(this, HttpClientError.prototype);
}
}
exports.HttpClientError = HttpClientError;
class HttpClientResponse {
constructor(message) {
this.message = message;
}
readBody() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
let output = Buffer.alloc(0);
this.message.on('data', (chunk) => {
output = Buffer.concat([output, chunk]);
});
this.message.on('end', () => {
resolve(output.toString());
});
}));
});
}
readBodyBuffer() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
const chunks = [];
this.message.on('data', (chunk) => {
chunks.push(chunk);
});
this.message.on('end', () => {
resolve(Buffer.concat(chunks));
});
}));
});
}
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
const parsedUrl = new URL(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, requestOptions) {
this._ignoreSslError = false;
this._allowRedirects = true;
this._allowRedirectDowngrade = false;
this._maxRedirects = 50;
this._allowRetries = false;
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
if (requestOptions.ignoreSslError != null) {
this._ignoreSslError = requestOptions.ignoreSslError;
}
this._socketTimeout = requestOptions.socketTimeout;
if (requestOptions.allowRedirects != null) {
this._allowRedirects = requestOptions.allowRedirects;
}
if (requestOptions.allowRedirectDowngrade != null) {
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
}
if (requestOptions.maxRedirects != null) {
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
}
if (requestOptions.keepAlive != null) {
this._keepAlive = requestOptions.keepAlive;
}
if (requestOptions.allowRetries != null) {
this._allowRetries = requestOptions.allowRetries;
}
if (requestOptions.maxRetries != null) {
this._maxRetries = requestOptions.maxRetries;
}
}
}
options(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
});
}
get(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('GET', requestUrl, null, additionalHeaders || {});
});
}
del(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
});
}
post(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('POST', requestUrl, data, additionalHeaders || {});
});
}
patch(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
});
}
put(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
});
}
head(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request(verb, requestUrl, stream, additionalHeaders);
});
}
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
getJson(requestUrl, additionalHeaders = {}) {
return __awaiter(this, void 0, void 0, function* () {
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
const res = yield this.get(requestUrl, additionalHeaders);
return this._processResponse(res, this.requestOptions);
});
}
postJson(requestUrl, obj, additionalHeaders = {}) {
return __awaiter(this, void 0, void 0, function* () {
const data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
const res = yield this.post(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
});
}
putJson(requestUrl, obj, additionalHeaders = {}) {
return __awaiter(this, void 0, void 0, function* () {
const data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
const res = yield this.put(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
});
}
patchJson(requestUrl, obj, additionalHeaders = {}) {
return __awaiter(this, void 0, void 0, function* () {
const data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
const res = yield this.patch(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
});
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
request(verb, requestUrl, data, headers) {
return __awaiter(this, void 0, void 0, function* () {
if (this._disposed) {
throw new Error('Client has already been disposed.');
}
const parsedUrl = new URL(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
? this._maxRetries + 1
: 1;
let numTries = 0;
let response;
do {
response = yield this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (const handler of this.handlers) {
if (handler.canHandleAuthentication(response)) {
authenticationHandler = handler;
break;
}
}
if (authenticationHandler) {
return authenticationHandler.handleAuthentication(this, info, data);
}
else {
// We have received an unauthorized response but have no handlers to handle it.
// Let the response return to the caller.
return response;
}
}
let redirectsRemaining = this._maxRedirects;
while (response.message.statusCode &&
HttpRedirectCodes.includes(response.message.statusCode) &&
this._allowRedirects &&
redirectsRemaining > 0) {
const redirectUrl = response.message.headers['location'];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
const parsedRedirectUrl = new URL(redirectUrl);
if (parsedUrl.protocol === 'https:' &&
parsedUrl.protocol !== parsedRedirectUrl.protocol &&
!this._allowRedirectDowngrade) {
throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
}
// we need to finish reading the response before reassigning response
// which will leak the open socket.
yield response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (const header in headers) {
// header names are case insensitive
if (header.toLowerCase() === 'authorization') {
delete headers[header];
}
}
}
// let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = yield this.requestRaw(info, data);
redirectsRemaining--;
}
if (!response.message.statusCode ||
!HttpResponseRetryCodes.includes(response.message.statusCode)) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
yield response.readBody();
yield this._performExponentialBackoff(numTries);
}
} while (numTries < maxTries);
return response;
});
}
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose() {
if (this._agent) {
this._agent.destroy();
}
this._disposed = true;
}
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info, data) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
function callbackForResult(err, res) {
if (err) {
reject(err);
}
else if (!res) {
// If `err` is not passed, then `res` must be passed.
reject(new Error('Unknown error'));
}
else {
resolve(res);
}
}
this.requestRawWithCallback(info, data, callbackForResult);
});
});
}
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info, data, onResult) {
if (typeof data === 'string') {
if (!info.options.headers) {
info.options.headers = {};
}
info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
let callbackCalled = false;
function handleResult(err, res) {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
}
const req = info.httpModule.request(info.options, (msg) => {
const res = new HttpClientResponse(msg);
handleResult(undefined, res);
});
let socket;
req.on('socket', sock => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
if (socket) {
socket.end();
}
handleResult(new Error(`Request timeout: ${info.options.path}`));
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err);
});
if (data && typeof data === 'string') {
req.write(data, 'utf8');
}
if (data && typeof data !== 'string') {
data.on('close', function () {
req.end();
});
data.pipe(req);
}
else {
req.end();
}
}
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl) {
const parsedUrl = new URL(serverUrl);
return this._getAgent(parsedUrl);
}
getAgentDispatcher(serverUrl) {
const parsedUrl = new URL(serverUrl);
const proxyUrl = pm.getProxyUrl(parsedUrl);
const useProxy = proxyUrl && proxyUrl.hostname;
if (!useProxy) {
return;
}
return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
}
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
const usingSsl = info.parsedUrl.protocol === 'https:';
info.httpModule = usingSsl ? https : http;
const defaultPort = usingSsl ? 443 : 80;
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port
? parseInt(info.parsedUrl.port)
: defaultPort;
info.options.path =
(info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method;
info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) {
info.options.headers['user-agent'] = this.userAgent;
}
info.options.agent = this._getAgent(info.parsedUrl);
// gives handlers an opportunity to participate
if (this.handlers) {
for (const handler of this.handlers) {
handler.prepareRequest(info.options);
}
}
return info;
}
_mergeHeaders(headers) {
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
const proxyUrl = pm.getProxyUrl(parsedUrl);
const useProxy = proxyUrl && proxyUrl.hostname;
if (this._keepAlive && useProxy) {
agent = this._proxyAgent;
}
if (this._keepAlive && !useProxy) {
agent = this._agent;
}
// if agent is already assigned use that agent.
if (agent) {
return agent;
}
const usingSsl = parsedUrl.protocol === 'https:';
let maxSockets = 100;
if (this.requestOptions) {
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
}
// This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
if (proxyUrl && proxyUrl.hostname) {
const agentOptions = {
maxSockets,
keepAlive: this._keepAlive,
proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
})), { host: proxyUrl.hostname, port: proxyUrl.port })
};
let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
agent = tunnelAgent(agentOptions);
this._proxyAgent = agent;
}
// if reusing agent across request and tunneling agent isn't assigned create a new agent
if (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
// if not using private agent and tunnel agent isn't setup then use global agent
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
}
return agent;
}
_getProxyAgentDispatcher(parsedUrl, proxyUrl) {
let proxyAgent;
if (this._keepAlive) {
proxyAgent = this._proxyAgentDispatcher;
}
// if agent is already assigned use that agent.
if (proxyAgent) {
return proxyAgent;
}
const usingSsl = parsedUrl.protocol === 'https:';
proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
token: `${proxyUrl.username}:${proxyUrl.password}`
})));
this._proxyAgentDispatcher = proxyAgent;
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
rejectUnauthorized: false
});
}
return proxyAgent;
}
_performExponentialBackoff(retryNumber) {
return __awaiter(this, void 0, void 0, function* () {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
});
}
_processResponse(res, options) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const statusCode = res.message.statusCode || 0;
const response = {
statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode === HttpCodes.NotFound) {
resolve(response);
}
// get the result from the body
function dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
const a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
let obj;
let contents;
try {
contents = yield res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, dateTimeDeserializer);
}
else {
obj = JSON.parse(contents);
}
response.result = obj;
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
}
else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
}
else {
msg = `Failed request: (${statusCode})`;
}
const err = new HttpClientError(msg, statusCode);
err.result = response.result;
reject(err);
}
else {
resolve(response);
}
}));
});
}
}
exports.HttpClient = HttpClient;
const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 19835:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkBypass = exports.getProxyUrl = void 0;
function getProxyUrl(reqUrl) {
const usingSsl = reqUrl.protocol === 'https:';
if (checkBypass(reqUrl)) {
return undefined;
}
const proxyVar = (() => {
if (usingSsl) {
return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
}
else {
return process.env['http_proxy'] || process.env['HTTP_PROXY'];
}
})();
if (proxyVar) {
try {
return new URL(proxyVar);
}
catch (_a) {
if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
return new URL(`http://${proxyVar}`);
}
}
else {
return undefined;
}
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
const reqHost = reqUrl.hostname;
if (isLoopbackAddress(reqHost)) {
return true;
}
const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
if (!noProxy) {
return false;
}
// Determine the request port
let reqPort;
if (reqUrl.port) {
reqPort = Number(reqUrl.port);
}
else if (reqUrl.protocol === 'http:') {
reqPort = 80;
}
else if (reqUrl.protocol === 'https:') {
reqPort = 443;
}
// Format the request hostname and hostname with port
const upperReqHosts = [reqUrl.hostname.toUpperCase()];
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
// Compare request host against noproxy
for (const upperNoProxyItem of noProxy
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
if (upperNoProxyItem === '*' ||
upperReqHosts.some(x => x === upperNoProxyItem ||
x.endsWith(`.${upperNoProxyItem}`) ||
(upperNoProxyItem.startsWith('.') &&
x.endsWith(`${upperNoProxyItem}`)))) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
function isLoopbackAddress(host) {
const hostLower = host.toLowerCase();
return (hostLower === 'localhost' ||
hostLower.startsWith('127.') ||
hostLower.startsWith('[::1]') ||
hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
}
//# sourceMappingURL=proxy.js.map
/***/ }),
/***/ 14018:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const AjvReference = Symbol.for('fastify.ajv-compiler.reference')
const ValidatorCompiler = __nccwpck_require__(57733)
const SerializerCompiler = __nccwpck_require__(35938)
function AjvCompiler (opts) {
const validatorPool = new Map()
const serializerPool = new Map()
if (opts && opts.jtdSerializer === true) {
return function buildSerializerFromPool (externalSchemas, serializerOpts) {
const uniqueAjvKey = getPoolKey({}, serializerOpts)
if (serializerPool.has(uniqueAjvKey)) {
return serializerPool.get(uniqueAjvKey)
}
const compiler = new SerializerCompiler(externalSchemas, serializerOpts)
const ret = compiler.buildSerializerFunction.bind(compiler)
serializerPool.set(uniqueAjvKey, ret)
return ret
}
}
return function buildCompilerFromPool (externalSchemas, options) {
const uniqueAjvKey = getPoolKey(externalSchemas, options.customOptions)
if (validatorPool.has(uniqueAjvKey)) {
return validatorPool.get(uniqueAjvKey)
}
const compiler = new ValidatorCompiler(externalSchemas, options)
const ret = compiler.buildValidatorFunction.bind(compiler)
validatorPool.set(uniqueAjvKey, ret)
if (options.customOptions.code !== undefined) {
ret[AjvReference] = compiler
}
return ret
}
}
function getPoolKey (externalSchemas, options) {
const externals = JSON.stringify(externalSchemas)
const ajvConfig = JSON.stringify(options)
return `${externals}${ajvConfig}`
}
module.exports = AjvCompiler
module.exports["default"] = AjvCompiler
module.exports.AjvCompiler = AjvCompiler
module.exports.AjvReference = AjvReference
module.exports.StandaloneValidator = __nccwpck_require__(65682)
/***/ }),
/***/ 79438:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastUri = __nccwpck_require__(49688)
module.exports = Object.freeze({
coerceTypes: 'array',
useDefaults: true,
removeAdditional: true,
uriResolver: fastUri,
addUsedSchema: false,
// Explicitly set allErrors to `false`.
// When set to `true`, a DoS attack is possible.
allErrors: false
})
/***/ }),
/***/ 35938:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const AjvJTD = __nccwpck_require__(96277)
const defaultAjvOptions = __nccwpck_require__(79438)
class SerializerCompiler {
constructor (externalSchemas, options) {
this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options))
/**
* https://ajv.js.org/json-type-definition.html#ref-form
* Unlike JSON Schema, JTD does not allow to reference:
* - any schema fragment other than root level definitions member
* - root of the schema - there is another way to define a self-recursive schema (see Example 2)
* - another schema file (but you can still combine schemas from multiple files using JavaScript).
*
* So we ignore the externalSchemas parameter.
*/
}
buildSerializerFunction ({ schema/*, method, url, httpStatus */ }) {
return this.ajv.compileSerializer(schema)
}
}
module.exports = SerializerCompiler
/***/ }),
/***/ 57733:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Ajv = (__nccwpck_require__(26905)["default"])
const AjvJTD = __nccwpck_require__(96277)
const defaultAjvOptions = __nccwpck_require__(79438)
class ValidatorCompiler {
constructor (externalSchemas, options) {
// This instance of Ajv is private
// it should not be customized or used
if (options.mode === 'JTD') {
this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions))
} else {
this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions))
}
let addFormatPlugin = true
if (options.plugins && options.plugins.length > 0) {
for (const plugin of options.plugins) {
if (Array.isArray(plugin)) {
addFormatPlugin = addFormatPlugin && plugin[0].name !== 'formatsPlugin'
plugin[0](this.ajv, plugin[1])
} else {
addFormatPlugin = addFormatPlugin && plugin.name !== 'formatsPlugin'
plugin(this.ajv)
}
}
}
if (addFormatPlugin) {
__nccwpck_require__(567)(this.ajv)
}
const sourceSchemas = Object.values(externalSchemas)
for (const extSchema of sourceSchemas) {
this.ajv.addSchema(extSchema)
}
}
buildValidatorFunction ({ schema/*, method, url, httpPart */ }) {
// Ajv does not support compiling two schemas with the same
// id inside the same instance. Therefore if we have already
// compiled the schema with the given id, we just return it.
if (schema.$id) {
const stored = this.ajv.getSchema(schema.$id)
if (stored) {
return stored
}
}
return this.ajv.compile(schema)
}
}
module.exports = ValidatorCompiler
/***/ }),
/***/ 26905:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = __nccwpck_require__(95826);
const draft7_1 = __nccwpck_require__(91934);
const discriminator_1 = __nccwpck_require__(47172);
const draft7MetaSchema = __nccwpck_require__(90686);
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
_addVocabularies() {
super._addVocabularies();
draft7_1.default.forEach((v) => this.addVocabulary(v));
if (this.opts.discriminator)
this.addKeyword(discriminator_1.default);
}
_addDefaultMetaSchema() {
super._addDefaultMetaSchema();
if (!this.opts.meta)
return;
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema;
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
}
defaultMeta() {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
}
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = Ajv;
var validate_1 = __nccwpck_require__(31564);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(79786);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
var validation_error_1 = __nccwpck_require__(55230);
Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } }));
var ref_error_1 = __nccwpck_require__(74874);
Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } }));
//# sourceMappingURL=ajv.js.map
/***/ }),
/***/ 11176:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
constructor(s) {
super();
if (!exports.IDENTIFIER.test(s))
throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return false;
}
get names() {
return { [this.str]: 1 };
}
}
exports.Name = Name;
class _Code extends _CodeOrName {
constructor(code) {
super();
this._items = typeof code === "string" ? [code] : code;
}
toString() {
return this.str;
}
emptyStr() {
if (this._items.length > 1)
return false;
const item = this._items[0];
return item === "" || item === '""';
}
get str() {
var _a;
return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
}
get names() {
var _a;
return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
if (c instanceof Name)
names[c.str] = (names[c.str] || 0) + 1;
return names;
}, {})));
}
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
const code = [strs[0]];
let i = 0;
while (i < args.length) {
addCodeArg(code, args[i]);
code.push(strs[++i]);
}
return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
const expr = [safeStringify(strs[0])];
let i = 0;
while (i < args.length) {
expr.push(plus);
addCodeArg(expr, args[i]);
expr.push(plus, safeStringify(strs[++i]));
}
optimize(expr);
return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
if (arg instanceof _Code)
code.push(...arg._items);
else if (arg instanceof Name)
code.push(arg);
else
code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
while (i < expr.length - 1) {
if (expr[i] === plus) {
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
if (res !== undefined) {
expr.splice(i - 1, 3, res);
continue;
}
expr[i++] = "+";
}
i++;
}
}
function mergeExprItems(a, b) {
if (b === '""')
return a;
if (a === '""')
return b;
if (typeof a == "string") {
if (b instanceof Name || a[a.length - 1] !== '"')
return;
if (typeof b != "string")
return `${a.slice(0, -1)}${b}"`;
if (b[0] === '"')
return a.slice(0, -1) + b.slice(1);
return;
}
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
return `"${a}${b.slice(1)}`;
return;
}
function strConcat(c1, c2) {
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
return typeof x == "number" || typeof x == "boolean" || x === null
? x
: safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
return JSON.stringify(x)
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
return new _Code(`${key}`);
}
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 79786:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = __nccwpck_require__(11176);
const scope_1 = __nccwpck_require__(34193);
var code_2 = __nccwpck_require__(11176);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return code_2._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return code_2.str; } }));
Object.defineProperty(exports, "strConcat", ({ enumerable: true, get: function () { return code_2.strConcat; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return code_2.nil; } }));
Object.defineProperty(exports, "getProperty", ({ enumerable: true, get: function () { return code_2.getProperty; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return code_2.stringify; } }));
Object.defineProperty(exports, "regexpCode", ({ enumerable: true, get: function () { return code_2.regexpCode; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return code_2.Name; } }));
var scope_2 = __nccwpck_require__(34193);
Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return scope_2.Scope; } }));
Object.defineProperty(exports, "ValueScope", ({ enumerable: true, get: function () { return scope_2.ValueScope; } }));
Object.defineProperty(exports, "ValueScopeName", ({ enumerable: true, get: function () { return scope_2.ValueScopeName; } }));
Object.defineProperty(exports, "varKinds", ({ enumerable: true, get: function () { return scope_2.varKinds; } }));
exports.operators = {
GT: new code_1._Code(">"),
GTE: new code_1._Code(">="),
LT: new code_1._Code("<"),
LTE: new code_1._Code("<="),
EQ: new code_1._Code("==="),
NEQ: new code_1._Code("!=="),
NOT: new code_1._Code("!"),
OR: new code_1._Code("||"),
AND: new code_1._Code("&&"),
ADD: new code_1._Code("+"),
};
class Node {
optimizeNodes() {
return this;
}
optimizeNames(_names, _constants) {
return this;
}
}
class Def extends Node {
constructor(varKind, name, rhs) {
super();
this.varKind = varKind;
this.name = name;
this.rhs = rhs;
}
render({ es5, _n }) {
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names, constants) {
if (!names[this.name.str])
return;
if (this.rhs)
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
}
class Assign extends Node {
constructor(lhs, rhs, sideEffects) {
super();
this.lhs = lhs;
this.rhs = rhs;
this.sideEffects = sideEffects;
}
render({ _n }) {
return `${this.lhs} = ${this.rhs};` + _n;
}
optimizeNames(names, constants) {
if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
return;
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
return addExprNames(names, this.rhs);
}
}
class AssignOp extends Assign {
constructor(lhs, op, rhs, sideEffects) {
super(lhs, rhs, sideEffects);
this.op = op;
}
render({ _n }) {
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
}
}
class Label extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
}
class Break extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
const label = this.label ? ` ${this.label}` : "";
return `break${label};` + _n;
}
}
class Throw extends Node {
constructor(error) {
super();
this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
}
class AnyCode extends Node {
constructor(code) {
super();
this.code = code;
}
render({ _n }) {
return `${this.code};` + _n;
}
optimizeNodes() {
return `${this.code}` ? this : undefined;
}
optimizeNames(names, constants) {
this.code = optimizeExpr(this.code, names, constants);
return this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
}
class ParentNode extends Node {
constructor(nodes = []) {
super();
this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i].optimizeNodes();
if (Array.isArray(n))
nodes.splice(i, 1, ...n);
else if (n)
nodes[i] = n;
else
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
optimizeNames(names, constants) {
const { nodes } = this;
let i = nodes.length;
while (i--) {
// iterating backwards improves 1-pass optimization
const n = nodes[i];
if (n.optimizeNames(names, constants))
continue;
subtractNames(names, n.names);
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
get names() {
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
}
}
class BlockNode extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
constructor(condition, nodes) {
super(nodes);
this.condition = condition;
}
render(opts) {
let code = `if(${this.condition})` + super.render(opts);
if (this.else)
code += "else " + this.else.render(opts);
return code;
}
optimizeNodes() {
super.optimizeNodes();
const cond = this.condition;
if (cond === true)
return this.nodes; // else is ignored here
let e = this.else;
if (e) {
const ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e) {
if (cond === false)
return e instanceof If ? e : e.nodes;
if (this.nodes.length)
return this;
return new If(not(cond), e instanceof If ? [e] : e.nodes);
}
if (cond === false || !this.nodes.length)
return undefined;
return this;
}
optimizeNames(names, constants) {
var _a;
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
if (!(super.optimizeNames(names, constants) || this.else))
return;
this.condition = optimizeExpr(this.condition, names, constants);
return this;
}
get names() {
const names = super.names;
addExprNames(names, this.condition);
if (this.else)
addNames(names, this.else.names);
return names;
}
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
constructor(iteration) {
super();
this.iteration = iteration;
}
render(opts) {
return `for(${this.iteration})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iteration = optimizeExpr(this.iteration, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
}
class ForRange extends For {
constructor(varKind, name, from, to) {
super();
this.varKind = varKind;
this.name = name;
this.from = from;
this.to = to;
}
render(opts) {
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
const { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
const names = addExprNames(super.names, this.from);
return addExprNames(names, this.to);
}
}
class ForIter extends For {
constructor(loop, varKind, name, iterable) {
super();
this.loop = loop;
this.varKind = varKind;
this.name = name;
this.iterable = iterable;
}
render(opts) {
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iterable = optimizeExpr(this.iterable, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
}
class Func extends BlockNode {
constructor(name, args, async) {
super();
this.name = name;
this.args = args;
this.async = async;
}
render(opts) {
const _async = this.async ? "async " : "";
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
}
}
Func.kind = "func";
class Return extends ParentNode {
render(opts) {
return "return " + super.render(opts);
}
}
Return.kind = "return";
class Try extends BlockNode {
render(opts) {
let code = "try" + super.render(opts);
if (this.catch)
code += this.catch.render(opts);
if (this.finally)
code += this.finally.render(opts);
return code;
}
optimizeNodes() {
var _a, _b;
super.optimizeNodes();
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
return this;
}
optimizeNames(names, constants) {
var _a, _b;
super.optimizeNames(names, constants);
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
return this;
}
get names() {
const names = super.names;
if (this.catch)
addNames(names, this.catch.names);
if (this.finally)
addNames(names, this.finally.names);
return names;
}
}
class Catch extends BlockNode {
constructor(error) {
super();
this.error = error;
}
render(opts) {
return `catch(${this.error})` + super.render(opts);
}
}
Catch.kind = "catch";
class Finally extends BlockNode {
render(opts) {
return "finally" + super.render(opts);
}
}
Finally.kind = "finally";
class CodeGen {
constructor(extScope, opts = {}) {
this._values = {};
this._blockStarts = [];
this._constants = {};
this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
this._extScope = extScope;
this._scope = new scope_1.Scope({ parent: extScope });
this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
// returns unique name in the internal scope
name(prefix) {
return this._scope.name(prefix);
}
// reserves unique name in the external scope
scopeName(prefix) {
return this._extScope.name(prefix);
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName, value) {
const name = this._extScope.value(prefixOrName, value);
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
vs.add(name);
return name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
const name = this._scope.toName(nameOrPrefix);
if (rhs !== undefined && constant)
this._constants[name.str] = rhs;
this._leafNode(new Def(varKind, name, rhs));
return name;
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
// `var` declaration with optional assignment
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
// assignment code
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
// `+=` code
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
// appends passed SafeExpr to code or executes Block
code(c) {
if (typeof c == "function")
c();
else if (c !== code_1.nil)
this._leafNode(new AnyCode(c));
return this;
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues) {
const code = ["{"];
for (const [key, value] of keyValues) {
if (code.length > 1)
code.push(",");
code.push(key);
if (key !== value || this.opts.es5) {
code.push(":");
(0, code_1.addCodeArg)(code, value);
}
}
code.push("}");
return new code_1._Code(code);
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition, thenBody, elseBody) {
this._blockNode(new If(condition));
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf();
}
else if (thenBody) {
this.code(thenBody).endIf();
}
else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body');
}
return this;
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition) {
return this._elseNode(new If(condition));
}
// `else` clause - only valid after `if` or `else if` clauses
else() {
return this._elseNode(new Else());
}
// end `if` statement (needed if gen.if was used only with condition)
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
this._blockNode(node);
if (forBody)
this.code(forBody).endFor();
return this;
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
// `for` statement for a range of values
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
const name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
this.var(name, (0, code_1._) `${arr}[${i}]`);
forBody(name);
});
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
}
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
// end `for` loop
endFor() {
return this._endBlockNode(For);
}
// `label` statement
label(label) {
return this._leafNode(new Label(label));
}
// `break` statement
break(label) {
return this._leafNode(new Break(label));
}
// `return` statement
return(value) {
const node = new Return();
this._blockNode(node);
this.code(value);
if (node.nodes.length !== 1)
throw new Error('CodeGen: "return" should have one node');
return this._endBlockNode(Return);
}
// `try` statement
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode)
throw new Error('CodeGen: "try" without "catch" and "finally"');
const node = new Try();
this._blockNode(node);
this.code(tryBody);
if (catchCode) {
const error = this.name("e");
this._currNode = node.catch = new Catch(error);
catchCode(error);
}
if (finallyCode) {
this._currNode = node.finally = new Finally();
this.code(finallyCode);
}
return this._endBlockNode(Catch, Finally);
}
// `throw` statement
throw(error) {
return this._leafNode(new Throw(error));
}
// start self-balancing block
block(body, nodeCount) {
this._blockStarts.push(this._nodes.length);
if (body)
this.code(body).endBlock(nodeCount);
return this;
}
// end the current self-balancing block
endBlock(nodeCount) {
const len = this._blockStarts.pop();
if (len === undefined)
throw new Error("CodeGen: not in self-balancing block");
const toClose = this._nodes.length - len;
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
}
this._nodes.length = len;
return this;
}
// `function` heading (or definition if funcBody is passed)
func(name, args = code_1.nil, async, funcBody) {
this._blockNode(new Func(name, args, async));
if (funcBody)
this.code(funcBody).endFunc();
return this;
}
// end function definition
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
while (n-- > 0) {
this._root.optimizeNodes();
this._root.optimizeNames(this._root.names, this._constants);
}
}
_leafNode(node) {
this._currNode.nodes.push(node);
return this;
}
_blockNode(node) {
this._currNode.nodes.push(node);
this._nodes.push(node);
}
_endBlockNode(N1, N2) {
const n = this._currNode;
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop();
return this;
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
const n = this._currNode;
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"');
}
this._currNode = n.else = node;
return this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
const ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
const ns = this._nodes;
ns[ns.length - 1] = node;
}
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) + (from[n] || 0);
return names;
}
function addExprNames(names, from) {
return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
if (expr instanceof code_1.Name)
return replaceName(expr);
if (!canOptimize(expr))
return expr;
return new code_1._Code(expr._items.reduce((items, c) => {
if (c instanceof code_1.Name)
c = replaceName(c);
if (c instanceof code_1._Code)
items.push(...c._items);
else
items.push(c);
return items;
}, []));
function replaceName(n) {
const c = constants[n.str];
if (c === undefined || names[n.str] !== 1)
return n;
delete names[n.str];
return c;
}
function canOptimize(e) {
return (e instanceof code_1._Code &&
e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
}
}
function subtractNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 34193:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = __nccwpck_require__(11176);
class ValueError extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`);
this.value = name.value;
}
}
var UsedValueState;
(function (UsedValueState) {
UsedValueState[UsedValueState["Started"] = 0] = "Started";
UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
const: new code_1.Name("const"),
let: new code_1.Name("let"),
var: new code_1.Name("var"),
};
class Scope {
constructor({ prefixes, parent } = {}) {
this._names = {};
this._prefixes = prefixes;
this._parent = parent;
}
toName(nameOrPrefix) {
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
}
name(prefix) {
return new code_1.Name(this._newName(prefix));
}
_newName(prefix) {
const ng = this._names[prefix] || this._nameGroup(prefix);
return `${prefix}${ng.index++}`;
}
_nameGroup(prefix) {
var _a, _b;
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
}
return (this._names[prefix] = { prefix, index: 0 });
}
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
constructor(prefix, nameStr) {
super(nameStr);
this.prefix = prefix;
}
setValue(value, { property, itemIndex }) {
this.value = value;
this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
}
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
constructor(opts) {
super(opts);
this._values = {};
this._scope = opts.scope;
this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
}
get() {
return this._scope;
}
name(prefix) {
return new ValueScopeName(prefix, this._newName(prefix));
}
value(nameOrPrefix, value) {
var _a;
if (value.ref === undefined)
throw new Error("CodeGen: ref must be passed in value");
const name = this.toName(nameOrPrefix);
const { prefix } = name;
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
let vs = this._values[prefix];
if (vs) {
const _name = vs.get(valueKey);
if (_name)
return _name;
}
else {
vs = this._values[prefix] = new Map();
}
vs.set(valueKey, name);
const s = this._scope[prefix] || (this._scope[prefix] = []);
const itemIndex = s.length;
s[itemIndex] = value.ref;
name.setValue(value, { property: prefix, itemIndex });
return name;
}
getValue(prefix, keyOrRef) {
const vs = this._values[prefix];
if (!vs)
return;
return vs.get(keyOrRef);
}
scopeRefs(scopeName, values = this._values) {
return this._reduceValues(values, (name) => {
if (name.scopePath === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return (0, code_1._) `${scopeName}${name.scopePath}`;
});
}
scopeCode(values = this._values, usedValues, getCode) {
return this._reduceValues(values, (name) => {
if (name.value === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return name.value.code;
}, usedValues, getCode);
}
_reduceValues(values, valueCode, usedValues = {}, getCode) {
let code = code_1.nil;
for (const prefix in values) {
const vs = values[prefix];
if (!vs)
continue;
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
vs.forEach((name) => {
if (nameSet.has(name))
return;
nameSet.set(name, UsedValueState.Started);
let c = valueCode(name);
if (c) {
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
}
else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
code = (0, code_1._) `${code}${c}${this.opts._n}`;
}
else {
throw new ValueError(name);
}
nameSet.set(name, UsedValueState.Completed);
});
}
return code;
}
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map
/***/ }),
/***/ 67216:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const names_1 = __nccwpck_require__(65763);
exports.keywordError = {
message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
message: ({ keyword, schemaType }) => schemaType
? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
: (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
addError(gen, errObj);
}
else {
returnErrors(it, (0, codegen_1._) `[${errObj}]`);
}
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
addError(gen, errObj);
if (!(compositeRule || allErrors)) {
returnErrors(it, names_1.default.vErrors);
}
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
gen.assign(names_1.default.errors, errsCount);
gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
/* istanbul ignore if */
if (errsCount === undefined)
throw new Error("ajv implementation error");
const err = gen.name("err");
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
if (it.opts.verbose) {
gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
gen.assign((0, codegen_1._) `${err}.data`, data);
}
});
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
const err = gen.const("err", errObj);
gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
const { gen, validateName, schemaEnv } = it;
if (schemaEnv.$async) {
gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
gen.return(false);
}
}
const E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
params: new codegen_1.Name("params"),
propertyName: new codegen_1.Name("propertyName"),
message: new codegen_1.Name("message"),
schema: new codegen_1.Name("schema"),
parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
const { createErrors } = cxt.it;
if (createErrors === false)
return (0, codegen_1._) `{}`;
return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
const { gen, it } = cxt;
const keyValues = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
];
extraErrorProps(cxt, error, keyValues);
return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
const instPath = instancePath
? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
: errorPath;
return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
if (schemaPath) {
schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
}
return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
const { keyword, data, schemaValue, it } = cxt;
const { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
}
if (opts.verbose) {
keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
}
if (propertyName)
keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ 40718:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = __nccwpck_require__(79786);
const validation_error_1 = __nccwpck_require__(55230);
const names_1 = __nccwpck_require__(65763);
const resolve_1 = __nccwpck_require__(70482);
const util_1 = __nccwpck_require__(570);
const validate_1 = __nccwpck_require__(31564);
class SchemaEnv {
constructor(env) {
var _a;
this.refs = {};
this.dynamicAnchors = {};
let schema;
if (typeof env.schema == "object")
schema = env.schema;
this.schema = env.schema;
this.schemaId = env.schemaId;
this.root = env.root || this;
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
this.schemaPath = env.schemaPath;
this.localRefs = env.localRefs;
this.meta = env.meta;
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
this.refs = {};
}
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
// TODO refactor - remove compilations
const _sch = getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
let _ValidationError;
if (sch.$async) {
_ValidationError = gen.scopeValue("Error", {
ref: validation_error_1.default,
code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
});
}
const validateName = gen.scopeName("validate");
sch.validateName = validateName;
const schemaCxt = {
gen,
allErrors: this.opts.allErrors,
data: names_1.default.data,
parentData: names_1.default.parentData,
parentDataProperty: names_1.default.parentDataProperty,
dataNames: [names_1.default.data],
dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
dataLevel: 0,
dataTypes: [],
definedProperties: new Set(),
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
: { ref: sch.schema }),
validateName,
ValidationError: _ValidationError,
schema: sch.schema,
schemaEnv: sch,
rootId,
baseId: sch.baseId || rootId,
schemaPath: codegen_1.nil,
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
errorPath: (0, codegen_1._) `""`,
opts: this.opts,
self: this,
};
let sourceCode;
try {
this._compilations.add(sch);
(0, validate_1.validateFunctionCode)(schemaCxt);
gen.optimize(this.opts.code.optimize);
// gen.optimize(1)
const validateCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
if (this.opts.code.process)
sourceCode = this.opts.code.process(sourceCode, sch);
// console.log("\n\n\n *** \n", sourceCode)
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
const validate = makeValidate(this, this.scope.get());
this.scope.value(validateName, { ref: validate });
validate.errors = null;
validate.schema = sch.schema;
validate.schemaEnv = sch;
if (sch.$async)
validate.$async = true;
if (this.opts.code.source === true) {
validate.source = { validateName, validateCode, scopeValues: gen._values };
}
if (this.opts.unevaluated) {
const { props, items } = schemaCxt;
validate.evaluated = {
props: props instanceof codegen_1.Name ? undefined : props,
items: items instanceof codegen_1.Name ? undefined : items,
dynamicProps: props instanceof codegen_1.Name,
dynamicItems: items instanceof codegen_1.Name,
};
if (validate.source)
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
}
sch.validate = validate;
return sch;
}
catch (e) {
delete sch.validate;
delete sch.validateName;
if (sourceCode)
this.logger.error("Error compiling schema, function code:", sourceCode);
// console.log("\n\n\n *** \n", sourceCode, this.opts)
throw e;
}
finally {
this._compilations.delete(sch);
}
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
var _a;
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
const schOrFunc = root.refs[ref];
if (schOrFunc)
return schOrFunc;
let _sch = resolve.call(this, root, ref);
if (_sch === undefined) {
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
const { schemaId } = this.opts;
if (schema)
_sch = new SchemaEnv({ schema, schemaId, root, baseId });
}
if (_sch === undefined)
return;
return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
return sch.schema;
return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
for (const sch of this._compilations) {
if (sameSchemaEnv(sch, schEnv))
return sch;
}
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
let sch;
while (typeof (sch = this.refs[ref]) == "string")
ref = sch;
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
const p = this.opts.uriResolver.parse(ref);
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root);
}
const id = (0, resolve_1.normalizeId)(refPath);
const schOrRef = this.refs[id] || this.schemas[id];
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef);
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
return;
return getJsonPointer.call(this, p, sch);
}
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
return;
if (!schOrRef.validate)
compileSchema.call(this, schOrRef);
if (id === (0, resolve_1.normalizeId)(ref)) {
const { schema } = schOrRef;
const { schemaId } = this.opts;
const schId = schema[schemaId];
if (schId)
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
return new SchemaEnv({ schema, schemaId, root, baseId });
}
return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
"properties",
"patternProperties",
"enum",
"dependencies",
"definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
var _a;
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
return;
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean")
return;
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
if (partSchema === undefined)
return;
schema = partSchema;
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId];
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
}
}
let env;
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
env = resolveSchema.call(this, root, $ref);
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const { schemaId } = this.opts;
env = env || new SchemaEnv({ schema, schemaId, root, baseId });
if (env.schema !== env.root.schema)
return env;
return undefined;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 41493:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const types_1 = __nccwpck_require__(82704);
const __1 = __nccwpck_require__(40718);
const codegen_1 = __nccwpck_require__(79786);
const ref_error_1 = __nccwpck_require__(74874);
const names_1 = __nccwpck_require__(65763);
const code_1 = __nccwpck_require__(56613);
const ref_1 = __nccwpck_require__(39948);
const type_1 = __nccwpck_require__(6796);
const parseJson_1 = __nccwpck_require__(36661);
const util_1 = __nccwpck_require__(570);
const timestamp_1 = __nccwpck_require__(94290);
const genParse = {
elements: parseElements,
values: parseValues,
discriminator: parseDiscriminator,
properties: parseProperties,
optionalProperties: parseProperties,
enum: parseEnum,
type: parseType,
ref: parseRef,
};
function compileParser(sch, definitions) {
const _sch = __1.getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
const parseName = gen.scopeName("parse");
const cxt = {
self: this,
gen,
schema: sch.schema,
schemaEnv: sch,
definitions,
data: names_1.default.data,
parseName,
char: gen.name("c"),
};
let sourceCode;
try {
this._compilations.add(sch);
sch.parseName = parseName;
parserFunction(cxt);
gen.optimize(this.opts.code.optimize);
const parseFuncCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
const parse = makeParse(this.scope.get());
this.scope.value(parseName, { ref: parse });
sch.parse = parse;
}
catch (e) {
if (sourceCode)
this.logger.error("Error compiling parser, function code:", sourceCode);
delete sch.parse;
delete sch.parseName;
throw e;
}
finally {
this._compilations.delete(sch);
}
return sch;
}
exports["default"] = compileParser;
const undef = (0, codegen_1._) `undefined`;
function parserFunction(cxt) {
const { gen, parseName, char } = cxt;
gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
gen.let(names_1.default.data);
gen.let(char);
gen.assign((0, codegen_1._) `${parseName}.message`, undef);
gen.assign((0, codegen_1._) `${parseName}.position`, undef);
gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`);
gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`);
parseCode(cxt);
skipWhitespace(cxt);
gen.if(names_1.default.jsonPart, () => {
gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
gen.return(names_1.default.data);
});
gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
jsonSyntaxError(cxt);
});
}
function parseCode(cxt) {
let form;
for (const key of types_1.jtdForms) {
if (key in cxt.schema) {
form = key;
break;
}
}
if (form)
parseNullable(cxt, genParse[form]);
else
parseEmpty(cxt);
}
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
function parseNullable(cxt, parseForm) {
const { gen, schema, data } = cxt;
if (!schema.nullable)
return parseForm(cxt);
tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
}
function parseElements(cxt) {
const { gen, schema, data } = cxt;
parseToken(cxt, "[");
const ix = gen.let("i", 0);
gen.assign(data, (0, codegen_1._) `[]`);
parseItems(cxt, "]", () => {
const el = gen.let("el");
parseCode({ ...cxt, schema: schema.elements, data: el });
gen.assign((0, codegen_1._) `${data}[${ix}++]`, el);
});
}
function parseValues(cxt) {
const { gen, schema, data } = cxt;
parseToken(cxt, "{");
gen.assign(data, (0, codegen_1._) `{}`);
parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
}
function parseItems(cxt, endToken, block) {
tryParseItems(cxt, endToken, block);
parseToken(cxt, endToken);
}
function tryParseItems(cxt, endToken, block) {
const { gen } = cxt;
gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
block();
tryParseToken(cxt, ",", () => gen.break(), hasItem);
});
function hasItem() {
tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
}
}
function parseKeyValue(cxt, schema) {
const { gen } = cxt;
const key = gen.let("key");
parseString({ ...cxt, data: key });
parseToken(cxt, ":");
parsePropertyValue(cxt, key, schema);
}
function parseDiscriminator(cxt) {
const { gen, data, schema } = cxt;
const { discriminator, mapping } = schema;
parseToken(cxt, "{");
gen.assign(data, (0, codegen_1._) `{}`);
const startPos = gen.const("pos", names_1.default.jsonPos);
const value = gen.let("value");
const tag = gen.let("tag");
tryParseItems(cxt, "}", () => {
const key = gen.let("key");
parseString({ ...cxt, data: key });
parseToken(cxt, ":");
gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => {
parseString({ ...cxt, data: tag });
gen.assign((0, codegen_1._) `${data}[${key}]`, tag);
gen.break();
}, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
);
});
gen.assign(names_1.default.jsonPos, startPos);
gen.if((0, codegen_1._) `${tag} === undefined`);
parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`);
for (const tagValue in mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
}
gen.else();
parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`);
gen.endIf();
}
function parseProperties(cxt) {
const { gen, data } = cxt;
parseToken(cxt, "{");
gen.assign(data, (0, codegen_1._) `{}`);
parseSchemaProperties(cxt);
}
function parseSchemaProperties(cxt, discriminator) {
const { gen, schema, data } = cxt;
const { properties, optionalProperties, additionalProperties } = schema;
parseItems(cxt, "}", () => {
const key = gen.let("key");
parseString({ ...cxt, data: key });
parseToken(cxt, ":");
gen.if(false);
parseDefinedProperty(cxt, key, properties);
parseDefinedProperty(cxt, key, optionalProperties);
if (discriminator) {
gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`);
const tag = gen.let("tag");
parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
}
gen.else();
if (additionalProperties) {
parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` });
}
else {
parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`);
}
gen.endIf();
});
if (properties) {
const hasProp = (0, code_1.hasPropFunc)(gen);
const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`));
gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`));
}
}
function parseDefinedProperty(cxt, key, schemas = {}) {
const { gen } = cxt;
for (const prop in schemas) {
gen.elseIf((0, codegen_1._) `${key} === ${prop}`);
parsePropertyValue(cxt, key, schemas[prop]);
}
}
function parsePropertyValue(cxt, key, schema) {
parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` });
}
function parseType(cxt) {
const { gen, schema, data, self } = cxt;
switch (schema.type) {
case "boolean":
parseBoolean(cxt);
break;
case "string":
parseString(cxt);
break;
case "timestamp": {
parseString(cxt);
const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
const { allowDate, parseDate } = self.opts;
const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`;
const fail = parseDate
? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`)
: notValid;
gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`));
break;
}
case "float32":
case "float64":
parseNumber(cxt);
break;
default: {
const t = schema.type;
if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
parseNumber(cxt, 16); // 2 ** 53 - max safe integer
if (t === "uint32") {
gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
}
}
else {
const [min, max, maxDigits] = type_1.intRange[t];
parseNumber(cxt, maxDigits);
gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
}
}
}
}
function parseString(cxt) {
parseToken(cxt, '"');
parseWith(cxt, parseJson_1.parseJsonString);
}
function parseEnum(cxt) {
const { gen, data, schema } = cxt;
const enumSch = schema.enum;
parseToken(cxt, '"');
// TODO loopEnum
gen.if(false);
for (const value of enumSch) {
const valueStr = JSON.stringify(value).slice(1); // remove starting quote
gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`);
gen.assign(data, (0, codegen_1.str) `${value}`);
gen.add(names_1.default.jsonPos, valueStr.length);
}
gen.else();
jsonSyntaxError(cxt);
gen.endIf();
}
function parseNumber(cxt, maxDigits) {
const { gen } = cxt;
skipWhitespace(cxt);
gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
}
function parseBooleanToken(bool, fail) {
return (cxt) => {
const { gen, data } = cxt;
tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
};
}
function parseRef(cxt) {
const { gen, self, definitions, schema, schemaEnv } = cxt;
const { ref } = schema;
const refSchema = definitions[ref];
if (!refSchema)
throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
if (!(0, ref_1.hasRef)(refSchema))
return parseCode({ ...cxt, schema: refSchema });
const { root } = schemaEnv;
const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
partialParse(cxt, getParser(gen, sch), true);
}
function getParser(gen, sch) {
return sch.parse
? gen.scopeValue("parse", { ref: sch.parse })
: (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
}
function parseEmpty(cxt) {
parseWith(cxt, parseJson_1.parseJson);
}
function parseWith(cxt, parseFunc, args) {
partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args);
}
function partialParse(cxt, parseFunc, args) {
const { gen, data } = cxt;
gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`);
gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`);
gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`));
}
function parseToken(cxt, tok) {
tryParseToken(cxt, tok, jsonSyntaxError);
}
function tryParseToken(cxt, tok, fail, success) {
const { gen } = cxt;
const n = tok.length;
skipWhitespace(cxt);
gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => {
gen.add(names_1.default.jsonPos, n);
success === null || success === void 0 ? void 0 : success(cxt);
}, () => fail(cxt));
}
function skipWhitespace({ gen, char: c }) {
gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
}
function jsonSlice(len) {
return len === 1
? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]`
: (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
}
function jsonSyntaxError(cxt) {
parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
}
function parsingError({ gen, parseName }, msg) {
gen.assign((0, codegen_1._) `${parseName}.message`, msg);
gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
gen.return(undef);
}
//# sourceMappingURL=parse.js.map
/***/ }),
/***/ 49310:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const types_1 = __nccwpck_require__(82704);
const __1 = __nccwpck_require__(40718);
const codegen_1 = __nccwpck_require__(79786);
const ref_error_1 = __nccwpck_require__(74874);
const names_1 = __nccwpck_require__(65763);
const code_1 = __nccwpck_require__(56613);
const ref_1 = __nccwpck_require__(39948);
const util_1 = __nccwpck_require__(570);
const quote_1 = __nccwpck_require__(20263);
const genSerialize = {
elements: serializeElements,
values: serializeValues,
discriminator: serializeDiscriminator,
properties: serializeProperties,
optionalProperties: serializeProperties,
enum: serializeString,
type: serializeType,
ref: serializeRef,
};
function compileSerializer(sch, definitions) {
const _sch = __1.getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
const serializeName = gen.scopeName("serialize");
const cxt = {
self: this,
gen,
schema: sch.schema,
schemaEnv: sch,
definitions,
data: names_1.default.data,
};
let sourceCode;
try {
this._compilations.add(sch);
sch.serializeName = serializeName;
gen.func(serializeName, names_1.default.data, false, () => {
gen.let(names_1.default.json, (0, codegen_1.str) ``);
serializeCode(cxt);
gen.return(names_1.default.json);
});
gen.optimize(this.opts.code.optimize);
const serializeFuncCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
const serialize = makeSerialize(this.scope.get());
this.scope.value(serializeName, { ref: serialize });
sch.serialize = serialize;
}
catch (e) {
if (sourceCode)
this.logger.error("Error compiling serializer, function code:", sourceCode);
delete sch.serialize;
delete sch.serializeName;
throw e;
}
finally {
this._compilations.delete(sch);
}
return sch;
}
exports["default"] = compileSerializer;
function serializeCode(cxt) {
let form;
for (const key of types_1.jtdForms) {
if (key in cxt.schema) {
form = key;
break;
}
}
serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
const { gen, schema, data } = cxt;
if (!schema.nullable)
return serializeForm(cxt);
gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
const { gen, schema, data } = cxt;
gen.add(names_1.default.json, (0, codegen_1.str) `[`);
const first = gen.let("first", true);
gen.forOf("el", data, (el) => {
addComma(cxt, first);
serializeCode({ ...cxt, schema: schema.elements, data: el });
});
gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
const { gen, schema, data } = cxt;
gen.add(names_1.default.json, (0, codegen_1.str) `{`);
const first = gen.let("first", true);
gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
const { gen, data } = cxt;
addComma(cxt, first);
serializeString({ ...cxt, data: key });
gen.add(names_1.default.json, (0, codegen_1.str) `:`);
const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
const { gen, schema, data } = cxt;
const { discriminator } = schema;
gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
serializeString({ ...cxt, data: tag });
gen.if(false);
for (const tagValue in schema.mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
const sch = schema.mapping[tagValue];
serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
}
gen.endIf();
gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
const { gen } = cxt;
gen.add(names_1.default.json, (0, codegen_1.str) `{`);
serializeSchemaProperties(cxt);
gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
const { gen, schema, data } = cxt;
const { properties, optionalProperties } = schema;
const props = keys(properties);
const optProps = keys(optionalProperties);
const allProps = allProperties(props.concat(optProps));
let first = !discriminator;
let firstProp;
for (const key of props) {
if (first)
first = false;
else
gen.add(names_1.default.json, (0, codegen_1.str) `,`);
serializeProperty(key, properties[key], keyValue(key));
}
if (first)
firstProp = gen.let("first", true);
for (const key of optProps) {
const value = keyValue(key);
gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => {
addComma(cxt, firstProp);
serializeProperty(key, optionalProperties[key], value);
});
}
if (schema.additionalProperties) {
gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)));
}
function keys(ps) {
return ps ? Object.keys(ps) : [];
}
function allProperties(ps) {
if (discriminator)
ps.push(discriminator);
if (new Set(ps).size !== ps.length) {
throw new Error("JTD: properties/optionalProperties/disciminator overlap");
}
return ps;
}
function keyValue(key) {
return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
}
function serializeProperty(key, propSchema, value) {
gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
serializeCode({ ...cxt, schema: propSchema, data: value });
}
function isAdditional(key, ps) {
return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
}
}
function serializeType(cxt) {
const { gen, schema, data } = cxt;
switch (schema.type) {
case "boolean":
gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
break;
case "string":
serializeString(cxt);
break;
case "timestamp":
gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
break;
default:
serializeNumber(cxt);
}
}
function serializeString({ gen, data }) {
gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data }) {
gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
}
function serializeRef(cxt) {
const { gen, self, data, definitions, schema, schemaEnv } = cxt;
const { ref } = schema;
const refSchema = definitions[ref];
if (!refSchema)
throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
if (!(0, ref_1.hasRef)(refSchema))
return serializeCode({ ...cxt, schema: refSchema });
const { root } = schemaEnv;
const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
return sch.serialize
? gen.scopeValue("serialize", { ref: sch.serialize })
: (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
if (first) {
gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
}
else {
gen.add(names_1.default.json, (0, codegen_1.str) `,`);
}
}
//# sourceMappingURL=serialize.js.map
/***/ }),
/***/ 82704:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.jtdForms = void 0;
exports.jtdForms = [
"elements",
"values",
"discriminator",
"properties",
"optionalProperties",
"enum",
"type",
"ref",
];
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 65763:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const names = {
// validation function arguments
data: new codegen_1.Name("data"), // data passed to validation function
// args passed from referencing schema
valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
// function scoped variables
vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
errors: new codegen_1.Name("errors"), // counter of validation errors
this: new codegen_1.Name("this"),
// "globals"
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
// JTD serialize/parse name for JSON string and position
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart"),
};
exports["default"] = names;
//# sourceMappingURL=names.js.map
/***/ }),
/***/ 74874:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const resolve_1 = __nccwpck_require__(70482);
class MissingRefError extends Error {
constructor(resolver, baseId, ref, msg) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
}
}
exports["default"] = MissingRefError;
//# sourceMappingURL=ref_error.js.map
/***/ }),
/***/ 70482:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = __nccwpck_require__(570);
const equal = __nccwpck_require__(28206);
const traverse = __nccwpck_require__(25158);
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
"type",
"format",
"pattern",
"maxLength",
"minLength",
"maxProperties",
"minProperties",
"maxItems",
"minItems",
"maximum",
"minimum",
"uniqueItems",
"multipleOf",
"required",
"enum",
"const",
]);
function inlineRef(schema, limit = true) {
if (typeof schema == "boolean")
return true;
if (limit === true)
return !hasRef(schema);
if (!limit)
return false;
return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
"$ref",
"$recursiveRef",
"$recursiveAnchor",
"$dynamicRef",
"$dynamicAnchor",
]);
function hasRef(schema) {
for (const key in schema) {
if (REF_KEYWORDS.has(key))
return true;
const sch = schema[key];
if (Array.isArray(sch) && sch.some(hasRef))
return true;
if (typeof sch == "object" && hasRef(sch))
return true;
}
return false;
}
function countKeys(schema) {
let count = 0;
for (const key in schema) {
if (key === "$ref")
return Infinity;
count++;
if (SIMPLE_INLINED.has(key))
continue;
if (typeof schema[key] == "object") {
(0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
}
if (count === Infinity)
return Infinity;
}
return count;
}
function getFullPath(resolver, id = "", normalize) {
if (normalize !== false)
id = normalizeId(id);
const p = resolver.parse(id);
return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
const serialized = resolver.serialize(p);
return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
id = normalizeId(id);
return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
if (typeof schema == "boolean")
return {};
const { schemaId, uriResolver } = this.opts;
const schId = normalizeId(schema[schemaId] || baseId);
const baseIds = { "": schId };
const pathPrefix = getFullPath(uriResolver, schId, false);
const localRefs = {};
const schemaRefs = new Set();
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined)
return;
const fullPath = pathPrefix + jsonPtr;
let innerBaseId = baseIds[parentJsonPtr];
if (typeof sch[schemaId] == "string")
innerBaseId = addRef.call(this, sch[schemaId]);
addAnchor.call(this, sch.$anchor);
addAnchor.call(this, sch.$dynamicAnchor);
baseIds[jsonPtr] = innerBaseId;
function addRef(ref) {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve;
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
if (schemaRefs.has(ref))
throw ambiguos(ref);
schemaRefs.add(ref);
let schOrRef = this.refs[ref];
if (typeof schOrRef == "string")
schOrRef = this.refs[schOrRef];
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref);
}
else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref);
localRefs[ref] = sch;
}
else {
this.refs[ref] = fullPath;
}
}
return ref;
}
function addAnchor(anchor) {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor))
throw new Error(`invalid anchor "${anchor}"`);
addRef.call(this, `#${anchor}`);
}
}
});
return localRefs;
function checkAmbiguosRef(sch1, sch2, ref) {
if (sch2 !== undefined && !equal(sch1, sch2))
throw ambiguos(ref);
}
function ambiguos(ref) {
return new Error(`reference "${ref}" resolves to more than one schema`);
}
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map
/***/ }),
/***/ 90451:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
const groups = {
number: { type: "number", rules: [] },
string: { type: "string", rules: [] },
array: { type: "array", rules: [] },
object: { type: "object", rules: [] },
};
return {
types: { ...groups, integer: true, boolean: true, null: true },
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
post: { rules: [] },
all: {},
keywords: {},
};
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map
/***/ }),
/***/ 570:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = __nccwpck_require__(79786);
const code_1 = __nccwpck_require__(11176);
// TODO refactor to use Set
function toHash(arr) {
const hash = {};
for (const item of arr)
hash[item] = true;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
if (typeof schema == "boolean")
return schema;
if (Object.keys(schema).length === 0)
return true;
checkUnknownRules(it, schema);
return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
const { opts, self } = it;
if (!opts.strictSchema)
return;
if (typeof schema === "boolean")
return;
const rules = self.RULES.keywords;
for (const key in schema) {
if (!rules[key])
checkStrictMode(it, `unknown keyword: "${key}"`);
}
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (rules[key])
return true;
return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (key !== "$ref" && RULES.all[key])
return true;
return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean")
return schema;
if (typeof schema == "string")
return (0, codegen_1._) `${schema}`;
}
return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
if (typeof str == "number")
return `${str}`;
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
if (Array.isArray(xs)) {
for (const x of xs)
f(x);
}
else {
f(xs);
}
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
return (gen, from, to, toName) => {
const res = to === undefined
? from
: to instanceof codegen_1.Name
? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
: from instanceof codegen_1.Name
? (mergeToName(gen, to, from), from)
: mergeValues(from, to);
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
};
}
exports.mergeEvaluated = {
props: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
}),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
if (from === true) {
gen.assign(to, true);
}
else {
gen.assign(to, (0, codegen_1._) `${to} || {}`);
setEvaluated(gen, to, from);
}
}),
mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
resultToName: evaluatedPropsToName,
}),
items: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
resultToName: (gen, items) => gen.var("items", items),
}),
};
function evaluatedPropsToName(gen, ps) {
if (ps === true)
return gen.var("props", true);
const props = gen.var("props", (0, codegen_1._) `{}`);
if (ps !== undefined)
setEvaluated(gen, props, ps);
return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
});
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
Type[Type["Num"] = 0] = "Num";
Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
// let path
if (dataProp instanceof codegen_1.Name) {
const isNumber = dataPropType === Type.Num;
return jsPropertySyntax
? isNumber
? (0, codegen_1._) `"[" + ${dataProp} + "]"`
: (0, codegen_1._) `"['" + ${dataProp} + "']"`
: isNumber
? (0, codegen_1._) `"/" + ${dataProp}`
: (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
}
return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
if (!mode)
return;
msg = `strict mode: ${msg}`;
if (mode === true)
throw new Error(msg);
it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map
/***/ }),
/***/ 30394:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
const group = self.RULES.types[type];
return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
var _a;
return (schema[rule.keyword] !== undefined ||
((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map
/***/ }),
/***/ 5477:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = __nccwpck_require__(67216);
const codegen_1 = __nccwpck_require__(79786);
const names_1 = __nccwpck_require__(65763);
const boolError = {
message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
const { gen, schema, validateName } = it;
if (schema === false) {
falseSchemaError(it, false);
}
else if (typeof schema == "object" && schema.$async === true) {
gen.return(names_1.default.data);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, null);
gen.return(true);
}
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
const { gen, schema } = it;
if (schema === false) {
gen.var(valid, false); // TODO var
falseSchemaError(it);
}
else {
gen.var(valid, true); // TODO var
}
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
const { gen, data } = it;
// TODO maybe some other interface should be used for non-keyword validation errors...
const cxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it,
};
(0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map
/***/ }),
/***/ 86777:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = __nccwpck_require__(90451);
const applicability_1 = __nccwpck_require__(30394);
const errors_1 = __nccwpck_require__(67216);
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
var DataType;
(function (DataType) {
DataType[DataType["Correct"] = 0] = "Correct";
DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
const types = getJSONTypes(schema.type);
const hasNull = types.includes("null");
if (hasNull) {
if (schema.nullable === false)
throw new Error("type: null contradicts nullable: false");
}
else {
if (!types.length && schema.nullable !== undefined) {
throw new Error('"nullable" cannot be used without "type"');
}
if (schema.nullable === true)
types.push("null");
}
return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
if (types.every(rules_1.isJSONType))
return types;
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
const { gen, data, opts } = it;
const coerceTo = coerceToTypes(types, opts.coerceTypes);
const checkTypes = types.length > 0 &&
!(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
gen.if(wrongType, () => {
if (coerceTo.length)
coerceData(it, types, coerceTo);
else
reportTypeError(it);
});
}
return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
return coerceTypes
? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
: [];
}
function coerceData(it, types, coerceTo) {
const { gen, data, opts } = it;
const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
if (opts.coerceTypes === "array") {
gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
.assign(data, (0, codegen_1._) `${data}[0]`)
.assign(dataType, (0, codegen_1._) `typeof ${data}`)
.if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
}
gen.if((0, codegen_1._) `${coerced} !== undefined`);
for (const t of coerceTo) {
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
coerceSpecificType(t);
}
}
gen.else();
reportTypeError(it);
gen.endIf();
gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
gen.assign(data, coerced);
assignParentData(it, coerced);
});
function coerceSpecificType(t) {
switch (t) {
case "string":
gen
.elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
.assign(coerced, (0, codegen_1._) `"" + ${data}`)
.elseIf((0, codegen_1._) `${data} === null`)
.assign(coerced, (0, codegen_1._) `""`);
return;
case "number":
gen
.elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "integer":
gen
.elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "boolean":
gen
.elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
.assign(coerced, false)
.elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
.assign(coerced, true);
return;
case "null":
gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
gen.assign(coerced, null);
return;
case "array":
gen
.elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
|| ${dataType} === "boolean" || ${data} === null`)
.assign(coerced, (0, codegen_1._) `[${data}]`);
}
}
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
// TODO use gen.property
gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
let cond;
switch (dataType) {
case "null":
return (0, codegen_1._) `${data} ${EQ} null`;
case "array":
cond = (0, codegen_1._) `Array.isArray(${data})`;
break;
case "object":
cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
break;
case "integer":
cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
break;
case "number":
cond = numCond();
break;
default:
return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
}
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
function numCond(_cond = codegen_1.nil) {
return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
}
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
if (dataTypes.length === 1) {
return checkDataType(dataTypes[0], data, strictNums, correct);
}
let cond;
const types = (0, util_1.toHash)(dataTypes);
if (types.array && types.object) {
const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
delete types.null;
delete types.array;
delete types.object;
}
else {
cond = codegen_1.nil;
}
if (types.number)
delete types.integer;
for (const t in types)
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
message: ({ schema }) => `must be ${schema}`,
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
const cxt = getTypeErrorContext(it);
(0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
const { gen, data, schema } = it;
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
return {
gen,
keyword: "type",
data,
schema: schema.type,
schemaCode,
schemaValue: schemaCode,
parentSchema: schema,
params: {},
it,
};
}
//# sourceMappingURL=dataType.js.map
/***/ }),
/***/ 97681:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.assignDefaults = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
function assignDefaults(it, ty) {
const { properties, items } = it.schema;
if (ty === "object" && properties) {
for (const key in properties) {
assignDefault(it, key, properties[key].default);
}
}
else if (ty === "array" && Array.isArray(items)) {
items.forEach((sch, i) => assignDefault(it, i, sch.default));
}
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
const { gen, compositeRule, data, opts } = it;
if (defaultValue === undefined)
return;
const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
if (compositeRule) {
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
return;
}
let condition = (0, codegen_1._) `${childData} === undefined`;
if (opts.useDefaults === "empty") {
condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
}
// `${childData} === undefined` +
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map
/***/ }),
/***/ 31564:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = __nccwpck_require__(5477);
const dataType_1 = __nccwpck_require__(86777);
const applicability_1 = __nccwpck_require__(30394);
const dataType_2 = __nccwpck_require__(86777);
const defaults_1 = __nccwpck_require__(97681);
const keyword_1 = __nccwpck_require__(84521);
const subschema_1 = __nccwpck_require__(19905);
const codegen_1 = __nccwpck_require__(79786);
const names_1 = __nccwpck_require__(65763);
const resolve_1 = __nccwpck_require__(70482);
const util_1 = __nccwpck_require__(570);
const errors_1 = __nccwpck_require__(67216);
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
topSchemaObjCode(it);
return;
}
}
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
if (opts.code.es5) {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
destructureValCxtES5(gen, opts);
gen.code(body);
});
}
else {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
}
}
function destructureValCxt(opts) {
return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
gen.if(names_1.default.valCxt, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
}, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
gen.var(names_1.default.rootData, names_1.default.data);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
});
}
function topSchemaObjCode(it) {
const { schema, opts, gen } = it;
validateFunction(it, () => {
if (opts.$comment && schema.$comment)
commentKeyword(it);
checkNoDefault(it);
gen.let(names_1.default.vErrors, null);
gen.let(names_1.default.errors, 0);
if (opts.unevaluated)
resetEvaluated(it);
typeAndKeywords(it);
returnResults(it);
});
return;
}
function resetEvaluated(it) {
// TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
const { gen, validateName } = it;
it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
const schId = typeof schema == "object" && schema[opts.schemaId];
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid);
return;
}
}
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (self.RULES.all[key])
return true;
return false;
}
function isSchemaObj(it) {
return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
const { schema, gen, opts } = it;
if (opts.$comment && schema.$comment)
commentKeyword(it);
updateContext(it);
checkAsyncSchema(it);
const errsCount = gen.const("_errs", names_1.default.errors);
typeAndKeywords(it, errsCount);
// TODO var
gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
(0, util_1.checkUnknownRules)(it);
checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
if (it.opts.jtd)
return schemaKeywords(it, [], false, errsCount);
const types = (0, dataType_1.getSchemaTypes)(it.schema);
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
const { schema, errSchemaPath, opts, self } = it;
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
}
}
function checkNoDefault(it) {
const { schema, opts } = it;
if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
}
}
function updateContext(it) {
const schId = it.schema[it.opts.schemaId];
if (schId)
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
if (it.schema.$async && !it.schemaEnv.$async)
throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
const msg = schema.$comment;
if (opts.$comment === true) {
gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
}
else if (typeof opts.$comment == "function") {
const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
}
}
function returnResults(it) {
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
if (schemaEnv.$async) {
// TODO assign unevaluated
gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
if (opts.unevaluated)
assignEvaluated(it);
gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
}
}
function assignEvaluated({ gen, evaluated, props, items }) {
if (props instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.props`, props);
if (items instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
const { gen, schema, data, allErrors, opts, self } = it;
const { RULES } = self;
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
return;
}
if (!opts.jtd)
checkStrictTypes(it, types);
gen.block(() => {
for (const group of RULES.rules)
groupKeywords(group);
groupKeywords(RULES.post);
});
function groupKeywords(group) {
if (!(0, applicability_1.shouldUseGroup)(schema, group))
return;
if (group.type) {
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
iterateKeywords(it, group);
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else();
(0, dataType_2.reportTypeError)(it);
}
gen.endIf();
}
else {
iterateKeywords(it, group);
}
// TODO make it "ok" call?
if (!allErrors)
gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
}
}
function iterateKeywords(it, group) {
const { gen, schema, opts: { useDefaults }, } = it;
if (useDefaults)
(0, defaults_1.assignDefaults)(it, group.type);
gen.block(() => {
for (const rule of group.rules) {
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type);
}
}
});
}
function checkStrictTypes(it, types) {
if (it.schemaEnv.meta || !it.opts.strictTypes)
return;
checkContextTypes(it, types);
if (!it.opts.allowUnionTypes)
checkMultipleTypes(it, types);
checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
if (!types.length)
return;
if (!it.dataTypes.length) {
it.dataTypes = types;
return;
}
types.forEach((t) => {
if (!includesType(it.dataTypes, t)) {
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
}
});
narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
}
}
function checkKeywordTypes(it, ts) {
const rules = it.self.RULES.all;
for (const keyword in rules) {
const rule = rules[keyword];
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
const { type } = rule.definition;
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
}
}
}
}
function hasApplicableType(schTs, kwdT) {
return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
const ts = [];
for (const t of it.dataTypes) {
if (includesType(withTypes, t))
ts.push(t);
else if (withTypes.includes("integer") && t === "number")
ts.push("integer");
}
it.dataTypes = ts;
}
function strictTypesError(it, msg) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
msg += ` at "${schemaPath}" (strictTypes)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
constructor(it, def, keyword) {
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
this.gen = it.gen;
this.allErrors = it.allErrors;
this.keyword = keyword;
this.data = it.data;
this.schema = it.schema[keyword];
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
this.schemaType = def.schemaType;
this.parentSchema = it.schema;
this.params = {};
this.it = it;
this.def = def;
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
}
else {
this.schemaCode = this.schemaValue;
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", names_1.default.errors);
}
}
result(condition, successAction, failAction) {
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
}
failResult(condition, successAction, failAction) {
this.gen.if(condition);
if (failAction)
failAction();
else
this.error();
if (successAction) {
this.gen.else();
successAction();
if (this.allErrors)
this.gen.endIf();
}
else {
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
}
pass(condition, failAction) {
this.failResult((0, codegen_1.not)(condition), undefined, failAction);
}
fail(condition) {
if (condition === undefined) {
this.error();
if (!this.allErrors)
this.gen.if(false); // this branch will be removed by gen.optimize
return;
}
this.gen.if(condition);
this.error();
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
fail$data(condition) {
if (!this.$data)
return this.fail(condition);
const { schemaCode } = this;
this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
}
error(append, errorParams, errorPaths) {
if (errorParams) {
this.setParams(errorParams);
this._error(append, errorPaths);
this.setParams({});
return;
}
this._error(append, errorPaths);
}
_error(append, errorPaths) {
;
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
}
$dataError() {
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
}
reset() {
if (this.errsCount === undefined)
throw new Error('add "trackErrors" to keyword definition');
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
}
ok(cond) {
if (!this.allErrors)
this.gen.if(cond);
}
setParams(obj, assign) {
if (assign)
Object.assign(this.params, obj);
else
this.params = obj;
}
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
this.gen.block(() => {
this.check$data(valid, $dataValid);
codeBlock();
});
}
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
if (!this.$data)
return;
const { gen, schemaCode, schemaType, def } = this;
gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
if (valid !== codegen_1.nil)
gen.assign(valid, true);
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data());
this.$dataError();
if (valid !== codegen_1.nil)
gen.assign(valid, false);
}
gen.else();
}
invalid$data() {
const { gen, schemaCode, schemaType, def, it } = this;
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
function wrong$DataType() {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof codegen_1.Name))
throw new Error("ajv implementation error");
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
}
return codegen_1.nil;
}
function invalid$DataSchema() {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
}
return codegen_1.nil;
}
}
subschema(appl, valid) {
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
(0, subschema_1.extendSubschemaMode)(subschema, appl);
const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
subschemaCode(nextContext, valid);
return nextContext;
}
mergeEvaluated(schemaCxt, toName) {
const { it, gen } = this;
if (!it.opts.unevaluated)
return;
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
}
}
mergeValidEvaluated(schemaCxt, valid) {
const { it, gen } = this;
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
return true;
}
}
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
const cxt = new KeywordCxt(it, def, keyword);
if ("code" in def) {
def.code(cxt, ruleType);
}
else if (cxt.$data && def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
else if ("macro" in def) {
(0, keyword_1.macroKeywordCode)(cxt, def);
}
else if (def.compile || def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
let jsonPointer;
let data;
if ($data === "")
return names_1.default.rootData;
if ($data[0] === "/") {
if (!JSON_POINTER.test($data))
throw new Error(`Invalid JSON-pointer: ${$data}`);
jsonPointer = $data;
data = names_1.default.rootData;
}
else {
const matches = RELATIVE_JSON_POINTER.exec($data);
if (!matches)
throw new Error(`Invalid JSON-pointer: ${$data}`);
const up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer === "#") {
if (up >= dataLevel)
throw new Error(errorMsg("property/index", up));
return dataPathArr[dataLevel - up];
}
if (up > dataLevel)
throw new Error(errorMsg("data", up));
data = dataNames[dataLevel - up];
if (!jsonPointer)
return data;
}
let expr = data;
const segments = jsonPointer.split("/");
for (const segment of segments) {
if (segment) {
data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
expr = (0, codegen_1._) `${expr} && ${data}`;
}
}
return expr;
function errorMsg(pointerType, up) {
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
}
}
exports.getData = getData;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 84521:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = __nccwpck_require__(79786);
const names_1 = __nccwpck_require__(65763);
const code_1 = __nccwpck_require__(56613);
const errors_1 = __nccwpck_require__(67216);
function macroKeywordCode(cxt, def) {
const { gen, keyword, schema, parentSchema, it } = cxt;
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
const schemaRef = useKeyword(gen, keyword, macroSchema);
if (it.opts.validateSchema !== false)
it.self.validateSchema(macroSchema, true);
const valid = gen.name("valid");
cxt.subschema({
schema: macroSchema,
schemaPath: codegen_1.nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true,
}, valid);
cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
var _a;
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
checkAsyncKeyword(it, def);
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
const validateRef = useKeyword(gen, keyword, validate);
const valid = gen.let("valid");
cxt.block$data(valid, validateKeyword);
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
function validateKeyword() {
if (def.errors === false) {
assignValid();
if (def.modifying)
modifyData(cxt);
reportErrs(() => cxt.error());
}
else {
const ruleErrs = def.async ? validateAsync() : validateSync();
if (def.modifying)
modifyData(cxt);
reportErrs(() => addErrs(cxt, ruleErrs));
}
}
function validateAsync() {
const ruleErrs = gen.let("ruleErrs", null);
gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
return ruleErrs;
}
function validateSync() {
const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
gen.assign(validateErrs, null);
assignValid(codegen_1.nil);
return validateErrs;
}
function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
const passSchema = !(("compile" in def && !$data) || def.schema === false);
gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
}
function reportErrs(errors) {
var _a;
gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
}
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
const { gen, data, it } = cxt;
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
const { gen } = cxt;
gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
gen
.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
(0, errors_1.extendErrors)(cxt);
}, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
if (def.async && !schemaEnv.$async)
throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
if (result === undefined)
throw new Error(`keyword "${keyword}" failed to compile`);
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
// TODO add tests
return (!schemaType.length ||
schemaType.some((st) => st === "array"
? Array.isArray(schema)
: st === "object"
? schema && typeof schema == "object" && !Array.isArray(schema)
: typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error");
}
const deps = def.dependencies;
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword]);
if (!valid) {
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors);
if (opts.validateSchema === "log")
self.logger.error(msg);
else
throw new Error(msg);
}
}
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map
/***/ }),
/***/ 19905:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
if (keyword !== undefined && schema !== undefined) {
throw new Error('both "keyword" and "schema" passed, only one allowed');
}
if (keyword !== undefined) {
const sch = it.schema[keyword];
return schemaProp === undefined
? {
schema: sch,
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
}
: {
schema: sch[schemaProp],
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
};
}
if (schema !== undefined) {
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath,
};
}
throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed');
}
const { gen } = it;
if (dataProp !== undefined) {
const { errorPath, dataPathArr, opts } = it;
const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
dataContextProps(nextData);
subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
}
if (data !== undefined) {
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
dataContextProps(nextData);
if (propertyName !== undefined)
subschema.propertyName = propertyName;
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes)
subschema.dataTypes = dataTypes;
function dataContextProps(_nextData) {
subschema.data = _nextData;
subschema.dataLevel = it.dataLevel + 1;
subschema.dataTypes = [];
it.definedProperties = new Set();
subschema.parentData = it.data;
subschema.dataNames = [...it.dataNames, _nextData];
}
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
if (compositeRule !== undefined)
subschema.compositeRule = compositeRule;
if (createErrors !== undefined)
subschema.createErrors = createErrors;
if (allErrors !== undefined)
subschema.allErrors = allErrors;
subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map
/***/ }),
/***/ 95826:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = __nccwpck_require__(31564);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(79786);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
const validation_error_1 = __nccwpck_require__(55230);
const ref_error_1 = __nccwpck_require__(74874);
const rules_1 = __nccwpck_require__(90451);
const compile_1 = __nccwpck_require__(40718);
const codegen_2 = __nccwpck_require__(79786);
const resolve_1 = __nccwpck_require__(70482);
const dataType_1 = __nccwpck_require__(86777);
const util_1 = __nccwpck_require__(570);
const $dataRefSchema = __nccwpck_require__(24624);
const uri_1 = __nccwpck_require__(97845);
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
"validate",
"serialize",
"parse",
"wrapper",
"root",
"schema",
"keyword",
"pattern",
"formats",
"validate$data",
"func",
"obj",
"Error",
]);
const removedOptions = {
errorDataPath: "",
format: "`validateFormats: false` can be used instead.",
nullable: '"nullable" keyword is supported by default.',
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
sourceCode: "Use option `code: {source: true}`",
strictDefaults: "It is default now, see option `strict`.",
strictKeywords: "It is default now, see option `strict`.",
uniqueItems: '"uniqueItems" keyword is always validated.',
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
cache: "Map is used as cache, schema object as key.",
serialize: "Map is used as cache, schema object as key.",
ajvErrors: "It is default now.",
};
const deprecatedOptions = {
ignoreKeywordsWithRef: "",
jsPropertySyntax: "",
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
return {
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
uriResolver: uriResolver,
};
}
class Ajv {
constructor(opts = {}) {
this.schemas = {};
this.refs = {};
this.formats = {};
this._compilations = new Set();
this._loading = {};
this._cache = new Map();
opts = this.opts = { ...opts, ...requiredOptions(opts) };
const { es5, lines } = this.opts.code;
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
this.logger = getLogger(opts.logger);
const formatOpt = opts.validateFormats;
opts.validateFormats = false;
this.RULES = (0, rules_1.getRules)();
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
this._metaOpts = getMetaSchemaOptions.call(this);
if (opts.formats)
addInitialFormats.call(this);
this._addVocabularies();
this._addDefaultMetaSchema();
if (opts.keywords)
addInitialKeywords.call(this, opts.keywords);
if (typeof opts.meta == "object")
this.addMetaSchema(opts.meta);
addInitialSchemas.call(this);
opts.validateFormats = formatOpt;
}
_addVocabularies() {
this.addKeyword("$async");
}
_addDefaultMetaSchema() {
const { $data, meta, schemaId } = this.opts;
let _dataRefSchema = $dataRefSchema;
if (schemaId === "id") {
_dataRefSchema = { ...$dataRefSchema };
_dataRefSchema.id = _dataRefSchema.$id;
delete _dataRefSchema.$id;
}
if (meta && $data)
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
}
defaultMeta() {
const { meta, schemaId } = this.opts;
return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
}
validate(schemaKeyRef, // key, ref or schema object
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
data // to be validated
) {
let v;
if (typeof schemaKeyRef == "string") {
v = this.getSchema(schemaKeyRef);
if (!v)
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
}
else {
v = this.compile(schemaKeyRef);
}
const valid = v(data);
if (!("$async" in v))
this.errors = v.errors;
return valid;
}
compile(schema, _meta) {
const sch = this._addSchema(schema, _meta);
return (sch.validate || this._compileSchemaEnv(sch));
}
compileAsync(schema, meta) {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function");
}
const { loadSchema } = this.opts;
return runCompileAsync.call(this, schema, meta);
async function runCompileAsync(_schema, _meta) {
await loadMetaSchema.call(this, _schema.$schema);
const sch = this._addSchema(_schema, _meta);
return sch.validate || _compileAsync.call(this, sch);
}
async function loadMetaSchema($ref) {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, { $ref }, true);
}
}
async function _compileAsync(sch) {
try {
return this._compileSchemaEnv(sch);
}
catch (e) {
if (!(e instanceof ref_error_1.default))
throw e;
checkLoaded.call(this, e);
await loadMissingSchema.call(this, e.missingSchema);
return _compileAsync.call(this, sch);
}
}
function checkLoaded({ missingSchema: ref, missingRef }) {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
}
}
async function loadMissingSchema(ref) {
const _schema = await _loadSchema.call(this, ref);
if (!this.refs[ref])
await loadMetaSchema.call(this, _schema.$schema);
if (!this.refs[ref])
this.addSchema(_schema, ref, meta);
}
async function _loadSchema(ref) {
const p = this._loading[ref];
if (p)
return p;
try {
return await (this._loading[ref] = loadSchema(ref));
}
finally {
delete this._loading[ref];
}
}
}
// Adds schema to the instance
addSchema(schema, // If array is passed, `key` will be ignored
key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
_meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
) {
if (Array.isArray(schema)) {
for (const sch of schema)
this.addSchema(sch, undefined, _meta, _validateSchema);
return this;
}
let id;
if (typeof schema === "object") {
const { schemaId } = this.opts;
id = schema[schemaId];
if (id !== undefined && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`);
}
}
key = (0, resolve_1.normalizeId)(key || id);
this._checkUnique(key);
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
return this;
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(schema, key, // schema key
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
) {
this.addSchema(schema, key, true, _validateSchema);
return this;
}
// Validate schema against its meta-schema
validateSchema(schema, throwOrLogError) {
if (typeof schema == "boolean")
return true;
let $schema;
$schema = schema.$schema;
if ($schema !== undefined && typeof $schema != "string") {
throw new Error("$schema must be a string");
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
if (!$schema) {
this.logger.warn("meta-schema not available");
this.errors = null;
return true;
}
const valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText();
if (this.opts.validateSchema === "log")
this.logger.error(message);
else
throw new Error(message);
}
return valid;
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema(keyRef) {
let sch;
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
keyRef = sch;
if (sch === undefined) {
const { schemaId } = this.opts;
const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
sch = compile_1.resolveSchema.call(this, root, keyRef);
if (!sch)
return;
this.refs[keyRef] = sch;
}
return (sch.validate || this._compileSchemaEnv(sch));
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef);
this._removeAllSchemas(this.refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas);
this._removeAllSchemas(this.refs);
this._cache.clear();
return this;
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef);
if (typeof sch == "object")
this._cache.delete(sch.schema);
delete this.schemas[schemaKeyRef];
delete this.refs[schemaKeyRef];
return this;
}
case "object": {
const cacheKey = schemaKeyRef;
this._cache.delete(cacheKey);
let id = schemaKeyRef[this.opts.schemaId];
if (id) {
id = (0, resolve_1.normalizeId)(id);
delete this.schemas[id];
delete this.refs[id];
}
return this;
}
default:
throw new Error("ajv.removeSchema: invalid parameter");
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions) {
for (const def of definitions)
this.addKeyword(def);
return this;
}
addKeyword(kwdOrDef, def // deprecated
) {
let keyword;
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef;
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
def.keyword = keyword;
}
}
else if (typeof kwdOrDef == "object" && def === undefined) {
def = kwdOrDef;
keyword = def.keyword;
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array");
}
}
else {
throw new Error("invalid addKeywords parameters");
}
checkKeyword.call(this, keyword, def);
if (!def) {
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
return this;
}
keywordMetaschema.call(this, def);
const definition = {
...def,
type: (0, dataType_1.getJSONTypes)(def.type),
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
};
(0, util_1.eachItem)(keyword, definition.type.length === 0
? (k) => addRule.call(this, k, definition)
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
return this;
}
getKeyword(keyword) {
const rule = this.RULES.all[keyword];
return typeof rule == "object" ? rule.definition : !!rule;
}
// Remove keyword
removeKeyword(keyword) {
// TODO return type should be Ajv
const { RULES } = this;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
if (i >= 0)
group.rules.splice(i, 1);
}
return this;
}
// Add format
addFormat(name, format) {
if (typeof format == "string")
format = new RegExp(format);
this.formats[name] = format;
return this;
}
errorsText(errors = this.errors, // optional array of validation errors
{ separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
) {
if (!errors || errors.length === 0)
return "No errors";
return errors
.map((e) => `${dataVar}${e.instancePath} ${e.message}`)
.reduce((text, msg) => text + separator + msg);
}
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
const rules = this.RULES.all;
metaSchema = JSON.parse(JSON.stringify(metaSchema));
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
let keywords = metaSchema;
for (const seg of segments)
keywords = keywords[seg];
for (const key in rules) {
const rule = rules[key];
if (typeof rule != "object")
continue;
const { $data } = rule.definition;
const schema = keywords[key];
if ($data && schema)
keywords[key] = schemaOrData(schema);
}
}
return metaSchema;
}
_removeAllSchemas(schemas, regex) {
for (const keyRef in schemas) {
const sch = schemas[keyRef];
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef];
}
else if (sch && !sch.meta) {
this._cache.delete(sch.schema);
delete schemas[keyRef];
}
}
}
}
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
let id;
const { schemaId } = this.opts;
if (typeof schema == "object") {
id = schema[schemaId];
}
else {
if (this.opts.jtd)
throw new Error("schema must be object");
else if (typeof schema != "boolean")
throw new Error("schema must be object or boolean");
}
let sch = this._cache.get(schema);
if (sch !== undefined)
return sch;
baseId = (0, resolve_1.normalizeId)(id || baseId);
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
this._cache.set(sch.schema, sch);
if (addSchema && !baseId.startsWith("#")) {
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
if (baseId)
this._checkUnique(baseId);
this.refs[baseId] = sch;
}
if (validateSchema)
this.validateSchema(schema, true);
return sch;
}
_checkUnique(id) {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`);
}
}
_compileSchemaEnv(sch) {
if (sch.meta)
this._compileMetaSchema(sch);
else
compile_1.compileSchema.call(this, sch);
/* istanbul ignore if */
if (!sch.validate)
throw new Error("ajv implementation error");
return sch.validate;
}
_compileMetaSchema(sch) {
const currentOpts = this.opts;
this.opts = this._metaOpts;
try {
compile_1.compileSchema.call(this, sch);
}
finally {
this.opts = currentOpts;
}
}
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports["default"] = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
for (const key in checkOpts) {
const opt = key;
if (opt in options)
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
}
}
function getSchEnv(keyRef) {
keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
const optsSchemas = this.opts.schemas;
if (!optsSchemas)
return;
if (Array.isArray(optsSchemas))
this.addSchema(optsSchemas);
else
for (const key in optsSchemas)
this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (const name in this.opts.formats) {
const format = this.opts.formats[name];
if (format)
this.addFormat(name, format);
}
}
function addInitialKeywords(defs) {
if (Array.isArray(defs)) {
this.addVocabulary(defs);
return;
}
this.logger.warn("keywords option as map is deprecated, pass array");
for (const keyword in defs) {
const def = defs[keyword];
if (!def.keyword)
def.keyword = keyword;
this.addKeyword(def);
}
}
function getMetaSchemaOptions() {
const metaOpts = { ...this.opts };
for (const opt of META_IGNORE_OPTIONS)
delete metaOpts[opt];
return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
if (logger === false)
return noLogs;
if (logger === undefined)
return console;
if (logger.log && logger.warn && logger.error)
return logger;
throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
const { RULES } = this;
(0, util_1.eachItem)(keyword, (kwd) => {
if (RULES.keywords[kwd])
throw new Error(`Keyword ${kwd} is already defined`);
if (!KEYWORD_NAME.test(kwd))
throw new Error(`Keyword ${kwd} has invalid name`);
});
if (!def)
return;
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function');
}
}
function addRule(keyword, definition, dataType) {
var _a;
const post = definition === null || definition === void 0 ? void 0 : definition.post;
if (dataType && post)
throw new Error('keyword with "post" flag cannot have "type"');
const { RULES } = this;
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.rules.push(ruleGroup);
}
RULES.keywords[keyword] = true;
if (!definition)
return;
const rule = {
keyword,
definition: {
...definition,
type: (0, dataType_1.getJSONTypes)(definition.type),
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
},
};
if (definition.before)
addBeforeRule.call(this, ruleGroup, rule, definition.before);
else
ruleGroup.rules.push(rule);
RULES.all[keyword] = rule;
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule);
}
else {
ruleGroup.rules.push(rule);
this.logger.warn(`rule ${before} is not defined`);
}
}
function keywordMetaschema(def) {
let { metaSchema } = def;
if (metaSchema === undefined)
return;
if (def.$data && this.opts.$data)
metaSchema = schemaOrData(metaSchema);
def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 96277:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = __nccwpck_require__(95826);
const jtd_1 = __nccwpck_require__(32727);
const jtd_schema_1 = __nccwpck_require__(45129);
const serialize_1 = __nccwpck_require__(49310);
const parse_1 = __nccwpck_require__(41493);
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
constructor(opts = {}) {
super({
...opts,
jtd: true,
});
}
_addVocabularies() {
super._addVocabularies();
this.addVocabulary(jtd_1.default);
}
_addDefaultMetaSchema() {
super._addDefaultMetaSchema();
if (!this.opts.meta)
return;
this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
}
defaultMeta() {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
}
compileSerializer(schema) {
const sch = this._addSchema(schema);
return sch.serialize || this._compileSerializer(sch);
}
compileParser(schema) {
const sch = this._addSchema(schema);
return (sch.parse || this._compileParser(sch));
}
_compileSerializer(sch) {
serialize_1.default.call(this, sch, sch.schema.definitions || {});
/* istanbul ignore if */
if (!sch.serialize)
throw new Error("ajv implementation error");
return sch.serialize;
}
_compileParser(sch) {
parse_1.default.call(this, sch, sch.schema.definitions || {});
/* istanbul ignore if */
if (!sch.parse)
throw new Error("ajv implementation error");
return sch.parse;
}
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = Ajv;
var validate_1 = __nccwpck_require__(31564);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(79786);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
var validation_error_1 = __nccwpck_require__(55230);
Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } }));
var ref_error_1 = __nccwpck_require__(74874);
Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } }));
//# sourceMappingURL=jtd.js.map
/***/ }),
/***/ 45129:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const shared = (root) => {
const sch = {
nullable: { type: "boolean" },
metadata: {
optionalProperties: {
union: { elements: { ref: "schema" } },
},
additionalProperties: true,
},
};
if (root)
sch.definitions = { values: { ref: "schema" } };
return sch;
};
const emptyForm = (root) => ({
optionalProperties: shared(root),
});
const refForm = (root) => ({
properties: {
ref: { type: "string" },
},
optionalProperties: shared(root),
});
const typeForm = (root) => ({
properties: {
type: {
enum: [
"boolean",
"timestamp",
"string",
"float32",
"float64",
"int8",
"uint8",
"int16",
"uint16",
"int32",
"uint32",
],
},
},
optionalProperties: shared(root),
});
const enumForm = (root) => ({
properties: {
enum: { elements: { type: "string" } },
},
optionalProperties: shared(root),
});
const elementsForm = (root) => ({
properties: {
elements: { ref: "schema" },
},
optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
properties: {
properties: { values: { ref: "schema" } },
},
optionalProperties: {
optionalProperties: { values: { ref: "schema" } },
additionalProperties: { type: "boolean" },
...shared(root),
},
});
const optionalPropertiesForm = (root) => ({
properties: {
optionalProperties: { values: { ref: "schema" } },
},
optionalProperties: {
additionalProperties: { type: "boolean" },
...shared(root),
},
});
const discriminatorForm = (root) => ({
properties: {
discriminator: { type: "string" },
mapping: {
values: {
metadata: {
union: [propertiesForm(false), optionalPropertiesForm(false)],
},
},
},
},
optionalProperties: shared(root),
});
const valuesForm = (root) => ({
properties: {
values: { ref: "schema" },
},
optionalProperties: shared(root),
});
const schema = (root) => ({
metadata: {
union: [
emptyForm,
refForm,
typeForm,
enumForm,
elementsForm,
propertiesForm,
optionalPropertiesForm,
discriminatorForm,
valuesForm,
].map((s) => s(root)),
},
});
const jtdMetaSchema = {
definitions: {
schema: schema(false),
},
...schema(true),
};
exports["default"] = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map
/***/ }),
/***/ 42481:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://github.com/ajv-validator/ajv/issues/889
const equal = __nccwpck_require__(28206);
equal.code = 'require("ajv/dist/runtime/equal").default';
exports["default"] = equal;
//# sourceMappingURL=equal.js.map
/***/ }),
/***/ 36661:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
let endPos;
parseJson.message = undefined;
let matches;
if (pos)
s = s.slice(pos);
try {
parseJson.position = pos + s.length;
return JSON.parse(s);
}
catch (e) {
matches = rxParseJson.exec(e.message);
if (!matches) {
parseJson.message = "unexpected end";
return undefined;
}
endPos = +matches[1];
const c = s[endPos];
s = s.slice(0, endPos);
parseJson.position = pos + endPos;
try {
return JSON.parse(s);
}
catch (e1) {
parseJson.message = `unexpected token ${c}`;
return undefined;
}
}
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
let numStr = "";
let c;
parseJsonNumber.message = undefined;
if (s[pos] === "-") {
numStr += "-";
pos++;
}
if (s[pos] === "0") {
numStr += "0";
pos++;
}
else {
if (!parseDigits(maxDigits)) {
errorMessage();
return undefined;
}
}
if (maxDigits) {
parseJsonNumber.position = pos;
return +numStr;
}
if (s[pos] === ".") {
numStr += ".";
pos++;
if (!parseDigits()) {
errorMessage();
return undefined;
}
}
if (((c = s[pos]), c === "e" || c === "E")) {
numStr += "e";
pos++;
if (((c = s[pos]), c === "+" || c === "-")) {
numStr += c;
pos++;
}
if (!parseDigits()) {
errorMessage();
return undefined;
}
}
parseJsonNumber.position = pos;
return +numStr;
function parseDigits(maxLen) {
let digit = false;
while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
digit = true;
numStr += c;
pos++;
}
return digit;
}
function errorMessage() {
parseJsonNumber.position = pos;
parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
}
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
b: "\b",
f: "\f",
n: "\n",
r: "\r",
t: "\t",
'"': '"',
"/": "/",
"\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
let str = "";
let c;
parseJsonString.message = undefined;
// eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
while (true) {
c = s[pos++];
if (c === '"')
break;
if (c === "\\") {
c = s[pos];
if (c in escapedChars) {
str += escapedChars[c];
pos++;
}
else if (c === "u") {
pos++;
let count = 4;
let code = 0;
while (count--) {
code <<= 4;
c = s[pos];
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (c === undefined) {
errorMessage("unexpected end");
return undefined;
}
c = c.toLowerCase();
if (c >= "a" && c <= "f") {
code += c.charCodeAt(0) - CODE_A + 10;
}
else if (c >= "0" && c <= "9") {
code += c.charCodeAt(0) - CODE_0;
}
else {
errorMessage(`unexpected token ${c}`);
return undefined;
}
pos++;
}
str += String.fromCharCode(code);
}
else {
errorMessage(`unexpected token ${c}`);
return undefined;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
}
else if (c === undefined) {
errorMessage("unexpected end");
return undefined;
}
else {
if (c.charCodeAt(0) >= 0x20) {
str += c;
}
else {
errorMessage(`unexpected token ${c}`);
return undefined;
}
}
}
parseJsonString.position = pos;
return str;
function errorMessage(msg) {
parseJsonString.position = pos;
parseJsonString.message = msg;
}
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map
/***/ }),
/***/ 20263:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const rxEscapable =
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
"\b": "\\b",
"\t": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\",
};
function quote(s) {
rxEscapable.lastIndex = 0;
return ('"' +
(rxEscapable.test(s)
? s.replace(rxEscapable, (a) => {
const c = escaped[a];
return typeof c === "string"
? c
: "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
})
: s) +
'"');
}
exports["default"] = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map
/***/ }),
/***/ 94290:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
// http://tools.ietf.org/html/rfc3339#section-5.6
const dt = str.split(DT_SEPARATOR);
return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
(allowDate && dt.length === 1 && validDate(dt[0])));
}
exports["default"] = validTimestamp;
function validDate(str) {
const matches = DATE.exec(str);
if (!matches)
return false;
const y = +matches[1];
const m = +matches[2];
const d = +matches[3];
return (m >= 1 &&
m <= 12 &&
d >= 1 &&
(d <= DAYS[m] ||
// leap year: https://tools.ietf.org/html/rfc3339#appendix-C
(m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
const matches = TIME.exec(str);
if (!matches)
return false;
const hr = +matches[1];
const min = +matches[2];
const sec = +matches[3];
const tzH = +(matches[4] || 0);
const tzM = +(matches[5] || 0);
return ((hr <= 23 && min <= 59 && sec <= 59) ||
// leap second
(hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map
/***/ }),
/***/ 61360:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
const len = str.length;
let length = 0;
let pos = 0;
let value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 0xd800 && value <= 0xdbff && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos);
if ((value & 0xfc00) === 0xdc00)
pos++; // low surrogate
}
}
return length;
}
exports["default"] = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map
/***/ }),
/***/ 97845:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const uri = __nccwpck_require__(70020);
uri.code = 'require("ajv/dist/runtime/uri").default';
exports["default"] = uri;
//# sourceMappingURL=uri.js.map
/***/ }),
/***/ 55230:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class ValidationError extends Error {
constructor(errors) {
super("validation failed");
this.errors = errors;
this.ajv = this.validation = true;
}
}
exports["default"] = ValidationError;
//# sourceMappingURL=validation_error.js.map
/***/ }),
/***/ 94883:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const scope_1 = __nccwpck_require__(34193);
const code_1 = __nccwpck_require__(11176);
function standaloneCode(ajv, refsOrFunc) {
if (!ajv.opts.code.source) {
throw new Error("moduleCode: ajv instance must have code.source option");
}
const { _n } = ajv.scope.opts;
return typeof refsOrFunc == "function"
? funcExportCode(refsOrFunc.source)
: refsOrFunc !== undefined
? multiExportsCode(refsOrFunc, getValidate)
: multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
function getValidate(id) {
const v = ajv.getSchema(id);
if (!v)
throw new Error(`moduleCode: no schema with id ${id}`);
return v;
}
function funcExportCode(source) {
const usedValues = {};
const n = source === null || source === void 0 ? void 0 : source.validateName;
const vCode = validateCode(usedValues, source);
if (ajv.opts.code.esm) {
// Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
}
return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
}
function multiExportsCode(schemas, getValidateFunc) {
var _a;
const usedValues = {};
let code = (0, code_1._) `"use strict";`;
for (const name in schemas) {
const v = getValidateFunc(schemas[name]);
if (v) {
const vCode = validateCode(usedValues, v.source);
const exportSyntax = ajv.opts.code.esm
? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
: (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
}
}
return `${code}`;
}
function validateCode(usedValues, s) {
if (!s)
throw new Error('moduleCode: function does not have "source" property');
if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
return code_1.nil;
setUsedState(s.validateName, scope_1.UsedValueState.Started);
const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
function refValidateCode(n) {
var _a;
const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
if (n.prefix === "validate" && typeof vRef == "function") {
const v = vRef;
return validateCode(usedValues, v.source);
}
else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
const { validate, validateName } = vRef;
if (!validateName)
throw new Error("ajv internal error");
const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
if (usedState(validateName) === scope_1.UsedValueState.Started)
return wrapper;
const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
return (0, code_1._) `${wrapper}${_n}${vCode}`;
}
return undefined;
}
function usedState(name) {
var _a;
return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
}
function setUsedState(name, state) {
const { prefix } = name;
const names = (usedValues[prefix] = usedValues[prefix] || new Map());
names.set(name, state);
}
}
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = standaloneCode;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 19776:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateAdditionalItems = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "additionalItems",
type: "array",
schemaType: ["boolean", "object"],
before: "uniqueItems",
error,
code(cxt) {
const { parentSchema, it } = cxt;
const { items } = parentSchema;
if (!Array.isArray(items)) {
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
return;
}
validateAdditionalItems(cxt, items);
},
};
function validateAdditionalItems(cxt, items) {
const { gen, schema, data, keyword, it } = cxt;
it.items = true;
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
if (schema === false) {
cxt.setParams({ len: items.length });
cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
}
else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
cxt.ok(valid);
}
function validateItems(valid) {
gen.forRange("i", items.length, len, (i) => {
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
if (!it.allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
});
}
}
exports.validateAdditionalItems = validateAdditionalItems;
exports["default"] = def;
//# sourceMappingURL=additionalItems.js.map
/***/ }),
/***/ 43160:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const names_1 = __nccwpck_require__(65763);
const util_1 = __nccwpck_require__(570);
const error = {
message: "must NOT have additional properties",
params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
keyword: "additionalProperties",
type: ["object"],
schemaType: ["boolean", "object"],
allowUndefined: true,
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
/* istanbul ignore if */
if (!errsCount)
throw new Error("ajv implementation error");
const { allErrors, opts } = it;
it.props = true;
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
return;
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
checkAdditionalProperties();
cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
function checkAdditionalProperties() {
gen.forIn("key", data, (key) => {
if (!props.length && !patProps.length)
additionalPropertyCode(key);
else
gen.if(isAdditional(key), () => additionalPropertyCode(key));
});
}
function isAdditional(key) {
let definedProp;
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
}
else if (props.length) {
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
}
else {
definedProp = codegen_1.nil;
}
if (patProps.length) {
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
}
return (0, codegen_1.not)(definedProp);
}
function deleteAdditional(key) {
gen.code((0, codegen_1._) `delete ${data}[${key}]`);
}
function additionalPropertyCode(key) {
if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
deleteAdditional(key);
return;
}
if (schema === false) {
cxt.setParams({ additionalProperty: key });
cxt.error();
if (!allErrors)
gen.break();
return;
}
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.name("valid");
if (opts.removeAdditional === "failing") {
applyAdditionalSchema(key, valid, false);
gen.if((0, codegen_1.not)(valid), () => {
cxt.reset();
deleteAdditional(key);
});
}
else {
applyAdditionalSchema(key, valid);
if (!allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
}
}
function applyAdditionalSchema(key, valid, errors) {
const subschema = {
keyword: "additionalProperties",
dataProp: key,
dataPropType: util_1.Type.Str,
};
if (errors === false) {
Object.assign(subschema, {
compositeRule: true,
createErrors: false,
allErrors: false,
});
}
cxt.subschema(subschema, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=additionalProperties.js.map
/***/ }),
/***/ 87735:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(570);
const def = {
keyword: "allOf",
schemaType: "array",
code(cxt) {
const { gen, schema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const valid = gen.name("valid");
schema.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
cxt.ok(valid);
cxt.mergeEvaluated(schCxt);
});
},
};
exports["default"] = def;
//# sourceMappingURL=allOf.js.map
/***/ }),
/***/ 74712:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const def = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in anyOf" },
};
exports["default"] = def;
//# sourceMappingURL=anyOf.js.map
/***/ }),
/***/ 26188:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: ({ params: { min, max } }) => max === undefined
? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
: (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
keyword: "contains",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
let min;
let max;
const { minContains, maxContains } = parentSchema;
if (it.opts.next) {
min = minContains === undefined ? 1 : minContains;
max = maxContains;
}
else {
min = 1;
}
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
cxt.setParams({ min, max });
if (max === undefined && min === 0) {
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
return;
}
if (max !== undefined && min > max) {
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
cxt.fail();
return;
}
if ((0, util_1.alwaysValidSchema)(it, schema)) {
let cond = (0, codegen_1._) `${len} >= ${min}`;
if (max !== undefined)
cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
cxt.pass(cond);
return;
}
it.items = true;
const valid = gen.name("valid");
if (max === undefined && min === 1) {
validateItems(valid, () => gen.if(valid, () => gen.break()));
}
else if (min === 0) {
gen.let(valid, true);
if (max !== undefined)
gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
}
else {
gen.let(valid, false);
validateItemsWithCount();
}
cxt.result(valid, () => cxt.reset());
function validateItemsWithCount() {
const schValid = gen.name("_valid");
const count = gen.let("count", 0);
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
}
function validateItems(_valid, block) {
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword: "contains",
dataProp: i,
dataPropType: util_1.Type.Num,
compositeRule: true,
}, _valid);
block();
});
}
function checkLimits(count) {
gen.code((0, codegen_1._) `${count}++`);
if (max === undefined) {
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
}
else {
gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
if (min === 1)
gen.assign(valid, true);
else
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=contains.js.map
/***/ }),
/***/ 76132:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const code_1 = __nccwpck_require__(56613);
exports.error = {
message: ({ params: { property, depsCount, deps } }) => {
const property_ies = depsCount === 1 ? "property" : "properties";
return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
},
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`, // TODO change to reference
};
const def = {
keyword: "dependencies",
type: "object",
schemaType: "object",
error: exports.error,
code(cxt) {
const [propDeps, schDeps] = splitDependencies(cxt);
validatePropertyDeps(cxt, propDeps);
validateSchemaDeps(cxt, schDeps);
},
};
function splitDependencies({ schema }) {
const propertyDeps = {};
const schemaDeps = {};
for (const key in schema) {
if (key === "__proto__")
continue;
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
deps[key] = schema[key];
}
return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
const { gen, data, it } = cxt;
if (Object.keys(propertyDeps).length === 0)
return;
const missing = gen.let("missing");
for (const prop in propertyDeps) {
const deps = propertyDeps[prop];
if (deps.length === 0)
continue;
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
cxt.setParams({
property: prop,
depsCount: deps.length,
deps: deps.join(", "),
});
if (it.allErrors) {
gen.if(hasProperty, () => {
for (const depProp of deps) {
(0, code_1.checkReportMissingProp)(cxt, depProp);
}
});
}
else {
gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
for (const prop in schemaDeps) {
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
continue;
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
cxt.mergeValidEvaluated(schCxt, valid);
}, () => gen.var(valid, true) // TODO var
);
cxt.ok(valid);
}
}
exports.validateSchemaDeps = validateSchemaDeps;
exports["default"] = def;
//# sourceMappingURL=dependencies.js.map
/***/ }),
/***/ 97689:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
keyword: "if",
schemaType: ["object", "boolean"],
trackErrors: true,
error,
code(cxt) {
const { gen, parentSchema, it } = cxt;
if (parentSchema.then === undefined && parentSchema.else === undefined) {
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
}
const hasThen = hasSchema(it, "then");
const hasElse = hasSchema(it, "else");
if (!hasThen && !hasElse)
return;
const valid = gen.let("valid", true);
const schValid = gen.name("_valid");
validateIf();
cxt.reset();
if (hasThen && hasElse) {
const ifClause = gen.let("ifClause");
cxt.setParams({ ifClause });
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
}
else if (hasThen) {
gen.if(schValid, validateClause("then"));
}
else {
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
}
cxt.pass(valid, () => cxt.error(true));
function validateIf() {
const schCxt = cxt.subschema({
keyword: "if",
compositeRule: true,
createErrors: false,
allErrors: false,
}, schValid);
cxt.mergeEvaluated(schCxt);
}
function validateClause(keyword, ifClause) {
return () => {
const schCxt = cxt.subschema({ keyword }, schValid);
gen.assign(valid, schValid);
cxt.mergeValidEvaluated(schCxt, valid);
if (ifClause)
gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
else
cxt.setParams({ ifClause: keyword });
};
}
},
};
function hasSchema(it, keyword) {
const schema = it.schema[keyword];
return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports["default"] = def;
//# sourceMappingURL=if.js.map
/***/ }),
/***/ 52438:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const additionalItems_1 = __nccwpck_require__(19776);
const prefixItems_1 = __nccwpck_require__(82029);
const items_1 = __nccwpck_require__(30630);
const items2020_1 = __nccwpck_require__(39988);
const contains_1 = __nccwpck_require__(26188);
const dependencies_1 = __nccwpck_require__(76132);
const propertyNames_1 = __nccwpck_require__(61912);
const additionalProperties_1 = __nccwpck_require__(43160);
const properties_1 = __nccwpck_require__(53083);
const patternProperties_1 = __nccwpck_require__(28895);
const not_1 = __nccwpck_require__(16699);
const anyOf_1 = __nccwpck_require__(74712);
const oneOf_1 = __nccwpck_require__(17519);
const allOf_1 = __nccwpck_require__(87735);
const if_1 = __nccwpck_require__(97689);
const thenElse_1 = __nccwpck_require__(63190);
function getApplicator(draft2020 = false) {
const applicator = [
// any
not_1.default,
anyOf_1.default,
oneOf_1.default,
allOf_1.default,
if_1.default,
thenElse_1.default,
// object
propertyNames_1.default,
additionalProperties_1.default,
dependencies_1.default,
properties_1.default,
patternProperties_1.default,
];
// array
if (draft2020)
applicator.push(prefixItems_1.default, items2020_1.default);
else
applicator.push(additionalItems_1.default, items_1.default);
applicator.push(contains_1.default);
return applicator;
}
exports["default"] = getApplicator;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 30630:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateTuple = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const code_1 = __nccwpck_require__(56613);
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "array", "boolean"],
before: "uniqueItems",
code(cxt) {
const { schema, it } = cxt;
if (Array.isArray(schema))
return validateTuple(cxt, "additionalItems", schema);
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
cxt.ok((0, code_1.validateArray)(cxt));
},
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
const { gen, parentSchema, data, keyword, it } = cxt;
checkStrictTuple(parentSchema);
if (it.opts.unevaluated && schArr.length && it.items !== true) {
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
}
const valid = gen.name("valid");
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
schArr.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
keyword,
schemaProp: i,
dataProp: i,
}, valid));
cxt.ok(valid);
});
function checkStrictTuple(sch) {
const { opts, errSchemaPath } = it;
const l = schArr.length;
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
if (opts.strictTuples && !fullTuple) {
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
}
}
}
exports.validateTuple = validateTuple;
exports["default"] = def;
//# sourceMappingURL=items.js.map
/***/ }),
/***/ 39988:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const code_1 = __nccwpck_require__(56613);
const additionalItems_1 = __nccwpck_require__(19776);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
error,
code(cxt) {
const { schema, parentSchema, it } = cxt;
const { prefixItems } = parentSchema;
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
if (prefixItems)
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
else
cxt.ok((0, code_1.validateArray)(cxt));
},
};
exports["default"] = def;
//# sourceMappingURL=items2020.js.map
/***/ }),
/***/ 16699:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(570);
const def = {
keyword: "not",
schemaType: ["object", "boolean"],
trackErrors: true,
code(cxt) {
const { gen, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema)) {
cxt.fail();
return;
}
const valid = gen.name("valid");
cxt.subschema({
keyword: "not",
compositeRule: true,
createErrors: false,
allErrors: false,
}, valid);
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
},
error: { message: "must NOT be valid" },
};
exports["default"] = def;
//# sourceMappingURL=not.js.map
/***/ }),
/***/ 17519:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: "must match exactly one schema in oneOf",
params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
keyword: "oneOf",
schemaType: "array",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
if (it.opts.discriminator && parentSchema.discriminator)
return;
const schArr = schema;
const valid = gen.let("valid", false);
const passing = gen.let("passing", null);
const schValid = gen.name("_valid");
cxt.setParams({ passing });
// TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
gen.block(validateOneOf);
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
function validateOneOf() {
schArr.forEach((sch, i) => {
let schCxt;
if ((0, util_1.alwaysValidSchema)(it, sch)) {
gen.var(schValid, true);
}
else {
schCxt = cxt.subschema({
keyword: "oneOf",
schemaProp: i,
compositeRule: true,
}, schValid);
}
if (i > 0) {
gen
.if((0, codegen_1._) `${schValid} && ${valid}`)
.assign(valid, false)
.assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
.else();
}
gen.if(schValid, () => {
gen.assign(valid, true);
gen.assign(passing, i);
if (schCxt)
cxt.mergeEvaluated(schCxt, codegen_1.Name);
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=oneOf.js.map
/***/ }),
/***/ 28895:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const util_2 = __nccwpck_require__(570);
const def = {
keyword: "patternProperties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, data, parentSchema, it } = cxt;
const { opts } = it;
const patterns = (0, code_1.allSchemaProperties)(schema);
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
if (patterns.length === 0 ||
(alwaysValidPatterns.length === patterns.length &&
(!it.opts.unevaluated || it.props === true))) {
return;
}
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
const valid = gen.name("valid");
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
}
const { props } = it;
validatePatternProperties();
function validatePatternProperties() {
for (const pat of patterns) {
if (checkProperties)
checkMatchingProperties(pat);
if (it.allErrors) {
validateProperties(pat);
}
else {
gen.var(valid, true); // TODO var
validateProperties(pat);
gen.if(valid);
}
}
}
function checkMatchingProperties(pat) {
for (const prop in checkProperties) {
if (new RegExp(pat).test(prop)) {
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
}
}
}
function validateProperties(pat) {
gen.forIn("key", data, (key) => {
gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
const alwaysValid = alwaysValidPatterns.includes(pat);
if (!alwaysValid) {
cxt.subschema({
keyword: "patternProperties",
schemaProp: pat,
dataProp: key,
dataPropType: util_2.Type.Str,
}, valid);
}
if (it.opts.unevaluated && props !== true) {
gen.assign((0, codegen_1._) `${props}[${key}]`, true);
}
else if (!alwaysValid && !it.allErrors) {
// can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
// or if all properties were evaluated (props === true)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=patternProperties.js.map
/***/ }),
/***/ 82029:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const items_1 = __nccwpck_require__(30630);
const def = {
keyword: "prefixItems",
type: "array",
schemaType: ["array"],
before: "uniqueItems",
code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports["default"] = def;
//# sourceMappingURL=prefixItems.js.map
/***/ }),
/***/ 53083:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const validate_1 = __nccwpck_require__(31564);
const code_1 = __nccwpck_require__(56613);
const util_1 = __nccwpck_require__(570);
const additionalProperties_1 = __nccwpck_require__(43160);
const def = {
keyword: "properties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
}
const allProps = (0, code_1.allSchemaProperties)(schema);
for (const prop of allProps) {
it.definedProperties.add(prop);
}
if (it.opts.unevaluated && allProps.length && it.props !== true) {
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
}
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
if (properties.length === 0)
return;
const valid = gen.name("valid");
for (const prop of properties) {
if (hasDefault(prop)) {
applyPropertySchema(prop);
}
else {
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
applyPropertySchema(prop);
if (!it.allErrors)
gen.else().var(valid, true);
gen.endIf();
}
cxt.it.definedProperties.add(prop);
cxt.ok(valid);
}
function hasDefault(prop) {
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
}
function applyPropertySchema(prop) {
cxt.subschema({
keyword: "properties",
schemaProp: prop,
dataProp: prop,
}, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=properties.js.map
/***/ }),
/***/ 61912:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: "property name must be valid",
params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
keyword: "propertyNames",
type: "object",
schemaType: ["object", "boolean"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
gen.forIn("key", data, (key) => {
cxt.setParams({ propertyName: key });
cxt.subschema({
keyword: "propertyNames",
data: key,
dataTypes: ["string"],
propertyName: key,
compositeRule: true,
}, valid);
gen.if((0, codegen_1.not)(valid), () => {
cxt.error(true);
if (!it.allErrors)
gen.break();
});
});
cxt.ok(valid);
},
};
exports["default"] = def;
//# sourceMappingURL=propertyNames.js.map
/***/ }),
/***/ 63190:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(570);
const def = {
keyword: ["then", "else"],
schemaType: ["object", "boolean"],
code({ keyword, parentSchema, it }) {
if (parentSchema.if === undefined)
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
},
};
exports["default"] = def;
//# sourceMappingURL=thenElse.js.map
/***/ }),
/***/ 56613:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const names_1 = __nccwpck_require__(65763);
const util_2 = __nccwpck_require__(570);
function checkReportMissingProp(cxt, prop) {
const { gen, data, it } = cxt;
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
cxt.error();
});
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
cxt.setParams({ missingProperty: missing }, true);
cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
});
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
const valCxt = [
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
[names_1.default.parentData, it.parentData],
[names_1.default.parentDataProperty, it.parentDataProperty],
[names_1.default.rootData, names_1.default.rootData],
];
if (it.opts.dynamicRef)
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
const u = opts.unicodeRegExp ? "u" : "";
const { regExp } = opts.code;
const rx = regExp(pattern, u);
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
});
}
exports.usePattern = usePattern;
function validateArray(cxt) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
if (it.allErrors) {
const validArr = gen.let("valid", true);
validateItems(() => gen.assign(validArr, false));
return validArr;
}
gen.var(valid, true);
validateItems(() => gen.break());
return valid;
function validateItems(notValid) {
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword,
dataProp: i,
dataPropType: util_1.Type.Num,
}, valid);
gen.if((0, codegen_1.not)(valid), notValid);
});
}
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
const { gen, schema, keyword, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
if (alwaysValid && !it.opts.unevaluated)
return;
const valid = gen.let("valid", false);
const schValid = gen.name("_valid");
gen.block(() => schema.forEach((_sch, i) => {
const schCxt = cxt.subschema({
keyword,
schemaProp: i,
compositeRule: true,
}, schValid);
gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged)
gen.if((0, codegen_1.not)(valid));
}));
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 98651:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const def = {
keyword: "id",
code() {
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
},
};
exports["default"] = def;
//# sourceMappingURL=id.js.map
/***/ }),
/***/ 81185:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const id_1 = __nccwpck_require__(98651);
const ref_1 = __nccwpck_require__(62182);
const core = [
"$schema",
"$id",
"$defs",
"$vocabulary",
{ keyword: "$comment" },
"definitions",
id_1.default,
ref_1.default,
];
exports["default"] = core;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 62182:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = __nccwpck_require__(74874);
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const names_1 = __nccwpck_require__(65763);
const compile_1 = __nccwpck_require__(40718);
const util_1 = __nccwpck_require__(570);
const def = {
keyword: "$ref",
schemaType: "string",
code(cxt) {
const { gen, schema: $ref, it } = cxt;
const { baseId, schemaEnv: env, validateName, opts, self } = it;
const { root } = env;
if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
return callRootRef();
const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
if (schOrEnv === undefined)
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
if (schOrEnv instanceof compile_1.SchemaEnv)
return callValidate(schOrEnv);
return inlineRefSchema(schOrEnv);
function callRootRef() {
if (env === root)
return callRef(cxt, validateName, env, env.$async);
const rootName = gen.scopeValue("root", { ref: root });
return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
}
function callValidate(sch) {
const v = getValidate(cxt, sch);
callRef(cxt, v, sch, sch.$async);
}
function inlineRefSchema(sch) {
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
const valid = gen.name("valid");
const schCxt = cxt.subschema({
schema: sch,
dataTypes: [],
schemaPath: codegen_1.nil,
topSchemaRef: schName,
errSchemaPath: $ref,
}, valid);
cxt.mergeEvaluated(schCxt);
cxt.ok(valid);
}
},
};
function getValidate(cxt, sch) {
const { gen } = cxt;
return sch.validate
? gen.scopeValue("validate", { ref: sch.validate })
: (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
const { gen, it } = cxt;
const { allErrors, schemaEnv: env, opts } = it;
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
if ($async)
callAsyncRef();
else
callSyncRef();
function callAsyncRef() {
if (!env.$async)
throw new Error("async schema referenced by sync schema");
const valid = gen.let("valid");
gen.try(() => {
gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
if (!allErrors)
gen.assign(valid, true);
}, (e) => {
gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
addErrorsFrom(e);
if (!allErrors)
gen.assign(valid, false);
});
cxt.ok(valid);
}
function callSyncRef() {
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
}
function addErrorsFrom(source) {
const errs = (0, codegen_1._) `${source}.errors`;
gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
}
function addEvaluatedFrom(source) {
var _a;
if (!it.opts.unevaluated)
return;
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
// TODO refactor
if (it.props !== true) {
if (schEvaluated && !schEvaluated.dynamicProps) {
if (schEvaluated.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
}
}
else {
const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
}
}
if (it.items !== true) {
if (schEvaluated && !schEvaluated.dynamicItems) {
if (schEvaluated.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
}
}
else {
const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
}
}
}
}
exports.callRef = callRef;
exports["default"] = def;
//# sourceMappingURL=ref.js.map
/***/ }),
/***/ 47172:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const types_1 = __nccwpck_require__(56787);
const compile_1 = __nccwpck_require__(40718);
const ref_error_1 = __nccwpck_require__(74874);
const util_1 = __nccwpck_require__(570);
const error = {
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
? `tag "${tagName}" must be string`
: `value of tag "${tagName}" must be in oneOf`,
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
keyword: "discriminator",
type: "object",
schemaType: "object",
error,
code(cxt) {
const { gen, data, schema, parentSchema, it } = cxt;
const { oneOf } = parentSchema;
if (!it.opts.discriminator) {
throw new Error("discriminator: requires discriminator option");
}
const tagName = schema.propertyName;
if (typeof tagName != "string")
throw new Error("discriminator: requires propertyName");
if (schema.mapping)
throw new Error("discriminator: mapping is not supported");
if (!oneOf)
throw new Error("discriminator: requires oneOf keyword");
const valid = gen.let("valid", false);
const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
cxt.ok(valid);
function validateMapping() {
const mapping = getMapping();
gen.if(false);
for (const tagValue in mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
gen.assign(valid, applyTagSchema(mapping[tagValue]));
}
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
gen.endIf();
}
function applyTagSchema(schemaProp) {
const _valid = gen.name("valid");
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
cxt.mergeEvaluated(schCxt, codegen_1.Name);
return _valid;
}
function getMapping() {
var _a;
const oneOfMapping = {};
const topRequired = hasRequired(parentSchema);
let tagRequired = true;
for (let i = 0; i < oneOf.length; i++) {
let sch = oneOf[i];
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
const ref = sch.$ref;
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
if (sch instanceof compile_1.SchemaEnv)
sch = sch.schema;
if (sch === undefined)
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
}
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
if (typeof propSch != "object") {
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
}
tagRequired = tagRequired && (topRequired || hasRequired(sch));
addMappings(propSch, i);
}
if (!tagRequired)
throw new Error(`discriminator: "${tagName}" must be required`);
return oneOfMapping;
function hasRequired({ required }) {
return Array.isArray(required) && required.includes(tagName);
}
function addMappings(sch, i) {
if (sch.const) {
addMapping(sch.const, i);
}
else if (sch.enum) {
for (const tagValue of sch.enum) {
addMapping(tagValue, i);
}
}
else {
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
}
}
function addMapping(tagValue, i) {
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
}
oneOfMapping[tagValue] = i;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 56787:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
DiscrError["Tag"] = "tag";
DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 91934:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const core_1 = __nccwpck_require__(81185);
const validation_1 = __nccwpck_require__(92754);
const applicator_1 = __nccwpck_require__(52438);
const format_1 = __nccwpck_require__(6466);
const metadata_1 = __nccwpck_require__(36526);
const draft7Vocabularies = [
core_1.default,
validation_1.default,
(0, applicator_1.default)(),
format_1.default,
metadata_1.metadataVocabulary,
metadata_1.contentVocabulary,
];
exports["default"] = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map
/***/ }),
/***/ 76613:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
keyword: "format",
type: ["number", "string"],
schemaType: "string",
$data: true,
error,
code(cxt, ruleType) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
const { opts, errSchemaPath, schemaEnv, self } = it;
if (!opts.validateFormats)
return;
if ($data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
});
const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
const fType = gen.let("fType");
const format = gen.let("format");
// TODO simplify
gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
function unknownFmt() {
if (opts.strictSchema === false)
return codegen_1.nil;
return (0, codegen_1._) `${schemaCode} && !${format}`;
}
function invalidFmt() {
const callFormat = schemaEnv.$async
? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
: (0, codegen_1._) `${format}(${data})`;
const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
}
}
function validateFormat() {
const formatDef = self.formats[schema];
if (!formatDef) {
unknownFormat();
return;
}
if (formatDef === true)
return;
const [fmtType, format, fmtRef] = getFormat(formatDef);
if (fmtType === ruleType)
cxt.pass(validCondition());
function unknownFormat() {
if (opts.strictSchema === false) {
self.logger.warn(unknownMsg());
return;
}
throw new Error(unknownMsg());
function unknownMsg() {
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
}
}
function getFormat(fmtDef) {
const code = fmtDef instanceof RegExp
? (0, codegen_1.regexpCode)(fmtDef)
: opts.code.formats
? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
: undefined;
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
}
return ["string", fmtDef, fmt];
}
function validCondition() {
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
if (!schemaEnv.$async)
throw new Error("async format in sync schema");
return (0, codegen_1._) `await ${fmtRef}(${data})`;
}
return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=format.js.map
/***/ }),
/***/ 6466:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const format_1 = __nccwpck_require__(76613);
const format = [format_1.default];
exports["default"] = format;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 21477:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const metadata_1 = __nccwpck_require__(39129);
const nullable_1 = __nccwpck_require__(8294);
const error_1 = __nccwpck_require__(40315);
const types_1 = __nccwpck_require__(56787);
const error = {
message: (cxt) => {
const { schema, params } = cxt;
return params.discrError
? params.discrError === types_1.DiscrError.Tag
? `tag "${schema}" must be string`
: `value of tag "${schema}" must be in mapping`
: (0, error_1.typeErrorMessage)(cxt, "object");
},
params: (cxt) => {
const { schema, params } = cxt;
return params.discrError
? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
: (0, error_1.typeErrorParams)(cxt, "object");
},
};
const def = {
keyword: "discriminator",
schemaType: "string",
implements: ["mapping"],
error,
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, schema, parentSchema } = cxt;
const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
gen.if(cond);
validateDiscriminator();
gen.elseIf((0, codegen_1.not)(valid));
cxt.error();
gen.endIf();
cxt.ok(valid);
function validateDiscriminator() {
const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`);
gen.if((0, codegen_1._) `${tag} === undefined`);
cxt.error(false, { discrError: types_1.DiscrError.Tag, tag });
gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`);
validateMapping(tag);
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema });
gen.endIf();
}
function validateMapping(tag) {
gen.if(false);
for (const tagValue in parentSchema.mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
gen.assign(valid, applyTagSchema(tagValue));
}
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true });
gen.endIf();
}
function applyTagSchema(schemaProp) {
const _valid = gen.name("valid");
cxt.subschema({
keyword: "mapping",
schemaProp,
jtdDiscriminator: schema,
}, _valid);
return _valid;
}
},
};
exports["default"] = def;
//# sourceMappingURL=discriminator.js.map
/***/ }),
/***/ 47046:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(570);
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const metadata_1 = __nccwpck_require__(39129);
const nullable_1 = __nccwpck_require__(8294);
const error_1 = __nccwpck_require__(40315);
const def = {
keyword: "elements",
schemaType: "object",
error: (0, error_1.typeError)("array"),
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const [valid] = (0, nullable_1.checkNullable)(cxt);
gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error()));
cxt.ok(valid);
},
};
exports["default"] = def;
//# sourceMappingURL=elements.js.map
/***/ }),
/***/ 53018:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const metadata_1 = __nccwpck_require__(39129);
const nullable_1 = __nccwpck_require__(8294);
const error = {
message: "must be equal to one of the allowed values",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
keyword: "enum",
schemaType: "array",
error,
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
if (schema.length === 0)
throw new Error("enum must have non-empty array");
if (schema.length !== new Set(schema).size)
throw new Error("enum items must be unique");
let valid;
const isString = (0, codegen_1._) `typeof ${data} == "string"`;
if (schema.length >= it.opts.loopEnum) {
let cond;
[valid, cond] = (0, nullable_1.checkNullable)(cxt, isString);
gen.if(cond, loopEnum);
}
else {
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`)));
if (parentSchema.nullable)
valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid);
}
cxt.pass(valid);
function loopEnum() {
gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break()));
}
},
};
exports["default"] = def;
//# sourceMappingURL=enum.js.map
/***/ }),
/***/ 40315:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0;
const codegen_1 = __nccwpck_require__(79786);
function typeError(t) {
return {
message: (cxt) => typeErrorMessage(cxt, t),
params: (cxt) => typeErrorParams(cxt, t),
};
}
exports.typeError = typeError;
function typeErrorMessage({ parentSchema }, t) {
return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`;
}
exports.typeErrorMessage = typeErrorMessage;
function typeErrorParams({ parentSchema }, t) {
return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`;
}
exports.typeErrorParams = typeErrorParams;
//# sourceMappingURL=error.js.map
/***/ }),
/***/ 32727:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const ref_1 = __nccwpck_require__(39948);
const type_1 = __nccwpck_require__(6796);
const enum_1 = __nccwpck_require__(53018);
const elements_1 = __nccwpck_require__(47046);
const properties_1 = __nccwpck_require__(39116);
const optionalProperties_1 = __nccwpck_require__(86504);
const discriminator_1 = __nccwpck_require__(21477);
const values_1 = __nccwpck_require__(94428);
const union_1 = __nccwpck_require__(71046);
const metadata_1 = __nccwpck_require__(39129);
const jtdVocabulary = [
"definitions",
ref_1.default,
type_1.default,
enum_1.default,
elements_1.default,
properties_1.default,
optionalProperties_1.default,
discriminator_1.default,
values_1.default,
union_1.default,
metadata_1.default,
{ keyword: "additionalProperties", schemaType: "boolean" },
{ keyword: "nullable", schemaType: "boolean" },
];
exports["default"] = jtdVocabulary;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 39129:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkMetadata = void 0;
const util_1 = __nccwpck_require__(570);
const def = {
keyword: "metadata",
schemaType: "object",
code(cxt) {
checkMetadata(cxt);
const { gen, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid);
cxt.ok(valid);
},
};
function checkMetadata({ it, keyword }, metadata) {
if (it.jtdMetadata !== metadata) {
throw new Error(`JTD: "${keyword}" cannot be used in this schema location`);
}
}
exports.checkMetadata = checkMetadata;
exports["default"] = def;
//# sourceMappingURL=metadata.js.map
/***/ }),
/***/ 8294:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkNullableObject = exports.checkNullable = void 0;
const codegen_1 = __nccwpck_require__(79786);
function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) {
const valid = gen.name("valid");
if (parentSchema.nullable) {
gen.let(valid, (0, codegen_1._) `${data} === null`);
cond = (0, codegen_1.not)(valid);
}
else {
gen.let(valid, false);
}
return [valid, cond];
}
exports.checkNullable = checkNullable;
function checkNullableObject(cxt, cond) {
const [valid, cond_] = checkNullable(cxt, cond);
return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`];
}
exports.checkNullableObject = checkNullableObject;
//# sourceMappingURL=nullable.js.map
/***/ }),
/***/ 86504:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const properties_1 = __nccwpck_require__(39116);
const def = {
keyword: "optionalProperties",
schemaType: "object",
error: properties_1.error,
code(cxt) {
if (cxt.parentSchema.properties)
return;
(0, properties_1.validateProperties)(cxt);
},
};
exports["default"] = def;
//# sourceMappingURL=optionalProperties.js.map
/***/ }),
/***/ 39116:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateProperties = exports.error = void 0;
const code_1 = __nccwpck_require__(56613);
const util_1 = __nccwpck_require__(570);
const codegen_1 = __nccwpck_require__(79786);
const metadata_1 = __nccwpck_require__(39129);
const nullable_1 = __nccwpck_require__(8294);
const error_1 = __nccwpck_require__(40315);
var PropError;
(function (PropError) {
PropError["Additional"] = "additional";
PropError["Missing"] = "missing";
})(PropError || (PropError = {}));
exports.error = {
message: (cxt) => {
const { params } = cxt;
return params.propError
? params.propError === PropError.Additional
? "must NOT have additional properties"
: `must have property '${params.missingProperty}'`
: (0, error_1.typeErrorMessage)(cxt, "object");
},
params: (cxt) => {
const { params } = cxt;
return params.propError
? params.propError === PropError.Additional
? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
: (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
: (0, error_1.typeErrorParams)(cxt, "object");
},
};
const def = {
keyword: "properties",
schemaType: "object",
error: exports.error,
code: validateProperties,
};
// const error: KeywordErrorDefinition = {
// message: "should NOT have additional properties",
// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }
function validateProperties(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, parentSchema, it } = cxt;
const { additionalProperties, nullable } = parentSchema;
if (it.jtdDiscriminator && nullable)
throw new Error("JTD: nullable inside discriminator mapping");
if (commonProperties()) {
throw new Error("JTD: properties and optionalProperties have common members");
}
const [allProps, properties] = schemaProperties("properties");
const [allOptProps, optProperties] = schemaProperties("optionalProperties");
if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
return;
}
const [valid, cond] = it.jtdDiscriminator === undefined
? (0, nullable_1.checkNullableObject)(cxt, data)
: [gen.let("valid", false), true];
gen.if(cond, () => gen.assign(valid, true).block(() => {
validateProps(properties, "properties", true);
validateProps(optProperties, "optionalProperties");
if (!additionalProperties)
validateAdditional();
}));
cxt.pass(valid);
function commonProperties() {
const props = parentSchema.properties;
const optProps = parentSchema.optionalProperties;
if (!(props && optProps))
return false;
for (const p in props) {
if (Object.prototype.hasOwnProperty.call(optProps, p))
return true;
}
return false;
}
function schemaProperties(keyword) {
const schema = parentSchema[keyword];
const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
throw new Error(`JTD: discriminator tag used in ${keyword}`);
}
const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
return [allPs, ps];
}
function validateProps(props, keyword, required) {
const _valid = gen.var("valid");
for (const prop of props) {
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop));
cxt.ok(_valid);
}
function missingProperty(prop) {
if (required) {
gen.assign(_valid, false);
cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop });
}
else {
gen.assign(_valid, true);
}
}
}
function applyPropertySchema(prop, keyword, _valid) {
cxt.subschema({
keyword,
schemaProp: prop,
dataProp: prop,
}, _valid);
}
function validateAdditional() {
gen.forIn("key", data, (key) => {
const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator);
const addOptProp = isAdditional(key, allOptProps, "optionalProperties");
const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp);
gen.if(extra, () => {
if (it.opts.removeAdditional) {
gen.code((0, codegen_1._) `delete ${data}[${key}]`);
}
else {
cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true });
if (!it.opts.allErrors)
gen.break();
}
});
});
}
function isAdditional(key, props, keyword, jtdDiscriminator) {
let additional;
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword);
additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key));
if (jtdDiscriminator !== undefined) {
additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`);
}
}
else if (props.length || jtdDiscriminator !== undefined) {
const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props);
additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`));
}
else {
additional = true;
}
return additional;
}
}
exports.validateProperties = validateProperties;
exports["default"] = def;
//# sourceMappingURL=properties.js.map
/***/ }),
/***/ 39948:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.hasRef = void 0;
const compile_1 = __nccwpck_require__(40718);
const codegen_1 = __nccwpck_require__(79786);
const ref_error_1 = __nccwpck_require__(74874);
const names_1 = __nccwpck_require__(65763);
const ref_1 = __nccwpck_require__(62182);
const metadata_1 = __nccwpck_require__(39129);
const def = {
keyword: "ref",
schemaType: "string",
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, schema: ref, parentSchema, it } = cxt;
const { schemaEnv: { root }, } = it;
const valid = gen.name("valid");
if (parentSchema.nullable) {
gen.var(valid, (0, codegen_1._) `${data} === null`);
gen.if((0, codegen_1.not)(valid), validateJtdRef);
}
else {
gen.var(valid, false);
validateJtdRef();
}
cxt.ok(valid);
function validateJtdRef() {
var _a;
const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
if (!refSchema) {
throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
}
if (hasRef(refSchema) || !it.opts.inlineRefs)
callValidate(refSchema);
else
inlineRefSchema(refSchema);
}
function callValidate(schema) {
const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
const v = (0, ref_1.getValidate)(cxt, sch);
const errsCount = gen.const("_errs", names_1.default.errors);
(0, ref_1.callRef)(cxt, v, sch, sch.$async);
gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function inlineRefSchema(schema) {
const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
cxt.subschema({
schema,
dataTypes: [],
schemaPath: codegen_1.nil,
topSchemaRef: schName,
errSchemaPath: `/definitions/${ref}`,
}, valid);
}
},
};
function hasRef(schema) {
for (const key in schema) {
let sch;
if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
return true;
}
return false;
}
exports.hasRef = hasRef;
exports["default"] = def;
//# sourceMappingURL=ref.js.map
/***/ }),
/***/ 6796:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.intRange = void 0;
const codegen_1 = __nccwpck_require__(79786);
const timestamp_1 = __nccwpck_require__(94290);
const util_1 = __nccwpck_require__(570);
const metadata_1 = __nccwpck_require__(39129);
const error_1 = __nccwpck_require__(40315);
exports.intRange = {
int8: [-128, 127, 3],
uint8: [0, 255, 3],
int16: [-32768, 32767, 5],
uint16: [0, 65535, 5],
int32: [-2147483648, 2147483647, 10],
uint32: [0, 4294967295, 10],
};
const error = {
message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
};
function timestampCode(cxt) {
const { gen, data, it } = cxt;
const { timestamp, allowDate } = it.opts;
if (timestamp === "date")
return (0, codegen_1._) `${data} instanceof Date `;
const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
}
const def = {
keyword: "type",
schemaType: "string",
error,
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { data, schema, parentSchema, it } = cxt;
let cond;
switch (schema) {
case "boolean":
case "string":
cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
break;
case "timestamp": {
cond = timestampCode(cxt);
break;
}
case "float32":
case "float64":
cond = (0, codegen_1._) `typeof ${data} == "number"`;
break;
default: {
const sch = schema;
cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
if (sch === "uint32")
cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
}
else {
const [min, max] = exports.intRange[sch];
cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
}
}
}
cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
},
};
exports["default"] = def;
//# sourceMappingURL=type.js.map
/***/ }),
/***/ 71046:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const def = {
keyword: "union",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in union" },
};
exports["default"] = def;
//# sourceMappingURL=union.js.map
/***/ }),
/***/ 94428:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(570);
const codegen_1 = __nccwpck_require__(79786);
const metadata_1 = __nccwpck_require__(39129);
const nullable_1 = __nccwpck_require__(8294);
const error_1 = __nccwpck_require__(40315);
const def = {
keyword: "values",
schemaType: "object",
error: (0, error_1.typeError)("object"),
code(cxt) {
(0, metadata_1.checkMetadata)(cxt);
const { gen, data, schema, it } = cxt;
const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
if ((0, util_1.alwaysValidSchema)(it, schema)) {
gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error());
}
else {
gen.if(cond);
gen.assign(valid, validateMap());
gen.elseIf((0, codegen_1.not)(valid));
cxt.error();
gen.endIf();
}
cxt.ok(valid);
function validateMap() {
const _valid = gen.name("valid");
if (it.allErrors) {
const validMap = gen.let("valid", true);
validateValues(() => gen.assign(validMap, false));
return validMap;
}
gen.var(_valid, true);
validateValues(() => gen.break());
return _valid;
function validateValues(notValid) {
gen.forIn("key", data, (key) => {
cxt.subschema({
keyword: "values",
dataProp: key,
dataPropType: util_1.Type.Str,
}, _valid);
gen.if((0, codegen_1.not)(_valid), notValid);
});
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=values.js.map
/***/ }),
/***/ 36526:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
"title",
"description",
"default",
"deprecated",
"readOnly",
"writeOnly",
"examples",
];
exports.contentVocabulary = [
"contentMediaType",
"contentEncoding",
"contentSchema",
];
//# sourceMappingURL=metadata.js.map
/***/ }),
/***/ 40677:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const equal_1 = __nccwpck_require__(42481);
const error = {
message: "must be equal to constant",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
keyword: "const",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schemaCode, schema } = cxt;
if ($data || (schema && typeof schema == "object")) {
cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
}
else {
cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
}
},
};
exports["default"] = def;
//# sourceMappingURL=const.js.map
/***/ }),
/***/ 91487:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const equal_1 = __nccwpck_require__(42481);
const error = {
message: "must be equal to one of the allowed values",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
keyword: "enum",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
if (!$data && schema.length === 0)
throw new Error("enum must have non-empty array");
const useLoop = schema.length >= it.opts.loopEnum;
let eql;
const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
let valid;
if (useLoop || $data) {
valid = gen.let("valid");
cxt.block$data(valid, loopEnum);
}
else {
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const vSchema = gen.const("vSchema", schemaCode);
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
}
cxt.pass(valid);
function loopEnum() {
gen.assign(valid, false);
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
}
function equalCode(vSchema, i) {
const sch = schema[i];
return typeof sch === "object" && sch !== null
? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
: (0, codegen_1._) `${data} === ${sch}`;
}
},
};
exports["default"] = def;
//# sourceMappingURL=enum.js.map
/***/ }),
/***/ 92754:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const limitNumber_1 = __nccwpck_require__(43392);
const multipleOf_1 = __nccwpck_require__(45984);
const limitLength_1 = __nccwpck_require__(41210);
const pattern_1 = __nccwpck_require__(45469);
const limitProperties_1 = __nccwpck_require__(60459);
const required_1 = __nccwpck_require__(6549);
const limitItems_1 = __nccwpck_require__(46164);
const uniqueItems_1 = __nccwpck_require__(99372);
const const_1 = __nccwpck_require__(40677);
const enum_1 = __nccwpck_require__(91487);
const validation = [
// number
limitNumber_1.default,
multipleOf_1.default,
// string
limitLength_1.default,
pattern_1.default,
// object
limitProperties_1.default,
required_1.default,
// array
limitItems_1.default,
uniqueItems_1.default,
// any
{ keyword: "type", schemaType: ["string", "array"] },
{ keyword: "nullable", schemaType: "boolean" },
const_1.default,
enum_1.default,
];
exports["default"] = validation;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 46164:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxItems" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxItems", "minItems"],
type: "array",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitItems.js.map
/***/ }),
/***/ 41210:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const ucs2length_1 = __nccwpck_require__(61360);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxLength" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode, it } = cxt;
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitLength.js.map
/***/ }),
/***/ 43392:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const ops = codegen_1.operators;
const KWDs = {
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
keyword: Object.keys(KWDs),
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitNumber.js.map
/***/ }),
/***/ 60459:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxProperties" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxProperties", "minProperties"],
type: "object",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitProperties.js.map
/***/ }),
/***/ 45984:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(79786);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
keyword: "multipleOf",
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, it } = cxt;
// const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
const prec = it.opts.multipleOfPrecision;
const res = gen.let("res");
const invalid = prec
? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
: (0, codegen_1._) `${res} !== parseInt(${res})`;
cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
},
};
exports["default"] = def;
//# sourceMappingURL=multipleOf.js.map
/***/ }),
/***/ 45469:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
keyword: "pattern",
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { data, $data, schema, schemaCode, it } = cxt;
// TODO regexp should be wrapped in try/catchs
const u = it.opts.unicodeRegExp ? "u" : "";
const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=pattern.js.map
/***/ }),
/***/ 6549:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(56613);
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const error = {
message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
keyword: "required",
type: "object",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, schema, schemaCode, data, $data, it } = cxt;
const { opts } = it;
if (!$data && schema.length === 0)
return;
const useLoop = schema.length >= opts.loopRequired;
if (it.allErrors)
allErrorsMode();
else
exitOnErrorMode();
if (opts.strictRequired) {
const props = cxt.parentSchema.properties;
const { definedProperties } = cxt.it;
for (const requiredKey of schema) {
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
}
}
}
function allErrorsMode() {
if (useLoop || $data) {
cxt.block$data(codegen_1.nil, loopAllRequired);
}
else {
for (const prop of schema) {
(0, code_1.checkReportMissingProp)(cxt, prop);
}
}
}
function exitOnErrorMode() {
const missing = gen.let("missing");
if (useLoop || $data) {
const valid = gen.let("valid", true);
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
cxt.ok(valid);
}
else {
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
function loopAllRequired() {
gen.forOf("prop", schemaCode, (prop) => {
cxt.setParams({ missingProperty: prop });
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
});
}
function loopUntilMissing(missing, valid) {
cxt.setParams({ missingProperty: missing });
gen.forOf(missing, schemaCode, () => {
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
gen.if((0, codegen_1.not)(valid), () => {
cxt.error();
gen.break();
});
}, codegen_1.nil);
}
},
};
exports["default"] = def;
//# sourceMappingURL=required.js.map
/***/ }),
/***/ 99372:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const dataType_1 = __nccwpck_require__(86777);
const codegen_1 = __nccwpck_require__(79786);
const util_1 = __nccwpck_require__(570);
const equal_1 = __nccwpck_require__(42481);
const error = {
message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
keyword: "uniqueItems",
type: "array",
schemaType: "boolean",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
if (!$data && !schema)
return;
const valid = gen.let("valid");
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
cxt.ok(valid);
function validateUniqueItems() {
const i = gen.let("i", (0, codegen_1._) `${data}.length`);
const j = gen.let("j");
cxt.setParams({ i, j });
gen.assign(valid, true);
gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
}
function canOptimize() {
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
}
function loopN(i, j) {
const item = gen.name("item");
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
const indices = gen.const("indices", (0, codegen_1._) `{}`);
gen.for((0, codegen_1._) `;${i}--;`, () => {
gen.let(item, (0, codegen_1._) `${data}[${i}]`);
gen.if(wrongType, (0, codegen_1._) `continue`);
if (itemTypes.length > 1)
gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
gen
.if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
cxt.error();
gen.assign(valid, false).break();
})
.code((0, codegen_1._) `${indices}[${item}] = ${i}`);
});
}
function loopN2(i, j) {
const eql = (0, util_1.useFunc)(gen, equal_1.default);
const outer = gen.name("outer");
gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
cxt.error();
gen.assign(valid, false).break(outer);
})));
}
},
};
exports["default"] = def;
//# sourceMappingURL=uniqueItems.js.map
/***/ }),
/***/ 25158:
/***/ ((module) => {
"use strict";
var traverse = module.exports = function (schema, opts, cb) {
// Legacy support for v0.3.1 and earlier.
if (typeof opts == 'function') {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
var post = cb.post || function() {};
_traverse(opts, pre, post, schema, '', schema);
};
traverse.keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
if: true,
then: true,
else: true
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
$defs: true,
definitions: true,
properties: true,
patternProperties: true,
dependencies: true
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
maximum: true,
minimum: true,
exclusiveMaximum: true,
exclusiveMinimum: true,
multipleOf: true,
maxLength: true,
minLength: true,
pattern: true,
format: true,
maxItems: true,
minItems: true,
uniqueItems: true,
maxProperties: true,
minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i=0; i<sch.length; i++)
_traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == 'object') {
for (var prop in sch)
_traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
_traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
function escapeJsonPtr(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
/***/ }),
/***/ 65682:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const ValidatorSelector = __nccwpck_require__(14018)
const standaloneCode = (__nccwpck_require__(94883)["default"])
function StandaloneValidator (options = { readMode: true }) {
if (options.readMode === true && !options.restoreFunction) {
throw new Error('You must provide a restoreFunction options when readMode ON')
}
if (options.readMode !== true && !options.storeFunction) {
throw new Error('You must provide a storeFunction options when readMode OFF')
}
if (options.readMode === true) {
// READ MODE: it behalf only in the restore function provided by the user
return function wrapper () {
return function (opts) {
return options.restoreFunction(opts)
}
}
}
// WRITE MODE: it behalf on the default ValidatorSelector, wrapping the API to run the Ajv Standalone code generation
const factory = ValidatorSelector()
return function wrapper (externalSchemas, ajvOptions = {}) {
if (!ajvOptions.customOptions || !ajvOptions.customOptions.code) {
// to generate the validation source code, these options are mandatory
ajvOptions.customOptions = Object.assign({}, ajvOptions.customOptions, { code: { source: true } })
}
const compiler = factory(externalSchemas, ajvOptions)
return function (opts) { // { schema/*, method, url, httpPart */ }
const validationFunc = compiler(opts)
const schemaValidationCode = standaloneCode(compiler[ValidatorSelector.AjvReference].ajv, validationFunc)
options.storeFunction(opts, schemaValidationCode)
return validationFunc
}
}
}
module.exports = StandaloneValidator
/***/ }),
/***/ 94908:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastJsonStringify = __nccwpck_require__(2793)
function SerializerSelector () {
return function buildSerializerFactory (externalSchemas, serializerOpts) {
const fjsOpts = Object.assign({}, serializerOpts, { schema: externalSchemas })
return responseSchemaCompiler.bind(null, fjsOpts)
}
}
function responseSchemaCompiler (fjsOpts, { schema /* method, url, httpStatus */ }) {
if (fjsOpts.schema && schema.$id && fjsOpts.schema[schema.$id]) {
fjsOpts.schema = { ...fjsOpts.schema }
delete fjsOpts.schema[schema.$id]
}
return fastJsonStringify(schema, fjsOpts)
}
module.exports = SerializerSelector
module.exports["default"] = SerializerSelector
module.exports.SerializerSelector = SerializerSelector
module.exports.StandaloneSerializer = __nccwpck_require__(60361)
/***/ }),
/***/ 60361:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const SerializerSelector = __nccwpck_require__(94908)
function StandaloneSerializer (options = { readMode: true }) {
if (options.readMode === true && typeof options.restoreFunction !== 'function') {
throw new Error('You must provide a function for the restoreFunction-option when readMode ON')
}
if (options.readMode !== true && typeof options.storeFunction !== 'function') {
throw new Error('You must provide a function for the storeFunction-option when readMode OFF')
}
if (options.readMode === true) {
// READ MODE: it behalf only in the restore function provided by the user
return function wrapper () {
return function (opts) {
return options.restoreFunction(opts)
}
}
}
// WRITE MODE: it behalf on the default SerializerSelector, wrapping the API to run the Ajv Standalone code generation
const factory = SerializerSelector()
return function wrapper (externalSchemas, serializerOpts = {}) {
// to generate the serialization source code, this option is mandatory
serializerOpts.mode = 'standalone'
const compiler = factory(externalSchemas, serializerOpts)
return function (opts) { // { schema/*, method, url, httpPart */ }
const serializeFuncCode = compiler(opts)
options.storeFunction(opts, serializeFuncCode)
// eslint-disable-next-line no-new-func
return new Function(serializeFuncCode)
}
}
}
module.exports = StandaloneSerializer
module.exports["default"] = StandaloneSerializer
/***/ }),
/***/ 85545:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Merge = __nccwpck_require__(60445);
const Reach = __nccwpck_require__(18891);
const internals = {};
module.exports = function (defaults, source, options = {}) {
Assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
Assert(!source || source === true || typeof source === 'object', 'Invalid source value: must be true, falsy or an object');
Assert(typeof options === 'object', 'Invalid options: must be an object');
if (!source) { // If no source, return null
return null;
}
if (options.shallow) {
return internals.applyToDefaultsWithShallow(defaults, source, options);
}
const copy = Clone(defaults);
if (source === true) { // If source is set to true, use defaults
return copy;
}
const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false;
return Merge(copy, source, { nullOverride, mergeArrays: false });
};
internals.applyToDefaultsWithShallow = function (defaults, source, options) {
const keys = options.shallow;
Assert(Array.isArray(keys), 'Invalid keys');
const seen = new Map();
const merge = source === true ? null : new Set();
for (let key of keys) {
key = Array.isArray(key) ? key : key.split('.'); // Pre-split optimization
const ref = Reach(defaults, key);
if (ref &&
typeof ref === 'object') {
seen.set(ref, merge && Reach(source, key) || ref);
}
else if (merge) {
merge.add(key);
}
}
const copy = Clone(defaults, {}, seen);
if (!merge) {
return copy;
}
for (const key of merge) {
internals.reachCopy(copy, source, key);
}
const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false;
return Merge(copy, source, { nullOverride, mergeArrays: false });
};
internals.reachCopy = function (dst, src, path) {
for (const segment of path) {
if (!(segment in src)) {
return;
}
const val = src[segment];
if (typeof val !== 'object' || val === null) {
return;
}
src = val;
}
const value = src;
let ref = dst;
for (let i = 0; i < path.length - 1; ++i) {
const segment = path[i];
if (typeof ref[segment] !== 'object') {
ref[segment] = {};
}
ref = ref[segment];
}
ref[path[path.length - 1]] = value;
};
/***/ }),
/***/ 32718:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const AssertError = __nccwpck_require__(35563);
const internals = {};
module.exports = function (condition, ...args) {
if (condition) {
return;
}
if (args.length === 1 &&
args[0] instanceof Error) {
throw args[0];
}
throw new AssertError(args);
};
/***/ }),
/***/ 85578:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Reach = __nccwpck_require__(18891);
const Types = __nccwpck_require__(26657);
const Utils = __nccwpck_require__(30417);
const internals = {
needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap])
};
module.exports = internals.clone = function (obj, options = {}, _seen = null) {
if (typeof obj !== 'object' ||
obj === null) {
return obj;
}
let clone = internals.clone;
let seen = _seen;
if (options.shallow) {
if (options.shallow !== true) {
return internals.cloneWithShallow(obj, options);
}
clone = (value) => value;
}
else if (seen) {
const lookup = seen.get(obj);
if (lookup) {
return lookup;
}
}
else {
seen = new Map();
}
// Built-in object types
const baseProto = Types.getInternalProto(obj);
if (baseProto === Types.buffer) {
return Buffer && Buffer.from(obj); // $lab:coverage:ignore$
}
if (baseProto === Types.date) {
return new Date(obj.getTime());
}
if (baseProto === Types.regex) {
return new RegExp(obj);
}
// Generic objects
const newObj = internals.base(obj, baseProto, options);
if (newObj === obj) {
return obj;
}
if (seen) {
seen.set(obj, newObj); // Set seen, since obj could recurse
}
if (baseProto === Types.set) {
for (const value of obj) {
newObj.add(clone(value, options, seen));
}
}
else if (baseProto === Types.map) {
for (const [key, value] of obj) {
newObj.set(key, clone(value, options, seen));
}
}
const keys = Utils.keys(obj, options);
for (const key of keys) {
if (key === '__proto__') {
continue;
}
if (baseProto === Types.array &&
key === 'length') {
newObj.length = obj.length;
continue;
}
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor) {
if (descriptor.get ||
descriptor.set) {
Object.defineProperty(newObj, key, descriptor);
}
else if (descriptor.enumerable) {
newObj[key] = clone(obj[key], options, seen);
}
else {
Object.defineProperty(newObj, key, { enumerable: false, writable: true, configurable: true, value: clone(obj[key], options, seen) });
}
}
else {
Object.defineProperty(newObj, key, {
enumerable: true,
writable: true,
configurable: true,
value: clone(obj[key], options, seen)
});
}
}
return newObj;
};
internals.cloneWithShallow = function (source, options) {
const keys = options.shallow;
options = Object.assign({}, options);
options.shallow = false;
const seen = new Map();
for (const key of keys) {
const ref = Reach(source, key);
if (typeof ref === 'object' ||
typeof ref === 'function') {
seen.set(ref, ref);
}
}
return internals.clone(source, options, seen);
};
internals.base = function (obj, baseProto, options) {
if (options.prototype === false) { // Defaults to true
if (internals.needsProtoHack.has(baseProto)) {
return new baseProto.constructor();
}
return baseProto === Types.array ? [] : {};
}
const proto = Object.getPrototypeOf(obj);
if (proto &&
proto.isImmutable) {
return obj;
}
if (baseProto === Types.array) {
const newObj = [];
if (proto !== baseProto) {
Object.setPrototypeOf(newObj, proto);
}
return newObj;
}
if (internals.needsProtoHack.has(baseProto)) {
const newObj = new proto.constructor();
if (proto !== baseProto) {
Object.setPrototypeOf(newObj, proto);
}
return newObj;
}
return Object.create(proto);
};
/***/ }),
/***/ 55801:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Types = __nccwpck_require__(26657);
const internals = {
mismatched: null
};
module.exports = function (obj, ref, options) {
options = Object.assign({ prototype: true }, options);
return !!internals.isDeepEqual(obj, ref, options, []);
};
internals.isDeepEqual = function (obj, ref, options, seen) {
if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
return obj !== 0 || 1 / obj === 1 / ref;
}
const type = typeof obj;
if (type !== typeof ref) {
return false;
}
if (obj === null ||
ref === null) {
return false;
}
if (type === 'function') {
if (!options.deepFunction ||
obj.toString() !== ref.toString()) {
return false;
}
// Continue as object
}
else if (type !== 'object') {
return obj !== obj && ref !== ref; // NaN
}
const instanceType = internals.getSharedType(obj, ref, !!options.prototype);
switch (instanceType) {
case Types.buffer:
return Buffer && Buffer.prototype.equals.call(obj, ref); // $lab:coverage:ignore$
case Types.promise:
return obj === ref;
case Types.regex:
return obj.toString() === ref.toString();
case internals.mismatched:
return false;
}
for (let i = seen.length - 1; i >= 0; --i) {
if (seen[i].isSame(obj, ref)) {
return true; // If previous comparison failed, it would have stopped execution
}
}
seen.push(new internals.SeenEntry(obj, ref));
try {
return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen);
}
finally {
seen.pop();
}
};
internals.getSharedType = function (obj, ref, checkPrototype) {
if (checkPrototype) {
if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
return internals.mismatched;
}
return Types.getInternalProto(obj);
}
const type = Types.getInternalProto(obj);
if (type !== Types.getInternalProto(ref)) {
return internals.mismatched;
}
return type;
};
internals.valueOf = function (obj) {
const objValueOf = obj.valueOf;
if (objValueOf === undefined) {
return obj;
}
try {
return objValueOf.call(obj);
}
catch (err) {
return err;
}
};
internals.hasOwnEnumerableProperty = function (obj, key) {
return Object.prototype.propertyIsEnumerable.call(obj, key);
};
internals.isSetSimpleEqual = function (obj, ref) {
for (const entry of Set.prototype.values.call(obj)) {
if (!Set.prototype.has.call(ref, entry)) {
return false;
}
}
return true;
};
internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) {
const { isDeepEqual, valueOf, hasOwnEnumerableProperty } = internals;
const { keys, getOwnPropertySymbols } = Object;
if (instanceType === Types.array) {
if (options.part) {
// Check if any index match any other index
for (const objValue of obj) {
for (const refValue of ref) {
if (isDeepEqual(objValue, refValue, options, seen)) {
return true;
}
}
}
}
else {
if (obj.length !== ref.length) {
return false;
}
for (let i = 0; i < obj.length; ++i) {
if (!isDeepEqual(obj[i], ref[i], options, seen)) {
return false;
}
}
return true;
}
}
else if (instanceType === Types.set) {
if (obj.size !== ref.size) {
return false;
}
if (!internals.isSetSimpleEqual(obj, ref)) {
// Check for deep equality
const ref2 = new Set(Set.prototype.values.call(ref));
for (const objEntry of Set.prototype.values.call(obj)) {
if (ref2.delete(objEntry)) {
continue;
}
let found = false;
for (const refEntry of ref2) {
if (isDeepEqual(objEntry, refEntry, options, seen)) {
ref2.delete(refEntry);
found = true;
break;
}
}
if (!found) {
return false;
}
}
}
}
else if (instanceType === Types.map) {
if (obj.size !== ref.size) {
return false;
}
for (const [key, value] of Map.prototype.entries.call(obj)) {
if (value === undefined && !Map.prototype.has.call(ref, key)) {
return false;
}
if (!isDeepEqual(value, Map.prototype.get.call(ref, key), options, seen)) {
return false;
}
}
}
else if (instanceType === Types.error) {
// Always check name and message
if (obj.name !== ref.name ||
obj.message !== ref.message) {
return false;
}
}
// Check .valueOf()
const valueOfObj = valueOf(obj);
const valueOfRef = valueOf(ref);
if ((obj !== valueOfObj || ref !== valueOfRef) &&
!isDeepEqual(valueOfObj, valueOfRef, options, seen)) {
return false;
}
// Check properties
const objKeys = keys(obj);
if (!options.part &&
objKeys.length !== keys(ref).length &&
!options.skip) {
return false;
}
let skipped = 0;
for (const key of objKeys) {
if (options.skip &&
options.skip.includes(key)) {
if (ref[key] === undefined) {
++skipped;
}
continue;
}
if (!hasOwnEnumerableProperty(ref, key)) {
return false;
}
if (!isDeepEqual(obj[key], ref[key], options, seen)) {
return false;
}
}
if (!options.part &&
objKeys.length - skipped !== keys(ref).length) {
return false;
}
// Check symbols
if (options.symbols !== false) { // Defaults to true
const objSymbols = getOwnPropertySymbols(obj);
const refSymbols = new Set(getOwnPropertySymbols(ref));
for (const key of objSymbols) {
if (!options.skip ||
!options.skip.includes(key)) {
if (hasOwnEnumerableProperty(obj, key)) {
if (!hasOwnEnumerableProperty(ref, key)) {
return false;
}
if (!isDeepEqual(obj[key], ref[key], options, seen)) {
return false;
}
}
else if (hasOwnEnumerableProperty(ref, key)) {
return false;
}
}
refSymbols.delete(key);
}
for (const key of refSymbols) {
if (hasOwnEnumerableProperty(ref, key)) {
return false;
}
}
}
return true;
};
internals.SeenEntry = class {
constructor(obj, ref) {
this.obj = obj;
this.ref = ref;
}
isSame(obj, ref) {
return this.obj === obj && this.ref === ref;
}
};
/***/ }),
/***/ 35563:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
const Stringify = __nccwpck_require__(37577);
const internals = {};
module.exports = class extends Error {
constructor(args) {
const msgs = args
.filter((arg) => arg !== '')
.map((arg) => {
return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg);
});
super(msgs.join(' ') || 'Unknown error');
if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$
Error.captureStackTrace(this, exports.assert);
}
}
};
/***/ }),
/***/ 24752:
/***/ ((module) => {
"use strict";
const internals = {};
module.exports = function (input) {
if (!input) {
return '';
}
let escaped = '';
for (let i = 0; i < input.length; ++i) {
const charCode = input.charCodeAt(i);
if (internals.isSafe(charCode)) {
escaped += input[i];
}
else {
escaped += internals.escapeHtmlChar(charCode);
}
}
return escaped;
};
internals.escapeHtmlChar = function (charCode) {
const namedEscape = internals.namedHtml.get(charCode);
if (namedEscape) {
return namedEscape;
}
if (charCode >= 256) {
return '&#' + charCode + ';';
}
const hexValue = charCode.toString(16).padStart(2, '0');
return `&#x${hexValue};`;
};
internals.isSafe = function (charCode) {
return internals.safeCharCodes.has(charCode);
};
internals.namedHtml = new Map([
[38, '&amp;'],
[60, '&lt;'],
[62, '&gt;'],
[34, '&quot;'],
[160, '&nbsp;'],
[162, '&cent;'],
[163, '&pound;'],
[164, '&curren;'],
[169, '&copy;'],
[174, '&reg;']
]);
internals.safeCharCodes = (function () {
const safe = new Set();
for (let i = 32; i < 123; ++i) {
if ((i >= 97) || // a-z
(i >= 65 && i <= 90) || // A-Z
(i >= 48 && i <= 57) || // 0-9
i === 32 || // space
i === 46 || // .
i === 44 || // ,
i === 45 || // -
i === 58 || // :
i === 95) { // _
safe.add(i);
}
}
return safe;
}());
/***/ }),
/***/ 91965:
/***/ ((module) => {
"use strict";
const internals = {};
module.exports = function (string) {
// Escape ^$.*+-?=!:|\/()[]{},
return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
/***/ }),
/***/ 12887:
/***/ ((module) => {
"use strict";
const internals = {};
module.exports = function () { };
/***/ }),
/***/ 60445:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Utils = __nccwpck_require__(30417);
const internals = {};
module.exports = internals.merge = function (target, source, options) {
Assert(target && typeof target === 'object', 'Invalid target value: must be an object');
Assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
if (!source) {
return target;
}
options = Object.assign({ nullOverride: true, mergeArrays: true }, options);
if (Array.isArray(source)) {
Assert(Array.isArray(target), 'Cannot merge array onto an object');
if (!options.mergeArrays) {
target.length = 0; // Must not change target assignment
}
for (let i = 0; i < source.length; ++i) {
target.push(Clone(source[i], { symbols: options.symbols }));
}
return target;
}
const keys = Utils.keys(source, options);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key === '__proto__' ||
!Object.prototype.propertyIsEnumerable.call(source, key)) {
continue;
}
const value = source[key];
if (value &&
typeof value === 'object') {
if (target[key] === value) {
continue; // Can occur for shallow merges
}
if (!target[key] ||
typeof target[key] !== 'object' ||
(Array.isArray(target[key]) !== Array.isArray(value)) ||
value instanceof Date ||
(Buffer && Buffer.isBuffer(value)) || // $lab:coverage:ignore$
value instanceof RegExp) {
target[key] = Clone(value, { symbols: options.symbols });
}
else {
internals.merge(target[key], value, options);
}
}
else {
if (value !== null &&
value !== undefined) { // Explicit to preserve empty strings
target[key] = value;
}
else if (options.nullOverride) {
target[key] = value;
}
}
}
return target;
};
/***/ }),
/***/ 18891:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const internals = {};
module.exports = function (obj, chain, options) {
if (chain === false ||
chain === null ||
chain === undefined) {
return obj;
}
options = options || {};
if (typeof options === 'string') {
options = { separator: options };
}
const isChainArray = Array.isArray(chain);
Assert(!isChainArray || !options.separator, 'Separator option is not valid for array-based chain');
const path = isChainArray ? chain : chain.split(options.separator || '.');
let ref = obj;
for (let i = 0; i < path.length; ++i) {
let key = path[i];
const type = options.iterables && internals.iterables(ref);
if (Array.isArray(ref) ||
type === 'set') {
const number = Number(key);
if (Number.isInteger(number)) {
key = number < 0 ? ref.length + number : number;
}
}
if (!ref ||
typeof ref === 'function' && options.functions === false || // Defaults to true
!type && ref[key] === undefined) {
Assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain);
Assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
ref = options.default;
break;
}
if (!type) {
ref = ref[key];
}
else if (type === 'set') {
ref = [...ref][key];
}
else { // type === 'map'
ref = ref.get(key);
}
}
return ref;
};
internals.iterables = function (ref) {
if (ref instanceof Set) {
return 'set';
}
if (ref instanceof Map) {
return 'map';
}
};
/***/ }),
/***/ 37577:
/***/ ((module) => {
"use strict";
const internals = {};
module.exports = function (...args) {
try {
return JSON.stringify(...args);
}
catch (err) {
return '[Cannot display object: ' + err.message + ']';
}
};
/***/ }),
/***/ 26657:
/***/ ((module, exports) => {
"use strict";
const internals = {};
exports = module.exports = {
array: Array.prototype,
buffer: Buffer && Buffer.prototype, // $lab:coverage:ignore$
date: Date.prototype,
error: Error.prototype,
generic: Object.prototype,
map: Map.prototype,
promise: Promise.prototype,
regex: RegExp.prototype,
set: Set.prototype,
weakMap: WeakMap.prototype,
weakSet: WeakSet.prototype
};
internals.typeMap = new Map([
['[object Error]', exports.error],
['[object Map]', exports.map],
['[object Promise]', exports.promise],
['[object Set]', exports.set],
['[object WeakMap]', exports.weakMap],
['[object WeakSet]', exports.weakSet]
]);
exports.getInternalProto = function (obj) {
if (Array.isArray(obj)) {
return exports.array;
}
if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$
return exports.buffer;
}
if (obj instanceof Date) {
return exports.date;
}
if (obj instanceof RegExp) {
return exports.regex;
}
if (obj instanceof Error) {
return exports.error;
}
const objName = Object.prototype.toString.call(obj);
return internals.typeMap.get(objName) || exports.generic;
};
/***/ }),
/***/ 30417:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const internals = {};
exports.keys = function (obj, options = {}) {
return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true
};
/***/ }),
/***/ 88392:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const internals = {};
exports.Sorter = class {
constructor() {
this._items = [];
this.nodes = [];
}
add(nodes, options) {
options = options || {};
// Validate rules
const before = [].concat(options.before || []);
const after = [].concat(options.after || []);
const group = options.group || '?';
const sort = options.sort || 0; // Used for merging only
Assert(!before.includes(group), `Item cannot come before itself: ${group}`);
Assert(!before.includes('?'), 'Item cannot come before unassociated items');
Assert(!after.includes(group), `Item cannot come after itself: ${group}`);
Assert(!after.includes('?'), 'Item cannot come after unassociated items');
if (!Array.isArray(nodes)) {
nodes = [nodes];
}
for (const node of nodes) {
const item = {
seq: this._items.length,
sort,
before,
after,
group,
node
};
this._items.push(item);
}
// Insert event
if (!options.manual) {
const valid = this._sort();
Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error');
}
return this.nodes;
}
merge(others) {
if (!Array.isArray(others)) {
others = [others];
}
for (const other of others) {
if (other) {
for (const item of other._items) {
this._items.push(Object.assign({}, item)); // Shallow cloned
}
}
}
// Sort items
this._items.sort(internals.mergeSort);
for (let i = 0; i < this._items.length; ++i) {
this._items[i].seq = i;
}
const valid = this._sort();
Assert(valid, 'merge created a dependencies error');
return this.nodes;
}
sort() {
const valid = this._sort();
Assert(valid, 'sort created a dependencies error');
return this.nodes;
}
_sort() {
// Construct graph
const graph = {};
const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives
const groups = Object.create(null);
for (const item of this._items) {
const seq = item.seq; // Unique across all items
const group = item.group;
// Determine Groups
groups[group] = groups[group] || [];
groups[group].push(seq);
// Build intermediary graph using 'before'
graph[seq] = item.before;
// Build second intermediary graph with 'after'
for (const after of item.after) {
graphAfters[after] = graphAfters[after] || [];
graphAfters[after].push(seq);
}
}
// Expand intermediary graph
for (const node in graph) {
const expandedGroups = [];
for (const graphNodeItem in graph[node]) {
const group = graph[node][graphNodeItem];
groups[group] = groups[group] || [];
expandedGroups.push(...groups[group]);
}
graph[node] = expandedGroups;
}
// Merge intermediary graph using graphAfters into final graph
for (const group in graphAfters) {
if (groups[group]) {
for (const node of groups[group]) {
graph[node].push(...graphAfters[group]);
}
}
}
// Compile ancestors
const ancestors = {};
for (const node in graph) {
const children = graph[node];
for (const child of children) {
ancestors[child] = ancestors[child] || [];
ancestors[child].push(node);
}
}
// Topo sort
const visited = {};
const sorted = [];
for (let i = 0; i < this._items.length; ++i) { // Looping through item.seq values out of order
let next = i;
if (ancestors[i]) {
next = null;
for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values
if (visited[j] === true) {
continue;
}
if (!ancestors[j]) {
ancestors[j] = [];
}
const shouldSeeCount = ancestors[j].length;
let seenCount = 0;
for (let k = 0; k < shouldSeeCount; ++k) {
if (visited[ancestors[j][k]]) {
++seenCount;
}
}
if (seenCount === shouldSeeCount) {
next = j;
break;
}
}
}
if (next !== null) {
visited[next] = true;
sorted.push(next);
}
}
if (sorted.length !== this._items.length) {
return false;
}
const seqIndex = {};
for (const item of this._items) {
seqIndex[item.seq] = item;
}
this._items = [];
this.nodes = [];
for (const value of sorted) {
const sortedItem = seqIndex[value];
this.nodes.push(sortedItem.node);
this._items.push(sortedItem);
}
return true;
}
};
internals.mergeSort = (a, b) => {
return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1);
};
/***/ }),
/***/ 97425:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Url = __nccwpck_require__(57310);
const Errors = __nccwpck_require__(91594);
const internals = {
minDomainSegments: 2,
nonAsciiRx: /[^\x00-\x7f]/,
domainControlRx: /[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/, // Control + space + separators
tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,
domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,
URL: Url.URL || URL // $lab:coverage:ignore$
};
exports.analyze = function (domain, options = {}) {
if (!domain) { // Catch null / undefined
return Errors.code('DOMAIN_NON_EMPTY_STRING');
}
if (typeof domain !== 'string') {
throw new Error('Invalid input: domain must be a string');
}
if (domain.length > 256) {
return Errors.code('DOMAIN_TOO_LONG');
}
const ascii = !internals.nonAsciiRx.test(domain);
if (!ascii) {
if (options.allowUnicode === false) { // Defaults to true
return Errors.code('DOMAIN_INVALID_UNICODE_CHARS');
}
domain = domain.normalize('NFC');
}
if (internals.domainControlRx.test(domain)) {
return Errors.code('DOMAIN_INVALID_CHARS');
}
domain = internals.punycode(domain);
// https://tools.ietf.org/html/rfc1035 section 2.3.1
if (options.allowFullyQualified &&
domain[domain.length - 1] === '.') {
domain = domain.slice(0, -1);
}
const minDomainSegments = options.minDomainSegments || internals.minDomainSegments;
const segments = domain.split('.');
if (segments.length < minDomainSegments) {
return Errors.code('DOMAIN_SEGMENTS_COUNT');
}
if (options.maxDomainSegments) {
if (segments.length > options.maxDomainSegments) {
return Errors.code('DOMAIN_SEGMENTS_COUNT_MAX');
}
}
const tlds = options.tlds;
if (tlds) {
const tld = segments[segments.length - 1].toLowerCase();
if (tlds.deny && tlds.deny.has(tld) ||
tlds.allow && !tlds.allow.has(tld)) {
return Errors.code('DOMAIN_FORBIDDEN_TLDS');
}
}
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (!segment.length) {
return Errors.code('DOMAIN_EMPTY_SEGMENT');
}
if (segment.length > 63) {
return Errors.code('DOMAIN_LONG_SEGMENT');
}
if (i < segments.length - 1) {
if (!internals.domainSegmentRx.test(segment)) {
return Errors.code('DOMAIN_INVALID_CHARS');
}
}
else {
if (!internals.tldSegmentRx.test(segment)) {
return Errors.code('DOMAIN_INVALID_TLDS_CHARS');
}
}
}
return null;
};
exports.isValid = function (domain, options) {
return !exports.analyze(domain, options);
};
internals.punycode = function (domain) {
if (domain.includes('%')) {
domain = domain.replace(/%/g, '%25');
}
try {
return new internals.URL(`http://${domain}`).host;
}
catch (err) {
return domain;
}
};
/***/ }),
/***/ 3283:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Util = __nccwpck_require__(73837);
const Domain = __nccwpck_require__(97425);
const Errors = __nccwpck_require__(91594);
const internals = {
nonAsciiRx: /[^\x00-\x7f]/,
encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$
};
exports.analyze = function (email, options) {
return internals.email(email, options);
};
exports.isValid = function (email, options) {
return !internals.email(email, options);
};
internals.email = function (email, options = {}) {
if (typeof email !== 'string') {
throw new Error('Invalid input: email must be a string');
}
if (!email) {
return Errors.code('EMPTY_STRING');
}
// Unicode
const ascii = !internals.nonAsciiRx.test(email);
if (!ascii) {
if (options.allowUnicode === false) { // Defaults to true
return Errors.code('FORBIDDEN_UNICODE');
}
email = email.normalize('NFC');
}
// Basic structure
const parts = email.split('@');
if (parts.length !== 2) {
return parts.length > 2 ? Errors.code('MULTIPLE_AT_CHAR') : Errors.code('MISSING_AT_CHAR');
}
const [local, domain] = parts;
if (!local) {
return Errors.code('EMPTY_LOCAL');
}
if (!options.ignoreLength) {
if (email.length > 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3
return Errors.code('ADDRESS_TOO_LONG');
}
if (internals.encoder.encode(local).length > 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
return Errors.code('LOCAL_TOO_LONG');
}
}
// Validate parts
return internals.local(local, ascii) || Domain.analyze(domain, options);
};
internals.local = function (local, ascii) {
const segments = local.split('.');
for (const segment of segments) {
if (!segment.length) {
return Errors.code('EMPTY_LOCAL_SEGMENT');
}
if (ascii) {
if (!internals.atextRx.test(segment)) {
return Errors.code('INVALID_LOCAL_CHARS');
}
continue;
}
for (const char of segment) {
if (internals.atextRx.test(char)) {
continue;
}
const binary = internals.binary(char);
if (!internals.atomRx.test(binary)) {
return Errors.code('INVALID_LOCAL_CHARS');
}
}
}
};
internals.binary = function (char) {
return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join('');
};
/*
From RFC 5321:
Mailbox = Local-part "@" ( Domain / address-literal )
Local-part = Dot-string / Quoted-string
Dot-string = Atom *("." Atom)
Atom = 1*atext
atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
Domain = sub-domain *("." sub-domain)
sub-domain = Let-dig [Ldh-str]
Let-dig = ALPHA / DIGIT
Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
ALPHA = %x41-5A / %x61-7A ; a-z, A-Z
DIGIT = %x30-39 ; 0-9
From RFC 6531:
sub-domain =/ U-label
atext =/ UTF8-non-ascii
UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
UTF8-2 = %xC2-DF UTF8-tail
UTF8-3 = %xE0 %xA0-BF UTF8-tail /
%xE1-EC 2( UTF8-tail ) /
%xED %x80-9F UTF8-tail /
%xEE-EF 2( UTF8-tail )
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) /
%xF1-F3 3( UTF8-tail ) /
%xF4 %x80-8F 2( UTF8-tail )
UTF8-tail = %x80-BF
Note: The following are not supported:
RFC 5321: address-literal, Quoted-string
RFC 5322: obs-*, CFWS
*/
internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w
internals.atomRx = new RegExp([
// %xC2-DF UTF8-tail
'(?:[\\xc2-\\xdf][\\x80-\\xbf])',
// %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail )
'(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})',
// %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail )
'(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})'
].join('|'));
/***/ }),
/***/ 91594:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
exports.codes = {
EMPTY_STRING: 'Address must be a non-empty string',
FORBIDDEN_UNICODE: 'Address contains forbidden Unicode characters',
MULTIPLE_AT_CHAR: 'Address cannot contain more than one @ character',
MISSING_AT_CHAR: 'Address must contain one @ character',
EMPTY_LOCAL: 'Address local part cannot be empty',
ADDRESS_TOO_LONG: 'Address too long',
LOCAL_TOO_LONG: 'Address local part too long',
EMPTY_LOCAL_SEGMENT: 'Address local part contains empty dot-separated segment',
INVALID_LOCAL_CHARS: 'Address local part contains invalid character',
DOMAIN_NON_EMPTY_STRING: 'Domain must be a non-empty string',
DOMAIN_TOO_LONG: 'Domain too long',
DOMAIN_INVALID_UNICODE_CHARS: 'Domain contains forbidden Unicode characters',
DOMAIN_INVALID_CHARS: 'Domain contains invalid character',
DOMAIN_INVALID_TLDS_CHARS: 'Domain contains invalid tld character',
DOMAIN_SEGMENTS_COUNT: 'Domain lacks the minimum required number of segments',
DOMAIN_SEGMENTS_COUNT_MAX: 'Domain contains too many segments',
DOMAIN_FORBIDDEN_TLDS: 'Domain uses forbidden TLD',
DOMAIN_EMPTY_SEGMENT: 'Domain contains empty dot-separated segment',
DOMAIN_LONG_SEGMENT: 'Domain contains dot-separated segment that is too long'
};
exports.code = function (code) {
return { code, error: exports.codes[code] };
};
/***/ }),
/***/ 82337:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Uri = __nccwpck_require__(74983);
const internals = {};
exports.regex = function (options = {}) {
// CIDR
Assert(options.cidr === undefined || typeof options.cidr === 'string', 'options.cidr must be a string');
const cidr = options.cidr ? options.cidr.toLowerCase() : 'optional';
Assert(['required', 'optional', 'forbidden'].includes(cidr), 'options.cidr must be one of required, optional, forbidden');
// Versions
Assert(options.version === undefined || typeof options.version === 'string' || Array.isArray(options.version), 'options.version must be a string or an array of string');
let versions = options.version || ['ipv4', 'ipv6', 'ipvfuture'];
if (!Array.isArray(versions)) {
versions = [versions];
}
Assert(versions.length >= 1, 'options.version must have at least 1 version specified');
for (let i = 0; i < versions.length; ++i) {
Assert(typeof versions[i] === 'string', 'options.version must only contain strings');
versions[i] = versions[i].toLowerCase();
Assert(['ipv4', 'ipv6', 'ipvfuture'].includes(versions[i]), 'options.version contains unknown version ' + versions[i] + ' - must be one of ipv4, ipv6, ipvfuture');
}
versions = Array.from(new Set(versions));
// Regex
const parts = versions.map((version) => {
// Forbidden
if (cidr === 'forbidden') {
return Uri.ip[version];
}
// Required
const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`;
if (cidr === 'required') {
return `${Uri.ip[version]}${cidrpart}`;
}
// Optional
return `${Uri.ip[version]}(?:${cidrpart})?`;
});
const raw = `(?:${parts.join('|')})`;
const regex = new RegExp(`^${raw}$`);
return { cidr, versions, regex, raw };
};
/***/ }),
/***/ 53092:
/***/ ((module) => {
"use strict";
const internals = {};
// http://data.iana.org/TLD/tlds-alpha-by-domain.txt
// # Version 2024012900, Last Updated Mon Jan 29 07:07:01 2024 UTC
internals.tlds = [
'AAA',
'AARP',
'ABB',
'ABBOTT',
'ABBVIE',
'ABC',
'ABLE',
'ABOGADO',
'ABUDHABI',
'AC',
'ACADEMY',
'ACCENTURE',
'ACCOUNTANT',
'ACCOUNTANTS',
'ACO',
'ACTOR',
'AD',
'ADS',
'ADULT',
'AE',
'AEG',
'AERO',
'AETNA',
'AF',
'AFL',
'AFRICA',
'AG',
'AGAKHAN',
'AGENCY',
'AI',
'AIG',
'AIRBUS',
'AIRFORCE',
'AIRTEL',
'AKDN',
'AL',
'ALIBABA',
'ALIPAY',
'ALLFINANZ',
'ALLSTATE',
'ALLY',
'ALSACE',
'ALSTOM',
'AM',
'AMAZON',
'AMERICANEXPRESS',
'AMERICANFAMILY',
'AMEX',
'AMFAM',
'AMICA',
'AMSTERDAM',
'ANALYTICS',
'ANDROID',
'ANQUAN',
'ANZ',
'AO',
'AOL',
'APARTMENTS',
'APP',
'APPLE',
'AQ',
'AQUARELLE',
'AR',
'ARAB',
'ARAMCO',
'ARCHI',
'ARMY',
'ARPA',
'ART',
'ARTE',
'AS',
'ASDA',
'ASIA',
'ASSOCIATES',
'AT',
'ATHLETA',
'ATTORNEY',
'AU',
'AUCTION',
'AUDI',
'AUDIBLE',
'AUDIO',
'AUSPOST',
'AUTHOR',
'AUTO',
'AUTOS',
'AVIANCA',
'AW',
'AWS',
'AX',
'AXA',
'AZ',
'AZURE',
'BA',
'BABY',
'BAIDU',
'BANAMEX',
'BAND',
'BANK',
'BAR',
'BARCELONA',
'BARCLAYCARD',
'BARCLAYS',
'BAREFOOT',
'BARGAINS',
'BASEBALL',
'BASKETBALL',
'BAUHAUS',
'BAYERN',
'BB',
'BBC',
'BBT',
'BBVA',
'BCG',
'BCN',
'BD',
'BE',
'BEATS',
'BEAUTY',
'BEER',
'BENTLEY',
'BERLIN',
'BEST',
'BESTBUY',
'BET',
'BF',
'BG',
'BH',
'BHARTI',
'BI',
'BIBLE',
'BID',
'BIKE',
'BING',
'BINGO',
'BIO',
'BIZ',
'BJ',
'BLACK',
'BLACKFRIDAY',
'BLOCKBUSTER',
'BLOG',
'BLOOMBERG',
'BLUE',
'BM',
'BMS',
'BMW',
'BN',
'BNPPARIBAS',
'BO',
'BOATS',
'BOEHRINGER',
'BOFA',
'BOM',
'BOND',
'BOO',
'BOOK',
'BOOKING',
'BOSCH',
'BOSTIK',
'BOSTON',
'BOT',
'BOUTIQUE',
'BOX',
'BR',
'BRADESCO',
'BRIDGESTONE',
'BROADWAY',
'BROKER',
'BROTHER',
'BRUSSELS',
'BS',
'BT',
'BUILD',
'BUILDERS',
'BUSINESS',
'BUY',
'BUZZ',
'BV',
'BW',
'BY',
'BZ',
'BZH',
'CA',
'CAB',
'CAFE',
'CAL',
'CALL',
'CALVINKLEIN',
'CAM',
'CAMERA',
'CAMP',
'CANON',
'CAPETOWN',
'CAPITAL',
'CAPITALONE',
'CAR',
'CARAVAN',
'CARDS',
'CARE',
'CAREER',
'CAREERS',
'CARS',
'CASA',
'CASE',
'CASH',
'CASINO',
'CAT',
'CATERING',
'CATHOLIC',
'CBA',
'CBN',
'CBRE',
'CC',
'CD',
'CENTER',
'CEO',
'CERN',
'CF',
'CFA',
'CFD',
'CG',
'CH',
'CHANEL',
'CHANNEL',
'CHARITY',
'CHASE',
'CHAT',
'CHEAP',
'CHINTAI',
'CHRISTMAS',
'CHROME',
'CHURCH',
'CI',
'CIPRIANI',
'CIRCLE',
'CISCO',
'CITADEL',
'CITI',
'CITIC',
'CITY',
'CK',
'CL',
'CLAIMS',
'CLEANING',
'CLICK',
'CLINIC',
'CLINIQUE',
'CLOTHING',
'CLOUD',
'CLUB',
'CLUBMED',
'CM',
'CN',
'CO',
'COACH',
'CODES',
'COFFEE',
'COLLEGE',
'COLOGNE',
'COM',
'COMCAST',
'COMMBANK',
'COMMUNITY',
'COMPANY',
'COMPARE',
'COMPUTER',
'COMSEC',
'CONDOS',
'CONSTRUCTION',
'CONSULTING',
'CONTACT',
'CONTRACTORS',
'COOKING',
'COOL',
'COOP',
'CORSICA',
'COUNTRY',
'COUPON',
'COUPONS',
'COURSES',
'CPA',
'CR',
'CREDIT',
'CREDITCARD',
'CREDITUNION',
'CRICKET',
'CROWN',
'CRS',
'CRUISE',
'CRUISES',
'CU',
'CUISINELLA',
'CV',
'CW',
'CX',
'CY',
'CYMRU',
'CYOU',
'CZ',
'DABUR',
'DAD',
'DANCE',
'DATA',
'DATE',
'DATING',
'DATSUN',
'DAY',
'DCLK',
'DDS',
'DE',
'DEAL',
'DEALER',
'DEALS',
'DEGREE',
'DELIVERY',
'DELL',
'DELOITTE',
'DELTA',
'DEMOCRAT',
'DENTAL',
'DENTIST',
'DESI',
'DESIGN',
'DEV',
'DHL',
'DIAMONDS',
'DIET',
'DIGITAL',
'DIRECT',
'DIRECTORY',
'DISCOUNT',
'DISCOVER',
'DISH',
'DIY',
'DJ',
'DK',
'DM',
'DNP',
'DO',
'DOCS',
'DOCTOR',
'DOG',
'DOMAINS',
'DOT',
'DOWNLOAD',
'DRIVE',
'DTV',
'DUBAI',
'DUNLOP',
'DUPONT',
'DURBAN',
'DVAG',
'DVR',
'DZ',
'EARTH',
'EAT',
'EC',
'ECO',
'EDEKA',
'EDU',
'EDUCATION',
'EE',
'EG',
'EMAIL',
'EMERCK',
'ENERGY',
'ENGINEER',
'ENGINEERING',
'ENTERPRISES',
'EPSON',
'EQUIPMENT',
'ER',
'ERICSSON',
'ERNI',
'ES',
'ESQ',
'ESTATE',
'ET',
'EU',
'EUROVISION',
'EUS',
'EVENTS',
'EXCHANGE',
'EXPERT',
'EXPOSED',
'EXPRESS',
'EXTRASPACE',
'FAGE',
'FAIL',
'FAIRWINDS',
'FAITH',
'FAMILY',
'FAN',
'FANS',
'FARM',
'FARMERS',
'FASHION',
'FAST',
'FEDEX',
'FEEDBACK',
'FERRARI',
'FERRERO',
'FI',
'FIDELITY',
'FIDO',
'FILM',
'FINAL',
'FINANCE',
'FINANCIAL',
'FIRE',
'FIRESTONE',
'FIRMDALE',
'FISH',
'FISHING',
'FIT',
'FITNESS',
'FJ',
'FK',
'FLICKR',
'FLIGHTS',
'FLIR',
'FLORIST',
'FLOWERS',
'FLY',
'FM',
'FO',
'FOO',
'FOOD',
'FOOTBALL',
'FORD',
'FOREX',
'FORSALE',
'FORUM',
'FOUNDATION',
'FOX',
'FR',
'FREE',
'FRESENIUS',
'FRL',
'FROGANS',
'FRONTIER',
'FTR',
'FUJITSU',
'FUN',
'FUND',
'FURNITURE',
'FUTBOL',
'FYI',
'GA',
'GAL',
'GALLERY',
'GALLO',
'GALLUP',
'GAME',
'GAMES',
'GAP',
'GARDEN',
'GAY',
'GB',
'GBIZ',
'GD',
'GDN',
'GE',
'GEA',
'GENT',
'GENTING',
'GEORGE',
'GF',
'GG',
'GGEE',
'GH',
'GI',
'GIFT',
'GIFTS',
'GIVES',
'GIVING',
'GL',
'GLASS',
'GLE',
'GLOBAL',
'GLOBO',
'GM',
'GMAIL',
'GMBH',
'GMO',
'GMX',
'GN',
'GODADDY',
'GOLD',
'GOLDPOINT',
'GOLF',
'GOO',
'GOODYEAR',
'GOOG',
'GOOGLE',
'GOP',
'GOT',
'GOV',
'GP',
'GQ',
'GR',
'GRAINGER',
'GRAPHICS',
'GRATIS',
'GREEN',
'GRIPE',
'GROCERY',
'GROUP',
'GS',
'GT',
'GU',
'GUARDIAN',
'GUCCI',
'GUGE',
'GUIDE',
'GUITARS',
'GURU',
'GW',
'GY',
'HAIR',
'HAMBURG',
'HANGOUT',
'HAUS',
'HBO',
'HDFC',
'HDFCBANK',
'HEALTH',
'HEALTHCARE',
'HELP',
'HELSINKI',
'HERE',
'HERMES',
'HIPHOP',
'HISAMITSU',
'HITACHI',
'HIV',
'HK',
'HKT',
'HM',
'HN',
'HOCKEY',
'HOLDINGS',
'HOLIDAY',
'HOMEDEPOT',
'HOMEGOODS',
'HOMES',
'HOMESENSE',
'HONDA',
'HORSE',
'HOSPITAL',
'HOST',
'HOSTING',
'HOT',
'HOTELS',
'HOTMAIL',
'HOUSE',
'HOW',
'HR',
'HSBC',
'HT',
'HU',
'HUGHES',
'HYATT',
'HYUNDAI',
'IBM',
'ICBC',
'ICE',
'ICU',
'ID',
'IE',
'IEEE',
'IFM',
'IKANO',
'IL',
'IM',
'IMAMAT',
'IMDB',
'IMMO',
'IMMOBILIEN',
'IN',
'INC',
'INDUSTRIES',
'INFINITI',
'INFO',
'ING',
'INK',
'INSTITUTE',
'INSURANCE',
'INSURE',
'INT',
'INTERNATIONAL',
'INTUIT',
'INVESTMENTS',
'IO',
'IPIRANGA',
'IQ',
'IR',
'IRISH',
'IS',
'ISMAILI',
'IST',
'ISTANBUL',
'IT',
'ITAU',
'ITV',
'JAGUAR',
'JAVA',
'JCB',
'JE',
'JEEP',
'JETZT',
'JEWELRY',
'JIO',
'JLL',
'JM',
'JMP',
'JNJ',
'JO',
'JOBS',
'JOBURG',
'JOT',
'JOY',
'JP',
'JPMORGAN',
'JPRS',
'JUEGOS',
'JUNIPER',
'KAUFEN',
'KDDI',
'KE',
'KERRYHOTELS',
'KERRYLOGISTICS',
'KERRYPROPERTIES',
'KFH',
'KG',
'KH',
'KI',
'KIA',
'KIDS',
'KIM',
'KINDLE',
'KITCHEN',
'KIWI',
'KM',
'KN',
'KOELN',
'KOMATSU',
'KOSHER',
'KP',
'KPMG',
'KPN',
'KR',
'KRD',
'KRED',
'KUOKGROUP',
'KW',
'KY',
'KYOTO',
'KZ',
'LA',
'LACAIXA',
'LAMBORGHINI',
'LAMER',
'LANCASTER',
'LAND',
'LANDROVER',
'LANXESS',
'LASALLE',
'LAT',
'LATINO',
'LATROBE',
'LAW',
'LAWYER',
'LB',
'LC',
'LDS',
'LEASE',
'LECLERC',
'LEFRAK',
'LEGAL',
'LEGO',
'LEXUS',
'LGBT',
'LI',
'LIDL',
'LIFE',
'LIFEINSURANCE',
'LIFESTYLE',
'LIGHTING',
'LIKE',
'LILLY',
'LIMITED',
'LIMO',
'LINCOLN',
'LINK',
'LIPSY',
'LIVE',
'LIVING',
'LK',
'LLC',
'LLP',
'LOAN',
'LOANS',
'LOCKER',
'LOCUS',
'LOL',
'LONDON',
'LOTTE',
'LOTTO',
'LOVE',
'LPL',
'LPLFINANCIAL',
'LR',
'LS',
'LT',
'LTD',
'LTDA',
'LU',
'LUNDBECK',
'LUXE',
'LUXURY',
'LV',
'LY',
'MA',
'MADRID',
'MAIF',
'MAISON',
'MAKEUP',
'MAN',
'MANAGEMENT',
'MANGO',
'MAP',
'MARKET',
'MARKETING',
'MARKETS',
'MARRIOTT',
'MARSHALLS',
'MATTEL',
'MBA',
'MC',
'MCKINSEY',
'MD',
'ME',
'MED',
'MEDIA',
'MEET',
'MELBOURNE',
'MEME',
'MEMORIAL',
'MEN',
'MENU',
'MERCKMSD',
'MG',
'MH',
'MIAMI',
'MICROSOFT',
'MIL',
'MINI',
'MINT',
'MIT',
'MITSUBISHI',
'MK',
'ML',
'MLB',
'MLS',
'MM',
'MMA',
'MN',
'MO',
'MOBI',
'MOBILE',
'MODA',
'MOE',
'MOI',
'MOM',
'MONASH',
'MONEY',
'MONSTER',
'MORMON',
'MORTGAGE',
'MOSCOW',
'MOTO',
'MOTORCYCLES',
'MOV',
'MOVIE',
'MP',
'MQ',
'MR',
'MS',
'MSD',
'MT',
'MTN',
'MTR',
'MU',
'MUSEUM',
'MUSIC',
'MV',
'MW',
'MX',
'MY',
'MZ',
'NA',
'NAB',
'NAGOYA',
'NAME',
'NATURA',
'NAVY',
'NBA',
'NC',
'NE',
'NEC',
'NET',
'NETBANK',
'NETFLIX',
'NETWORK',
'NEUSTAR',
'NEW',
'NEWS',
'NEXT',
'NEXTDIRECT',
'NEXUS',
'NF',
'NFL',
'NG',
'NGO',
'NHK',
'NI',
'NICO',
'NIKE',
'NIKON',
'NINJA',
'NISSAN',
'NISSAY',
'NL',
'NO',
'NOKIA',
'NORTON',
'NOW',
'NOWRUZ',
'NOWTV',
'NP',
'NR',
'NRA',
'NRW',
'NTT',
'NU',
'NYC',
'NZ',
'OBI',
'OBSERVER',
'OFFICE',
'OKINAWA',
'OLAYAN',
'OLAYANGROUP',
'OLLO',
'OM',
'OMEGA',
'ONE',
'ONG',
'ONL',
'ONLINE',
'OOO',
'OPEN',
'ORACLE',
'ORANGE',
'ORG',
'ORGANIC',
'ORIGINS',
'OSAKA',
'OTSUKA',
'OTT',
'OVH',
'PA',
'PAGE',
'PANASONIC',
'PARIS',
'PARS',
'PARTNERS',
'PARTS',
'PARTY',
'PAY',
'PCCW',
'PE',
'PET',
'PF',
'PFIZER',
'PG',
'PH',
'PHARMACY',
'PHD',
'PHILIPS',
'PHONE',
'PHOTO',
'PHOTOGRAPHY',
'PHOTOS',
'PHYSIO',
'PICS',
'PICTET',
'PICTURES',
'PID',
'PIN',
'PING',
'PINK',
'PIONEER',
'PIZZA',
'PK',
'PL',
'PLACE',
'PLAY',
'PLAYSTATION',
'PLUMBING',
'PLUS',
'PM',
'PN',
'PNC',
'POHL',
'POKER',
'POLITIE',
'PORN',
'POST',
'PR',
'PRAMERICA',
'PRAXI',
'PRESS',
'PRIME',
'PRO',
'PROD',
'PRODUCTIONS',
'PROF',
'PROGRESSIVE',
'PROMO',
'PROPERTIES',
'PROPERTY',
'PROTECTION',
'PRU',
'PRUDENTIAL',
'PS',
'PT',
'PUB',
'PW',
'PWC',
'PY',
'QA',
'QPON',
'QUEBEC',
'QUEST',
'RACING',
'RADIO',
'RE',
'READ',
'REALESTATE',
'REALTOR',
'REALTY',
'RECIPES',
'RED',
'REDSTONE',
'REDUMBRELLA',
'REHAB',
'REISE',
'REISEN',
'REIT',
'RELIANCE',
'REN',
'RENT',
'RENTALS',
'REPAIR',
'REPORT',
'REPUBLICAN',
'REST',
'RESTAURANT',
'REVIEW',
'REVIEWS',
'REXROTH',
'RICH',
'RICHARDLI',
'RICOH',
'RIL',
'RIO',
'RIP',
'RO',
'ROCKS',
'RODEO',
'ROGERS',
'ROOM',
'RS',
'RSVP',
'RU',
'RUGBY',
'RUHR',
'RUN',
'RW',
'RWE',
'RYUKYU',
'SA',
'SAARLAND',
'SAFE',
'SAFETY',
'SAKURA',
'SALE',
'SALON',
'SAMSCLUB',
'SAMSUNG',
'SANDVIK',
'SANDVIKCOROMANT',
'SANOFI',
'SAP',
'SARL',
'SAS',
'SAVE',
'SAXO',
'SB',
'SBI',
'SBS',
'SC',
'SCB',
'SCHAEFFLER',
'SCHMIDT',
'SCHOLARSHIPS',
'SCHOOL',
'SCHULE',
'SCHWARZ',
'SCIENCE',
'SCOT',
'SD',
'SE',
'SEARCH',
'SEAT',
'SECURE',
'SECURITY',
'SEEK',
'SELECT',
'SENER',
'SERVICES',
'SEVEN',
'SEW',
'SEX',
'SEXY',
'SFR',
'SG',
'SH',
'SHANGRILA',
'SHARP',
'SHAW',
'SHELL',
'SHIA',
'SHIKSHA',
'SHOES',
'SHOP',
'SHOPPING',
'SHOUJI',
'SHOW',
'SI',
'SILK',
'SINA',
'SINGLES',
'SITE',
'SJ',
'SK',
'SKI',
'SKIN',
'SKY',
'SKYPE',
'SL',
'SLING',
'SM',
'SMART',
'SMILE',
'SN',
'SNCF',
'SO',
'SOCCER',
'SOCIAL',
'SOFTBANK',
'SOFTWARE',
'SOHU',
'SOLAR',
'SOLUTIONS',
'SONG',
'SONY',
'SOY',
'SPA',
'SPACE',
'SPORT',
'SPOT',
'SR',
'SRL',
'SS',
'ST',
'STADA',
'STAPLES',
'STAR',
'STATEBANK',
'STATEFARM',
'STC',
'STCGROUP',
'STOCKHOLM',
'STORAGE',
'STORE',
'STREAM',
'STUDIO',
'STUDY',
'STYLE',
'SU',
'SUCKS',
'SUPPLIES',
'SUPPLY',
'SUPPORT',
'SURF',
'SURGERY',
'SUZUKI',
'SV',
'SWATCH',
'SWISS',
'SX',
'SY',
'SYDNEY',
'SYSTEMS',
'SZ',
'TAB',
'TAIPEI',
'TALK',
'TAOBAO',
'TARGET',
'TATAMOTORS',
'TATAR',
'TATTOO',
'TAX',
'TAXI',
'TC',
'TCI',
'TD',
'TDK',
'TEAM',
'TECH',
'TECHNOLOGY',
'TEL',
'TEMASEK',
'TENNIS',
'TEVA',
'TF',
'TG',
'TH',
'THD',
'THEATER',
'THEATRE',
'TIAA',
'TICKETS',
'TIENDA',
'TIPS',
'TIRES',
'TIROL',
'TJ',
'TJMAXX',
'TJX',
'TK',
'TKMAXX',
'TL',
'TM',
'TMALL',
'TN',
'TO',
'TODAY',
'TOKYO',
'TOOLS',
'TOP',
'TORAY',
'TOSHIBA',
'TOTAL',
'TOURS',
'TOWN',
'TOYOTA',
'TOYS',
'TR',
'TRADE',
'TRADING',
'TRAINING',
'TRAVEL',
'TRAVELERS',
'TRAVELERSINSURANCE',
'TRUST',
'TRV',
'TT',
'TUBE',
'TUI',
'TUNES',
'TUSHU',
'TV',
'TVS',
'TW',
'TZ',
'UA',
'UBANK',
'UBS',
'UG',
'UK',
'UNICOM',
'UNIVERSITY',
'UNO',
'UOL',
'UPS',
'US',
'UY',
'UZ',
'VA',
'VACATIONS',
'VANA',
'VANGUARD',
'VC',
'VE',
'VEGAS',
'VENTURES',
'VERISIGN',
'VERSICHERUNG',
'VET',
'VG',
'VI',
'VIAJES',
'VIDEO',
'VIG',
'VIKING',
'VILLAS',
'VIN',
'VIP',
'VIRGIN',
'VISA',
'VISION',
'VIVA',
'VIVO',
'VLAANDEREN',
'VN',
'VODKA',
'VOLVO',
'VOTE',
'VOTING',
'VOTO',
'VOYAGE',
'VU',
'WALES',
'WALMART',
'WALTER',
'WANG',
'WANGGOU',
'WATCH',
'WATCHES',
'WEATHER',
'WEATHERCHANNEL',
'WEBCAM',
'WEBER',
'WEBSITE',
'WED',
'WEDDING',
'WEIBO',
'WEIR',
'WF',
'WHOSWHO',
'WIEN',
'WIKI',
'WILLIAMHILL',
'WIN',
'WINDOWS',
'WINE',
'WINNERS',
'WME',
'WOLTERSKLUWER',
'WOODSIDE',
'WORK',
'WORKS',
'WORLD',
'WOW',
'WS',
'WTC',
'WTF',
'XBOX',
'XEROX',
'XFINITY',
'XIHUAN',
'XIN',
'XN--11B4C3D',
'XN--1CK2E1B',
'XN--1QQW23A',
'XN--2SCRJ9C',
'XN--30RR7Y',
'XN--3BST00M',
'XN--3DS443G',
'XN--3E0B707E',
'XN--3HCRJ9C',
'XN--3PXU8K',
'XN--42C2D9A',
'XN--45BR5CYL',
'XN--45BRJ9C',
'XN--45Q11C',
'XN--4DBRK0CE',
'XN--4GBRIM',
'XN--54B7FTA0CC',
'XN--55QW42G',
'XN--55QX5D',
'XN--5SU34J936BGSG',
'XN--5TZM5G',
'XN--6FRZ82G',
'XN--6QQ986B3XL',
'XN--80ADXHKS',
'XN--80AO21A',
'XN--80AQECDR1A',
'XN--80ASEHDB',
'XN--80ASWG',
'XN--8Y0A063A',
'XN--90A3AC',
'XN--90AE',
'XN--90AIS',
'XN--9DBQ2A',
'XN--9ET52U',
'XN--9KRT00A',
'XN--B4W605FERD',
'XN--BCK1B9A5DRE4C',
'XN--C1AVG',
'XN--C2BR7G',
'XN--CCK2B3B',
'XN--CCKWCXETD',
'XN--CG4BKI',
'XN--CLCHC0EA0B2G2A9GCD',
'XN--CZR694B',
'XN--CZRS0T',
'XN--CZRU2D',
'XN--D1ACJ3B',
'XN--D1ALF',
'XN--E1A4C',
'XN--ECKVDTC9D',
'XN--EFVY88H',
'XN--FCT429K',
'XN--FHBEI',
'XN--FIQ228C5HS',
'XN--FIQ64B',
'XN--FIQS8S',
'XN--FIQZ9S',
'XN--FJQ720A',
'XN--FLW351E',
'XN--FPCRJ9C3D',
'XN--FZC2C9E2C',
'XN--FZYS8D69UVGM',
'XN--G2XX48C',
'XN--GCKR3F0F',
'XN--GECRJ9C',
'XN--GK3AT1E',
'XN--H2BREG3EVE',
'XN--H2BRJ9C',
'XN--H2BRJ9C8C',
'XN--HXT814E',
'XN--I1B6B1A6A2E',
'XN--IMR513N',
'XN--IO0A7I',
'XN--J1AEF',
'XN--J1AMH',
'XN--J6W193G',
'XN--JLQ480N2RG',
'XN--JVR189M',
'XN--KCRX77D1X4A',
'XN--KPRW13D',
'XN--KPRY57D',
'XN--KPUT3I',
'XN--L1ACC',
'XN--LGBBAT1AD8J',
'XN--MGB9AWBF',
'XN--MGBA3A3EJT',
'XN--MGBA3A4F16A',
'XN--MGBA7C0BBN0A',
'XN--MGBAAM7A8H',
'XN--MGBAB2BD',
'XN--MGBAH1A3HJKRD',
'XN--MGBAI9AZGQP6J',
'XN--MGBAYH7GPA',
'XN--MGBBH1A',
'XN--MGBBH1A71E',
'XN--MGBC0A9AZCG',
'XN--MGBCA7DZDO',
'XN--MGBCPQ6GPA1A',
'XN--MGBERP4A5D4AR',
'XN--MGBGU82A',
'XN--MGBI4ECEXP',
'XN--MGBPL2FH',
'XN--MGBT3DHD',
'XN--MGBTX2B',
'XN--MGBX4CD0AB',
'XN--MIX891F',
'XN--MK1BU44C',
'XN--MXTQ1M',
'XN--NGBC5AZD',
'XN--NGBE9E0A',
'XN--NGBRX',
'XN--NODE',
'XN--NQV7F',
'XN--NQV7FS00EMA',
'XN--NYQY26A',
'XN--O3CW4H',
'XN--OGBPF8FL',
'XN--OTU796D',
'XN--P1ACF',
'XN--P1AI',
'XN--PGBS0DH',
'XN--PSSY2U',
'XN--Q7CE6A',
'XN--Q9JYB4C',
'XN--QCKA1PMC',
'XN--QXA6A',
'XN--QXAM',
'XN--RHQV96G',
'XN--ROVU88B',
'XN--RVC1E0AM3E',
'XN--S9BRJ9C',
'XN--SES554G',
'XN--T60B56A',
'XN--TCKWE',
'XN--TIQ49XQYJ',
'XN--UNUP4Y',
'XN--VERMGENSBERATER-CTB',
'XN--VERMGENSBERATUNG-PWB',
'XN--VHQUV',
'XN--VUQ861B',
'XN--W4R85EL8FHU5DNRA',
'XN--W4RS40L',
'XN--WGBH1C',
'XN--WGBL6A',
'XN--XHQ521B',
'XN--XKC2AL3HYE2A',
'XN--XKC2DL3A5EE0H',
'XN--Y9A3AQ',
'XN--YFRO4I67O',
'XN--YGBI2AMMX',
'XN--ZFR164B',
'XXX',
'XYZ',
'YACHTS',
'YAHOO',
'YAMAXUN',
'YANDEX',
'YE',
'YODOBASHI',
'YOGA',
'YOKOHAMA',
'YOU',
'YOUTUBE',
'YT',
'YUN',
'ZA',
'ZAPPOS',
'ZARA',
'ZERO',
'ZIP',
'ZM',
'ZONE',
'ZUERICH',
'ZW'
];
// Keep as upper-case to make updating from source easier
module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase()));
/***/ }),
/***/ 74983:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const EscapeRegex = __nccwpck_require__(91965);
const internals = {};
internals.generate = function () {
const rfc3986 = {};
const hexDigit = '\\dA-Fa-f'; // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
const hexDigitOnly = '[' + hexDigit + ']';
const unreserved = '\\w-\\.~'; // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
const pctEncoded = '%' + hexDigit; // pct-encoded = "%" HEXDIG HEXDIG
const pchar = unreserved + pctEncoded + subDelims + ':@'; // pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
const pcharOnly = '[' + pchar + ']';
const decOctect = '(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])'; // dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 ; 0-9 / 10-99 / 100-199 / 200-249 / 250-255
rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
/*
h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal
ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address
IPv6address = 6( h16 ":" ) ls32
/ "::" 5( h16 ":" ) ls32
/ [ h16 ] "::" 4( h16 ":" ) ls32
/ [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
/ [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
/ [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
/ [ *4( h16 ":" ) h16 ] "::" ls32
/ [ *5( h16 ":" ) h16 ] "::" h16
/ [ *6( h16 ":" ) h16 ] "::"
*/
const h16 = hexDigitOnly + '{1,4}';
const ls32 = '(?:' + h16 + ':' + h16 + '|' + rfc3986.ipv4address + ')';
const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32;
const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32;
const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32;
const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32;
const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32;
const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32;
const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32;
const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16;
const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::';
rfc3986.ipv4Cidr = '(?:\\d|[1-2]\\d|3[0-2])'; // IPv4 cidr = DIGIT / %x31-32 DIGIT / "3" %x30-32 ; 0-9 / 10-29 / 30-32
rfc3986.ipv6Cidr = '(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])'; // IPv6 cidr = DIGIT / %x31-39 DIGIT / "1" %x0-1 DIGIT / "12" %x0-8; 0-9 / 10-99 / 100-119 / 120-128
rfc3986.ipv6address = '(?:' + IPv6SixHex + '|' + IPv6FiveHex + '|' + IPv6FourHex + '|' + IPv6ThreeHex + '|' + IPv6TwoHex + '|' + IPv6OneHex + '|' + IPv6NoneHex + '|' + IPv6NoneHex2 + '|' + IPv6NoneHex3 + ')';
rfc3986.ipvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
rfc3986.scheme = '[a-zA-Z][a-zA-Z\\d+-\\.]*'; // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
rfc3986.schemeRegex = new RegExp(rfc3986.scheme);
const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; // userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
const IPLiteral = '\\[(?:' + rfc3986.ipv6address + '|' + rfc3986.ipvFuture + ')\\]'; // IP-literal = "[" ( IPv6address / IPvFuture ) "]"
const regName = '[' + unreserved + pctEncoded + subDelims + ']{1,255}'; // reg-name = *( unreserved / pct-encoded / sub-delims )
const host = '(?:' + IPLiteral + '|' + rfc3986.ipv4address + '|' + regName + ')'; // host = IP-literal / IPv4address / reg-name
const port = '\\d*'; // port = *DIGIT
const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; // authority = [ userinfo "@" ] host [ ":" port ]
const authorityCapture = '(?:' + userinfo + '@)?(' + host + ')(?::' + port + ')?';
/*
segment = *pchar
segment-nz = 1*pchar
path = path-abempty ; begins with "/" '|' is empty
/ path-absolute ; begins with "/" but not "//"
/ path-noscheme ; begins with a non-colon segment
/ path-rootless ; begins with a segment
/ path-empty ; zero characters
path-abempty = *( "/" segment )
path-absolute = "/" [ segment-nz *( "/" segment ) ]
path-rootless = segment-nz *( "/" segment )
*/
const segment = pcharOnly + '*';
const segmentNz = pcharOnly + '+';
const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+';
const pathEmpty = '';
const pathAbEmpty = '(?:\\/' + segment + ')*';
const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?';
const pathRootless = segmentNz + pathAbEmpty;
const pathNoScheme = segmentNzNc + pathAbEmpty;
const pathAbNoAuthority = '(?:\\/\\/\\/' + segment + pathAbEmpty + ')'; // Used by file:///
// hier-part = "//" authority path
rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + '|' + pathAbNoAuthority + ')';
rfc3986.hierPartCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + ')';
// relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty
rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')';
rfc3986.relativeRefCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')';
// query = *( pchar / "/" / "?" )
// query = *( pchar / "[" / "]" / "/" / "?" )
rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part '|' end of the line.
rfc3986.queryWithSquareBrackets = '[' + pchar + '\\[\\]\\/\\?]*(?=#|$)';
// fragment = *( pchar / "/" / "?" )
rfc3986.fragment = '[' + pchar + '\\/\\?]*';
return rfc3986;
};
internals.rfc3986 = internals.generate();
exports.ip = {
v4Cidr: internals.rfc3986.ipv4Cidr,
v6Cidr: internals.rfc3986.ipv6Cidr,
ipv4: internals.rfc3986.ipv4address,
ipv6: internals.rfc3986.ipv6address,
ipvfuture: internals.rfc3986.ipvFuture
};
internals.createRegex = function (options) {
const rfc = internals.rfc3986;
// Construct expression
const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query;
const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?';
// relative-ref = relative-part [ "?" query ] [ "#" fragment ]
const relative = options.domain ? rfc.relativeRefCapture : rfc.relativeRef;
if (options.relativeOnly) {
return internals.wrap(relative + suffix);
}
// Custom schemes
let customScheme = '';
if (options.scheme) {
Assert(options.scheme instanceof RegExp || typeof options.scheme === 'string' || Array.isArray(options.scheme), 'scheme must be a RegExp, String, or Array');
const schemes = [].concat(options.scheme);
Assert(schemes.length >= 1, 'scheme must have at least 1 scheme specified');
// Flatten the array into a string to be used to match the schemes
const selections = [];
for (let i = 0; i < schemes.length; ++i) {
const scheme = schemes[i];
Assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String');
if (scheme instanceof RegExp) {
selections.push(scheme.source.toString());
}
else {
Assert(rfc.schemeRegex.test(scheme), 'scheme at position ' + i + ' must be a valid scheme');
selections.push(EscapeRegex(scheme));
}
}
customScheme = selections.join('|');
}
// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
const scheme = customScheme ? '(?:' + customScheme + ')' : rfc.scheme;
const absolute = '(?:' + scheme + ':' + (options.domain ? rfc.hierPartCapture : rfc.hierPart) + ')';
const prefix = options.allowRelative ? '(?:' + absolute + '|' + relative + ')' : absolute;
return internals.wrap(prefix + suffix, customScheme);
};
internals.wrap = function (raw, scheme) {
raw = `(?=.)(?!https?\:/(?:$|[^/]))(?!https?\:///)(?!https?\:[^/])${raw}`; // Require at least one character and explicitly forbid 'http:/' or HTTP with empty domain
return {
raw,
regex: new RegExp(`^${raw}$`),
scheme
};
};
internals.uriRegex = internals.createRegex({});
exports.regex = function (options = {}) {
if (options.scheme ||
options.allowRelative ||
options.relativeOnly ||
options.allowQuerySquareBrackets ||
options.domain) {
return internals.createRegex(options);
}
return internals.uriRegex;
};
/***/ }),
/***/ 34379:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const internals = {
operators: ['!', '^', '*', '/', '%', '+', '-', '<', '<=', '>', '>=', '==', '!=', '&&', '||', '??'],
operatorCharacters: ['!', '^', '*', '/', '%', '+', '-', '<', '=', '>', '&', '|', '?'],
operatorsOrder: [['^'], ['*', '/', '%'], ['+', '-'], ['<', '<=', '>', '>='], ['==', '!='], ['&&'], ['||', '??']],
operatorsPrefix: ['!', 'n'],
literals: {
'"': '"',
'`': '`',
'\'': '\'',
'[': ']'
},
numberRx: /^(?:[0-9]*(\.[0-9]*)?){1}$/,
tokenRx: /^[\w\$\#\.\@\:\{\}]+$/,
symbol: Symbol('formula'),
settings: Symbol('settings')
};
exports.Parser = class {
constructor(string, options = {}) {
if (!options[internals.settings] &&
options.constants) {
for (const constant in options.constants) {
const value = options.constants[constant];
if (value !== null &&
!['boolean', 'number', 'string'].includes(typeof value)) {
throw new Error(`Formula constant ${constant} contains invalid ${typeof value} value type`);
}
}
}
this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options);
this.single = null;
this._parts = null;
this._parse(string);
}
_parse(string) {
let parts = [];
let current = '';
let parenthesis = 0;
let literal = false;
const flush = (inner) => {
if (parenthesis) {
throw new Error('Formula missing closing parenthesis');
}
const last = parts.length ? parts[parts.length - 1] : null;
if (!literal &&
!current &&
!inner) {
return;
}
if (last &&
last.type === 'reference' &&
inner === ')') { // Function
last.type = 'function';
last.value = this._subFormula(current, last.value);
current = '';
return;
}
if (inner === ')') { // Segment
const sub = new exports.Parser(current, this.settings);
parts.push({ type: 'segment', value: sub });
}
else if (literal) {
if (literal === ']') { // Reference
parts.push({ type: 'reference', value: current });
current = '';
return;
}
parts.push({ type: 'literal', value: current }); // Literal
}
else if (internals.operatorCharacters.includes(current)) { // Operator
if (last &&
last.type === 'operator' &&
internals.operators.includes(last.value + current)) { // 2 characters operator
last.value += current;
}
else {
parts.push({ type: 'operator', value: current });
}
}
else if (current.match(internals.numberRx)) { // Number
parts.push({ type: 'constant', value: parseFloat(current) });
}
else if (this.settings.constants[current] !== undefined) { // Constant
parts.push({ type: 'constant', value: this.settings.constants[current] });
}
else { // Reference
if (!current.match(internals.tokenRx)) {
throw new Error(`Formula contains invalid token: ${current}`);
}
parts.push({ type: 'reference', value: current });
}
current = '';
};
for (const c of string) {
if (literal) {
if (c === literal) {
flush();
literal = false;
}
else {
current += c;
}
}
else if (parenthesis) {
if (c === '(') {
current += c;
++parenthesis;
}
else if (c === ')') {
--parenthesis;
if (!parenthesis) {
flush(c);
}
else {
current += c;
}
}
else {
current += c;
}
}
else if (c in internals.literals) {
literal = internals.literals[c];
}
else if (c === '(') {
flush();
++parenthesis;
}
else if (internals.operatorCharacters.includes(c)) {
flush();
current = c;
flush();
}
else if (c !== ' ') {
current += c;
}
else {
flush();
}
}
flush();
// Replace prefix - to internal negative operator
parts = parts.map((part, i) => {
if (part.type !== 'operator' ||
part.value !== '-' ||
i && parts[i - 1].type !== 'operator') {
return part;
}
return { type: 'operator', value: 'n' };
});
// Validate tokens order
let operator = false;
for (const part of parts) {
if (part.type === 'operator') {
if (internals.operatorsPrefix.includes(part.value)) {
continue;
}
if (!operator) {
throw new Error('Formula contains an operator in invalid position');
}
if (!internals.operators.includes(part.value)) {
throw new Error(`Formula contains an unknown operator ${part.value}`);
}
}
else if (operator) {
throw new Error('Formula missing expected operator');
}
operator = !operator;
}
if (!operator) {
throw new Error('Formula contains invalid trailing operator');
}
// Identify single part
if (parts.length === 1 &&
['reference', 'literal', 'constant'].includes(parts[0].type)) {
this.single = { type: parts[0].type === 'reference' ? 'reference' : 'value', value: parts[0].value };
}
// Process parts
this._parts = parts.map((part) => {
// Operators
if (part.type === 'operator') {
return internals.operatorsPrefix.includes(part.value) ? part : part.value;
}
// Literals, constants, segments
if (part.type !== 'reference') {
return part.value;
}
// References
if (this.settings.tokenRx &&
!this.settings.tokenRx.test(part.value)) {
throw new Error(`Formula contains invalid reference ${part.value}`);
}
if (this.settings.reference) {
return this.settings.reference(part.value);
}
return internals.reference(part.value);
});
}
_subFormula(string, name) {
const method = this.settings.functions[name];
if (typeof method !== 'function') {
throw new Error(`Formula contains unknown function ${name}`);
}
let args = [];
if (string) {
let current = '';
let parenthesis = 0;
let literal = false;
const flush = () => {
if (!current) {
throw new Error(`Formula contains function ${name} with invalid arguments ${string}`);
}
args.push(current);
current = '';
};
for (let i = 0; i < string.length; ++i) {
const c = string[i];
if (literal) {
current += c;
if (c === literal) {
literal = false;
}
}
else if (c in internals.literals &&
!parenthesis) {
current += c;
literal = internals.literals[c];
}
else if (c === ',' &&
!parenthesis) {
flush();
}
else {
current += c;
if (c === '(') {
++parenthesis;
}
else if (c === ')') {
--parenthesis;
}
}
}
flush();
}
args = args.map((arg) => new exports.Parser(arg, this.settings));
return function (context) {
const innerValues = [];
for (const arg of args) {
innerValues.push(arg.evaluate(context));
}
return method.call(context, ...innerValues);
};
}
evaluate(context) {
const parts = this._parts.slice();
// Prefix operators
for (let i = parts.length - 2; i >= 0; --i) {
const part = parts[i];
if (part &&
part.type === 'operator') {
const current = parts[i + 1];
parts.splice(i + 1, 1);
const value = internals.evaluate(current, context);
parts[i] = internals.single(part.value, value);
}
}
// Left-right operators
internals.operatorsOrder.forEach((set) => {
for (let i = 1; i < parts.length - 1;) {
if (set.includes(parts[i])) {
const operator = parts[i];
const left = internals.evaluate(parts[i - 1], context);
const right = internals.evaluate(parts[i + 1], context);
parts.splice(i, 2);
const result = internals.calculate(operator, left, right);
parts[i - 1] = result === 0 ? 0 : result; // Convert -0
}
else {
i += 2;
}
}
});
return internals.evaluate(parts[0], context);
}
};
exports.Parser.prototype[internals.symbol] = true;
internals.reference = function (name) {
return function (context) {
return context && context[name] !== undefined ? context[name] : null;
};
};
internals.evaluate = function (part, context) {
if (part === null) {
return null;
}
if (typeof part === 'function') {
return part(context);
}
if (part[internals.symbol]) {
return part.evaluate(context);
}
return part;
};
internals.single = function (operator, value) {
if (operator === '!') {
return value ? false : true;
}
// operator === 'n'
const negative = -value;
if (negative === 0) { // Override -0
return 0;
}
return negative;
};
internals.calculate = function (operator, left, right) {
if (operator === '??') {
return internals.exists(left) ? left : right;
}
if (typeof left === 'string' ||
typeof right === 'string') {
if (operator === '+') {
left = internals.exists(left) ? left : '';
right = internals.exists(right) ? right : '';
return left + right;
}
}
else {
switch (operator) {
case '^': return Math.pow(left, right);
case '*': return left * right;
case '/': return left / right;
case '%': return left % right;
case '+': return left + right;
case '-': return left - right;
}
}
switch (operator) {
case '<': return left < right;
case '<=': return left <= right;
case '>': return left > right;
case '>=': return left >= right;
case '==': return left === right;
case '!=': return left !== right;
case '&&': return left && right;
case '||': return left || right;
}
return null;
};
internals.exists = function (value) {
return value !== null && value !== undefined;
};
/***/ }),
/***/ 75604:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const internals = {};
exports.location = function (depth = 0) {
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (ignore, stack) => stack;
const capture = {};
Error.captureStackTrace(capture, this);
const line = capture.stack[depth + 1];
Error.prepareStackTrace = orig;
return {
filename: line.getFileName(),
line: line.getLineNumber()
};
};
/***/ }),
/***/ 32861:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* module decorator */ module = __nccwpck_require__.nmd(module);
function noop () { }
const proto = {
fatal: noop,
error: noop,
warn: noop,
info: noop,
debug: noop,
trace: noop
}
Object.defineProperty(module, 'exports', {
get () {
return Object.create(proto)
}
})
/***/ }),
/***/ 20407:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
function fmtDef(validate, compare) {
return { validate, compare };
}
exports.fullFormats = {
// date: http://tools.ietf.org/html/rfc3339#section-5.6
date: fmtDef(date, compareDate),
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
time: fmtDef(time, compareTime),
"date-time": fmtDef(date_time, compareDateTime),
// duration: https://tools.ietf.org/html/rfc3339#appendix-A
duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
uri,
"uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
// uri-template: https://tools.ietf.org/html/rfc6570
"uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
regex,
// uuid: http://tools.ietf.org/html/rfc4122
uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
// JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
"json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
"relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
// the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
// byte: https://github.com/miguelmota/is-base64
byte,
// signed 32 bit integer
int32: { type: "number", validate: validateInt32 },
// signed 64 bit integer
int64: { type: "number", validate: validateInt64 },
// C-type float
float: { type: "number", validate: validateNumber },
// C-type double
double: { type: "number", validate: validateNumber },
// hint to the UI to hide input strings
password: true,
// unchecked string payload
binary: true,
};
exports.fastFormats = {
...exports.fullFormats,
date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareTime),
"date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
"uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
// email (sources from jsen validator):
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
};
exports.formatNames = Object.keys(exports.fullFormats);
function isLeapYear(year) {
// https://tools.ietf.org/html/rfc3339#appendix-C
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
const matches = DATE.exec(str);
if (!matches)
return false;
const year = +matches[1];
const month = +matches[2];
const day = +matches[3];
return (month >= 1 &&
month <= 12 &&
day >= 1 &&
day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));
}
function compareDate(d1, d2) {
if (!(d1 && d2))
return undefined;
if (d1 > d2)
return 1;
if (d1 < d2)
return -1;
return 0;
}
const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
function time(str, withTimeZone) {
const matches = TIME.exec(str);
if (!matches)
return false;
const hour = +matches[1];
const minute = +matches[2];
const second = +matches[3];
const timeZone = matches[5];
return (((hour <= 23 && minute <= 59 && second <= 59) ||
(hour === 23 && minute === 59 && second === 60)) &&
(!withTimeZone || timeZone !== ""));
}
function compareTime(t1, t2) {
if (!(t1 && t2))
return undefined;
const a1 = TIME.exec(t1);
const a2 = TIME.exec(t2);
if (!(a1 && a2))
return undefined;
t1 = a1[1] + a1[2] + a1[3] + (a1[4] || "");
t2 = a2[1] + a2[2] + a2[3] + (a2[4] || "");
if (t1 > t2)
return 1;
if (t1 < t2)
return -1;
return 0;
}
const DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
// http://tools.ietf.org/html/rfc3339#section-5.6
const dateTime = str.split(DATE_TIME_SEPARATOR);
return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true);
}
function compareDateTime(dt1, dt2) {
if (!(dt1 && dt2))
return undefined;
const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
const res = compareDate(d1, d2);
if (res === undefined)
return undefined;
return res || compareTime(t1, t2);
}
const NOT_URI_FRAGMENT = /\/|:/;
const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
function uri(str) {
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
function byte(str) {
BYTE.lastIndex = 0;
return BYTE.test(str);
}
const MIN_INT32 = -(2 ** 31);
const MAX_INT32 = 2 ** 31 - 1;
function validateInt32(value) {
return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
}
function validateInt64(value) {
// JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64
return Number.isInteger(value);
}
function validateNumber() {
return true;
}
const Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
if (Z_ANCHOR.test(str))
return false;
try {
new RegExp(str);
return true;
}
catch (e) {
return false;
}
}
//# sourceMappingURL=formats.js.map
/***/ }),
/***/ 567:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const formats_1 = __nccwpck_require__(20407);
const limit_1 = __nccwpck_require__(89930);
const codegen_1 = __nccwpck_require__(20893);
const fullName = new codegen_1.Name("fullFormats");
const fastName = new codegen_1.Name("fastFormats");
const formatsPlugin = (ajv, opts = { keywords: true }) => {
if (Array.isArray(opts)) {
addFormats(ajv, opts, formats_1.fullFormats, fullName);
return ajv;
}
const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
const list = opts.formats || formats_1.formatNames;
addFormats(ajv, list, formats, exportName);
if (opts.keywords)
limit_1.default(ajv);
return ajv;
};
formatsPlugin.get = (name, mode = "full") => {
const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
const f = formats[name];
if (!f)
throw new Error(`Unknown format "${name}"`);
return f;
};
function addFormats(ajv, list, fs, exportName) {
var _a;
var _b;
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = codegen_1._ `require("ajv-formats/dist/formats").${exportName}`);
for (const f of list)
ajv.addFormat(f, fs[f]);
}
module.exports = exports = formatsPlugin;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = formatsPlugin;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 89930:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatLimitDefinition = void 0;
const ajv_1 = __nccwpck_require__(62623);
const codegen_1 = __nccwpck_require__(20893);
const ops = codegen_1.operators;
const KWDs = {
formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
message: ({ keyword, schemaCode }) => codegen_1.str `should be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => codegen_1._ `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
exports.formatLimitDefinition = {
keyword: Object.keys(KWDs),
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, keyword, it } = cxt;
const { opts, self } = it;
if (!opts.validateFormats)
return;
const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
if (fCxt.$data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
});
const fmt = gen.const("fmt", codegen_1._ `${fmts}[${fCxt.schemaCode}]`);
cxt.fail$data(codegen_1.or(codegen_1._ `typeof ${fmt} != "object"`, codegen_1._ `${fmt} instanceof RegExp`, codegen_1._ `typeof ${fmt}.compare != "function"`, compareCode(fmt)));
}
function validateFormat() {
const format = fCxt.schema;
const fmtDef = self.formats[format];
if (!fmtDef || fmtDef === true)
return;
if (typeof fmtDef != "object" ||
fmtDef instanceof RegExp ||
typeof fmtDef.compare != "function") {
throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
}
const fmt = gen.scopeValue("formats", {
key: format,
ref: fmtDef,
code: opts.code.formats ? codegen_1._ `${opts.code.formats}${codegen_1.getProperty(format)}` : undefined,
});
cxt.fail$data(compareCode(fmt));
}
function compareCode(fmt) {
return codegen_1._ `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
}
},
dependencies: ["format"],
};
const formatLimitPlugin = (ajv) => {
ajv.addKeyword(exports.formatLimitDefinition);
return ajv;
};
exports["default"] = formatLimitPlugin;
//# sourceMappingURL=limit.js.map
/***/ }),
/***/ 62623:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = __nccwpck_require__(77626);
const draft7_1 = __nccwpck_require__(49329);
const discriminator_1 = __nccwpck_require__(32818);
const draft7MetaSchema = __nccwpck_require__(90074);
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
_addVocabularies() {
super._addVocabularies();
draft7_1.default.forEach((v) => this.addVocabulary(v));
if (this.opts.discriminator)
this.addKeyword(discriminator_1.default);
}
_addDefaultMetaSchema() {
super._addDefaultMetaSchema();
if (!this.opts.meta)
return;
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema;
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
}
defaultMeta() {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
}
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = Ajv;
var validate_1 = __nccwpck_require__(66569);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(20893);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
var validation_error_1 = __nccwpck_require__(9684);
Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } }));
var ref_error_1 = __nccwpck_require__(19083);
Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } }));
//# sourceMappingURL=ajv.js.map
/***/ }),
/***/ 8476:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
constructor(s) {
super();
if (!exports.IDENTIFIER.test(s))
throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return false;
}
get names() {
return { [this.str]: 1 };
}
}
exports.Name = Name;
class _Code extends _CodeOrName {
constructor(code) {
super();
this._items = typeof code === "string" ? [code] : code;
}
toString() {
return this.str;
}
emptyStr() {
if (this._items.length > 1)
return false;
const item = this._items[0];
return item === "" || item === '""';
}
get str() {
var _a;
return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
}
get names() {
var _a;
return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
if (c instanceof Name)
names[c.str] = (names[c.str] || 0) + 1;
return names;
}, {})));
}
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
const code = [strs[0]];
let i = 0;
while (i < args.length) {
addCodeArg(code, args[i]);
code.push(strs[++i]);
}
return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
const expr = [safeStringify(strs[0])];
let i = 0;
while (i < args.length) {
expr.push(plus);
addCodeArg(expr, args[i]);
expr.push(plus, safeStringify(strs[++i]));
}
optimize(expr);
return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
if (arg instanceof _Code)
code.push(...arg._items);
else if (arg instanceof Name)
code.push(arg);
else
code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
while (i < expr.length - 1) {
if (expr[i] === plus) {
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
if (res !== undefined) {
expr.splice(i - 1, 3, res);
continue;
}
expr[i++] = "+";
}
i++;
}
}
function mergeExprItems(a, b) {
if (b === '""')
return a;
if (a === '""')
return b;
if (typeof a == "string") {
if (b instanceof Name || a[a.length - 1] !== '"')
return;
if (typeof b != "string")
return `${a.slice(0, -1)}${b}"`;
if (b[0] === '"')
return a.slice(0, -1) + b.slice(1);
return;
}
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
return `"${a}${b.slice(1)}`;
return;
}
function strConcat(c1, c2) {
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
return typeof x == "number" || typeof x == "boolean" || x === null
? x
: safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
return JSON.stringify(x)
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
return new _Code(`${key}`);
}
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 20893:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = __nccwpck_require__(8476);
const scope_1 = __nccwpck_require__(58105);
var code_2 = __nccwpck_require__(8476);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return code_2._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return code_2.str; } }));
Object.defineProperty(exports, "strConcat", ({ enumerable: true, get: function () { return code_2.strConcat; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return code_2.nil; } }));
Object.defineProperty(exports, "getProperty", ({ enumerable: true, get: function () { return code_2.getProperty; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return code_2.stringify; } }));
Object.defineProperty(exports, "regexpCode", ({ enumerable: true, get: function () { return code_2.regexpCode; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return code_2.Name; } }));
var scope_2 = __nccwpck_require__(58105);
Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return scope_2.Scope; } }));
Object.defineProperty(exports, "ValueScope", ({ enumerable: true, get: function () { return scope_2.ValueScope; } }));
Object.defineProperty(exports, "ValueScopeName", ({ enumerable: true, get: function () { return scope_2.ValueScopeName; } }));
Object.defineProperty(exports, "varKinds", ({ enumerable: true, get: function () { return scope_2.varKinds; } }));
exports.operators = {
GT: new code_1._Code(">"),
GTE: new code_1._Code(">="),
LT: new code_1._Code("<"),
LTE: new code_1._Code("<="),
EQ: new code_1._Code("==="),
NEQ: new code_1._Code("!=="),
NOT: new code_1._Code("!"),
OR: new code_1._Code("||"),
AND: new code_1._Code("&&"),
ADD: new code_1._Code("+"),
};
class Node {
optimizeNodes() {
return this;
}
optimizeNames(_names, _constants) {
return this;
}
}
class Def extends Node {
constructor(varKind, name, rhs) {
super();
this.varKind = varKind;
this.name = name;
this.rhs = rhs;
}
render({ es5, _n }) {
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names, constants) {
if (!names[this.name.str])
return;
if (this.rhs)
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
}
class Assign extends Node {
constructor(lhs, rhs, sideEffects) {
super();
this.lhs = lhs;
this.rhs = rhs;
this.sideEffects = sideEffects;
}
render({ _n }) {
return `${this.lhs} = ${this.rhs};` + _n;
}
optimizeNames(names, constants) {
if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
return;
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
return addExprNames(names, this.rhs);
}
}
class AssignOp extends Assign {
constructor(lhs, op, rhs, sideEffects) {
super(lhs, rhs, sideEffects);
this.op = op;
}
render({ _n }) {
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
}
}
class Label extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
}
class Break extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
const label = this.label ? ` ${this.label}` : "";
return `break${label};` + _n;
}
}
class Throw extends Node {
constructor(error) {
super();
this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
}
class AnyCode extends Node {
constructor(code) {
super();
this.code = code;
}
render({ _n }) {
return `${this.code};` + _n;
}
optimizeNodes() {
return `${this.code}` ? this : undefined;
}
optimizeNames(names, constants) {
this.code = optimizeExpr(this.code, names, constants);
return this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
}
class ParentNode extends Node {
constructor(nodes = []) {
super();
this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i].optimizeNodes();
if (Array.isArray(n))
nodes.splice(i, 1, ...n);
else if (n)
nodes[i] = n;
else
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
optimizeNames(names, constants) {
const { nodes } = this;
let i = nodes.length;
while (i--) {
// iterating backwards improves 1-pass optimization
const n = nodes[i];
if (n.optimizeNames(names, constants))
continue;
subtractNames(names, n.names);
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
get names() {
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
}
}
class BlockNode extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
constructor(condition, nodes) {
super(nodes);
this.condition = condition;
}
render(opts) {
let code = `if(${this.condition})` + super.render(opts);
if (this.else)
code += "else " + this.else.render(opts);
return code;
}
optimizeNodes() {
super.optimizeNodes();
const cond = this.condition;
if (cond === true)
return this.nodes; // else is ignored here
let e = this.else;
if (e) {
const ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e) {
if (cond === false)
return e instanceof If ? e : e.nodes;
if (this.nodes.length)
return this;
return new If(not(cond), e instanceof If ? [e] : e.nodes);
}
if (cond === false || !this.nodes.length)
return undefined;
return this;
}
optimizeNames(names, constants) {
var _a;
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
if (!(super.optimizeNames(names, constants) || this.else))
return;
this.condition = optimizeExpr(this.condition, names, constants);
return this;
}
get names() {
const names = super.names;
addExprNames(names, this.condition);
if (this.else)
addNames(names, this.else.names);
return names;
}
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
constructor(iteration) {
super();
this.iteration = iteration;
}
render(opts) {
return `for(${this.iteration})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iteration = optimizeExpr(this.iteration, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
}
class ForRange extends For {
constructor(varKind, name, from, to) {
super();
this.varKind = varKind;
this.name = name;
this.from = from;
this.to = to;
}
render(opts) {
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
const { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
const names = addExprNames(super.names, this.from);
return addExprNames(names, this.to);
}
}
class ForIter extends For {
constructor(loop, varKind, name, iterable) {
super();
this.loop = loop;
this.varKind = varKind;
this.name = name;
this.iterable = iterable;
}
render(opts) {
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iterable = optimizeExpr(this.iterable, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
}
class Func extends BlockNode {
constructor(name, args, async) {
super();
this.name = name;
this.args = args;
this.async = async;
}
render(opts) {
const _async = this.async ? "async " : "";
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
}
}
Func.kind = "func";
class Return extends ParentNode {
render(opts) {
return "return " + super.render(opts);
}
}
Return.kind = "return";
class Try extends BlockNode {
render(opts) {
let code = "try" + super.render(opts);
if (this.catch)
code += this.catch.render(opts);
if (this.finally)
code += this.finally.render(opts);
return code;
}
optimizeNodes() {
var _a, _b;
super.optimizeNodes();
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
return this;
}
optimizeNames(names, constants) {
var _a, _b;
super.optimizeNames(names, constants);
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
return this;
}
get names() {
const names = super.names;
if (this.catch)
addNames(names, this.catch.names);
if (this.finally)
addNames(names, this.finally.names);
return names;
}
}
class Catch extends BlockNode {
constructor(error) {
super();
this.error = error;
}
render(opts) {
return `catch(${this.error})` + super.render(opts);
}
}
Catch.kind = "catch";
class Finally extends BlockNode {
render(opts) {
return "finally" + super.render(opts);
}
}
Finally.kind = "finally";
class CodeGen {
constructor(extScope, opts = {}) {
this._values = {};
this._blockStarts = [];
this._constants = {};
this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
this._extScope = extScope;
this._scope = new scope_1.Scope({ parent: extScope });
this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
// returns unique name in the internal scope
name(prefix) {
return this._scope.name(prefix);
}
// reserves unique name in the external scope
scopeName(prefix) {
return this._extScope.name(prefix);
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName, value) {
const name = this._extScope.value(prefixOrName, value);
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
vs.add(name);
return name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
const name = this._scope.toName(nameOrPrefix);
if (rhs !== undefined && constant)
this._constants[name.str] = rhs;
this._leafNode(new Def(varKind, name, rhs));
return name;
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
// `var` declaration with optional assignment
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
// assignment code
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
// `+=` code
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
// appends passed SafeExpr to code or executes Block
code(c) {
if (typeof c == "function")
c();
else if (c !== code_1.nil)
this._leafNode(new AnyCode(c));
return this;
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues) {
const code = ["{"];
for (const [key, value] of keyValues) {
if (code.length > 1)
code.push(",");
code.push(key);
if (key !== value || this.opts.es5) {
code.push(":");
(0, code_1.addCodeArg)(code, value);
}
}
code.push("}");
return new code_1._Code(code);
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition, thenBody, elseBody) {
this._blockNode(new If(condition));
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf();
}
else if (thenBody) {
this.code(thenBody).endIf();
}
else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body');
}
return this;
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition) {
return this._elseNode(new If(condition));
}
// `else` clause - only valid after `if` or `else if` clauses
else() {
return this._elseNode(new Else());
}
// end `if` statement (needed if gen.if was used only with condition)
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
this._blockNode(node);
if (forBody)
this.code(forBody).endFor();
return this;
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
// `for` statement for a range of values
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
const name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
this.var(name, (0, code_1._) `${arr}[${i}]`);
forBody(name);
});
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
}
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
// end `for` loop
endFor() {
return this._endBlockNode(For);
}
// `label` statement
label(label) {
return this._leafNode(new Label(label));
}
// `break` statement
break(label) {
return this._leafNode(new Break(label));
}
// `return` statement
return(value) {
const node = new Return();
this._blockNode(node);
this.code(value);
if (node.nodes.length !== 1)
throw new Error('CodeGen: "return" should have one node');
return this._endBlockNode(Return);
}
// `try` statement
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode)
throw new Error('CodeGen: "try" without "catch" and "finally"');
const node = new Try();
this._blockNode(node);
this.code(tryBody);
if (catchCode) {
const error = this.name("e");
this._currNode = node.catch = new Catch(error);
catchCode(error);
}
if (finallyCode) {
this._currNode = node.finally = new Finally();
this.code(finallyCode);
}
return this._endBlockNode(Catch, Finally);
}
// `throw` statement
throw(error) {
return this._leafNode(new Throw(error));
}
// start self-balancing block
block(body, nodeCount) {
this._blockStarts.push(this._nodes.length);
if (body)
this.code(body).endBlock(nodeCount);
return this;
}
// end the current self-balancing block
endBlock(nodeCount) {
const len = this._blockStarts.pop();
if (len === undefined)
throw new Error("CodeGen: not in self-balancing block");
const toClose = this._nodes.length - len;
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
}
this._nodes.length = len;
return this;
}
// `function` heading (or definition if funcBody is passed)
func(name, args = code_1.nil, async, funcBody) {
this._blockNode(new Func(name, args, async));
if (funcBody)
this.code(funcBody).endFunc();
return this;
}
// end function definition
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
while (n-- > 0) {
this._root.optimizeNodes();
this._root.optimizeNames(this._root.names, this._constants);
}
}
_leafNode(node) {
this._currNode.nodes.push(node);
return this;
}
_blockNode(node) {
this._currNode.nodes.push(node);
this._nodes.push(node);
}
_endBlockNode(N1, N2) {
const n = this._currNode;
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop();
return this;
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
const n = this._currNode;
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"');
}
this._currNode = n.else = node;
return this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
const ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
const ns = this._nodes;
ns[ns.length - 1] = node;
}
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) + (from[n] || 0);
return names;
}
function addExprNames(names, from) {
return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
if (expr instanceof code_1.Name)
return replaceName(expr);
if (!canOptimize(expr))
return expr;
return new code_1._Code(expr._items.reduce((items, c) => {
if (c instanceof code_1.Name)
c = replaceName(c);
if (c instanceof code_1._Code)
items.push(...c._items);
else
items.push(c);
return items;
}, []));
function replaceName(n) {
const c = constants[n.str];
if (c === undefined || names[n.str] !== 1)
return n;
delete names[n.str];
return c;
}
function canOptimize(e) {
return (e instanceof code_1._Code &&
e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
}
}
function subtractNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 58105:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = __nccwpck_require__(8476);
class ValueError extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`);
this.value = name.value;
}
}
var UsedValueState;
(function (UsedValueState) {
UsedValueState[UsedValueState["Started"] = 0] = "Started";
UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
const: new code_1.Name("const"),
let: new code_1.Name("let"),
var: new code_1.Name("var"),
};
class Scope {
constructor({ prefixes, parent } = {}) {
this._names = {};
this._prefixes = prefixes;
this._parent = parent;
}
toName(nameOrPrefix) {
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
}
name(prefix) {
return new code_1.Name(this._newName(prefix));
}
_newName(prefix) {
const ng = this._names[prefix] || this._nameGroup(prefix);
return `${prefix}${ng.index++}`;
}
_nameGroup(prefix) {
var _a, _b;
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
}
return (this._names[prefix] = { prefix, index: 0 });
}
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
constructor(prefix, nameStr) {
super(nameStr);
this.prefix = prefix;
}
setValue(value, { property, itemIndex }) {
this.value = value;
this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
}
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
constructor(opts) {
super(opts);
this._values = {};
this._scope = opts.scope;
this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
}
get() {
return this._scope;
}
name(prefix) {
return new ValueScopeName(prefix, this._newName(prefix));
}
value(nameOrPrefix, value) {
var _a;
if (value.ref === undefined)
throw new Error("CodeGen: ref must be passed in value");
const name = this.toName(nameOrPrefix);
const { prefix } = name;
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
let vs = this._values[prefix];
if (vs) {
const _name = vs.get(valueKey);
if (_name)
return _name;
}
else {
vs = this._values[prefix] = new Map();
}
vs.set(valueKey, name);
const s = this._scope[prefix] || (this._scope[prefix] = []);
const itemIndex = s.length;
s[itemIndex] = value.ref;
name.setValue(value, { property: prefix, itemIndex });
return name;
}
getValue(prefix, keyOrRef) {
const vs = this._values[prefix];
if (!vs)
return;
return vs.get(keyOrRef);
}
scopeRefs(scopeName, values = this._values) {
return this._reduceValues(values, (name) => {
if (name.scopePath === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return (0, code_1._) `${scopeName}${name.scopePath}`;
});
}
scopeCode(values = this._values, usedValues, getCode) {
return this._reduceValues(values, (name) => {
if (name.value === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return name.value.code;
}, usedValues, getCode);
}
_reduceValues(values, valueCode, usedValues = {}, getCode) {
let code = code_1.nil;
for (const prefix in values) {
const vs = values[prefix];
if (!vs)
continue;
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
vs.forEach((name) => {
if (nameSet.has(name))
return;
nameSet.set(name, UsedValueState.Started);
let c = valueCode(name);
if (c) {
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
}
else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
code = (0, code_1._) `${code}${c}${this.opts._n}`;
}
else {
throw new ValueError(name);
}
nameSet.set(name, UsedValueState.Completed);
});
}
return code;
}
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map
/***/ }),
/***/ 4118:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const names_1 = __nccwpck_require__(77416);
exports.keywordError = {
message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
message: ({ keyword, schemaType }) => schemaType
? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
: (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
addError(gen, errObj);
}
else {
returnErrors(it, (0, codegen_1._) `[${errObj}]`);
}
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
addError(gen, errObj);
if (!(compositeRule || allErrors)) {
returnErrors(it, names_1.default.vErrors);
}
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
gen.assign(names_1.default.errors, errsCount);
gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
/* istanbul ignore if */
if (errsCount === undefined)
throw new Error("ajv implementation error");
const err = gen.name("err");
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
if (it.opts.verbose) {
gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
gen.assign((0, codegen_1._) `${err}.data`, data);
}
});
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
const err = gen.const("err", errObj);
gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
const { gen, validateName, schemaEnv } = it;
if (schemaEnv.$async) {
gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
gen.return(false);
}
}
const E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
params: new codegen_1.Name("params"),
propertyName: new codegen_1.Name("propertyName"),
message: new codegen_1.Name("message"),
schema: new codegen_1.Name("schema"),
parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
const { createErrors } = cxt.it;
if (createErrors === false)
return (0, codegen_1._) `{}`;
return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
const { gen, it } = cxt;
const keyValues = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
];
extraErrorProps(cxt, error, keyValues);
return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
const instPath = instancePath
? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
: errorPath;
return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
if (schemaPath) {
schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
}
return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
const { keyword, data, schemaValue, it } = cxt;
const { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
}
if (opts.verbose) {
keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
}
if (propertyName)
keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ 40879:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = __nccwpck_require__(20893);
const validation_error_1 = __nccwpck_require__(9684);
const names_1 = __nccwpck_require__(77416);
const resolve_1 = __nccwpck_require__(4780);
const util_1 = __nccwpck_require__(63149);
const validate_1 = __nccwpck_require__(66569);
class SchemaEnv {
constructor(env) {
var _a;
this.refs = {};
this.dynamicAnchors = {};
let schema;
if (typeof env.schema == "object")
schema = env.schema;
this.schema = env.schema;
this.schemaId = env.schemaId;
this.root = env.root || this;
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
this.schemaPath = env.schemaPath;
this.localRefs = env.localRefs;
this.meta = env.meta;
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
this.refs = {};
}
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
// TODO refactor - remove compilations
const _sch = getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
let _ValidationError;
if (sch.$async) {
_ValidationError = gen.scopeValue("Error", {
ref: validation_error_1.default,
code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
});
}
const validateName = gen.scopeName("validate");
sch.validateName = validateName;
const schemaCxt = {
gen,
allErrors: this.opts.allErrors,
data: names_1.default.data,
parentData: names_1.default.parentData,
parentDataProperty: names_1.default.parentDataProperty,
dataNames: [names_1.default.data],
dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
dataLevel: 0,
dataTypes: [],
definedProperties: new Set(),
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
: { ref: sch.schema }),
validateName,
ValidationError: _ValidationError,
schema: sch.schema,
schemaEnv: sch,
rootId,
baseId: sch.baseId || rootId,
schemaPath: codegen_1.nil,
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
errorPath: (0, codegen_1._) `""`,
opts: this.opts,
self: this,
};
let sourceCode;
try {
this._compilations.add(sch);
(0, validate_1.validateFunctionCode)(schemaCxt);
gen.optimize(this.opts.code.optimize);
// gen.optimize(1)
const validateCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
if (this.opts.code.process)
sourceCode = this.opts.code.process(sourceCode, sch);
// console.log("\n\n\n *** \n", sourceCode)
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
const validate = makeValidate(this, this.scope.get());
this.scope.value(validateName, { ref: validate });
validate.errors = null;
validate.schema = sch.schema;
validate.schemaEnv = sch;
if (sch.$async)
validate.$async = true;
if (this.opts.code.source === true) {
validate.source = { validateName, validateCode, scopeValues: gen._values };
}
if (this.opts.unevaluated) {
const { props, items } = schemaCxt;
validate.evaluated = {
props: props instanceof codegen_1.Name ? undefined : props,
items: items instanceof codegen_1.Name ? undefined : items,
dynamicProps: props instanceof codegen_1.Name,
dynamicItems: items instanceof codegen_1.Name,
};
if (validate.source)
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
}
sch.validate = validate;
return sch;
}
catch (e) {
delete sch.validate;
delete sch.validateName;
if (sourceCode)
this.logger.error("Error compiling schema, function code:", sourceCode);
// console.log("\n\n\n *** \n", sourceCode, this.opts)
throw e;
}
finally {
this._compilations.delete(sch);
}
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
var _a;
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
const schOrFunc = root.refs[ref];
if (schOrFunc)
return schOrFunc;
let _sch = resolve.call(this, root, ref);
if (_sch === undefined) {
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
const { schemaId } = this.opts;
if (schema)
_sch = new SchemaEnv({ schema, schemaId, root, baseId });
}
if (_sch === undefined)
return;
return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
return sch.schema;
return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
for (const sch of this._compilations) {
if (sameSchemaEnv(sch, schEnv))
return sch;
}
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
let sch;
while (typeof (sch = this.refs[ref]) == "string")
ref = sch;
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
const p = this.opts.uriResolver.parse(ref);
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root);
}
const id = (0, resolve_1.normalizeId)(refPath);
const schOrRef = this.refs[id] || this.schemas[id];
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef);
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
return;
return getJsonPointer.call(this, p, sch);
}
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
return;
if (!schOrRef.validate)
compileSchema.call(this, schOrRef);
if (id === (0, resolve_1.normalizeId)(ref)) {
const { schema } = schOrRef;
const { schemaId } = this.opts;
const schId = schema[schemaId];
if (schId)
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
return new SchemaEnv({ schema, schemaId, root, baseId });
}
return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
"properties",
"patternProperties",
"enum",
"dependencies",
"definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
var _a;
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
return;
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean")
return;
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
if (partSchema === undefined)
return;
schema = partSchema;
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId];
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
}
}
let env;
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
env = resolveSchema.call(this, root, $ref);
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const { schemaId } = this.opts;
env = env || new SchemaEnv({ schema, schemaId, root, baseId });
if (env.schema !== env.root.schema)
return env;
return undefined;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 77416:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const names = {
// validation function arguments
data: new codegen_1.Name("data"), // data passed to validation function
// args passed from referencing schema
valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
// function scoped variables
vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
errors: new codegen_1.Name("errors"), // counter of validation errors
this: new codegen_1.Name("this"),
// "globals"
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
// JTD serialize/parse name for JSON string and position
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart"),
};
exports["default"] = names;
//# sourceMappingURL=names.js.map
/***/ }),
/***/ 19083:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const resolve_1 = __nccwpck_require__(4780);
class MissingRefError extends Error {
constructor(resolver, baseId, ref, msg) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
}
}
exports["default"] = MissingRefError;
//# sourceMappingURL=ref_error.js.map
/***/ }),
/***/ 4780:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = __nccwpck_require__(63149);
const equal = __nccwpck_require__(28206);
const traverse = __nccwpck_require__(6702);
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
"type",
"format",
"pattern",
"maxLength",
"minLength",
"maxProperties",
"minProperties",
"maxItems",
"minItems",
"maximum",
"minimum",
"uniqueItems",
"multipleOf",
"required",
"enum",
"const",
]);
function inlineRef(schema, limit = true) {
if (typeof schema == "boolean")
return true;
if (limit === true)
return !hasRef(schema);
if (!limit)
return false;
return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
"$ref",
"$recursiveRef",
"$recursiveAnchor",
"$dynamicRef",
"$dynamicAnchor",
]);
function hasRef(schema) {
for (const key in schema) {
if (REF_KEYWORDS.has(key))
return true;
const sch = schema[key];
if (Array.isArray(sch) && sch.some(hasRef))
return true;
if (typeof sch == "object" && hasRef(sch))
return true;
}
return false;
}
function countKeys(schema) {
let count = 0;
for (const key in schema) {
if (key === "$ref")
return Infinity;
count++;
if (SIMPLE_INLINED.has(key))
continue;
if (typeof schema[key] == "object") {
(0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
}
if (count === Infinity)
return Infinity;
}
return count;
}
function getFullPath(resolver, id = "", normalize) {
if (normalize !== false)
id = normalizeId(id);
const p = resolver.parse(id);
return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
const serialized = resolver.serialize(p);
return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
id = normalizeId(id);
return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
if (typeof schema == "boolean")
return {};
const { schemaId, uriResolver } = this.opts;
const schId = normalizeId(schema[schemaId] || baseId);
const baseIds = { "": schId };
const pathPrefix = getFullPath(uriResolver, schId, false);
const localRefs = {};
const schemaRefs = new Set();
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined)
return;
const fullPath = pathPrefix + jsonPtr;
let innerBaseId = baseIds[parentJsonPtr];
if (typeof sch[schemaId] == "string")
innerBaseId = addRef.call(this, sch[schemaId]);
addAnchor.call(this, sch.$anchor);
addAnchor.call(this, sch.$dynamicAnchor);
baseIds[jsonPtr] = innerBaseId;
function addRef(ref) {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve;
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
if (schemaRefs.has(ref))
throw ambiguos(ref);
schemaRefs.add(ref);
let schOrRef = this.refs[ref];
if (typeof schOrRef == "string")
schOrRef = this.refs[schOrRef];
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref);
}
else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref);
localRefs[ref] = sch;
}
else {
this.refs[ref] = fullPath;
}
}
return ref;
}
function addAnchor(anchor) {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor))
throw new Error(`invalid anchor "${anchor}"`);
addRef.call(this, `#${anchor}`);
}
}
});
return localRefs;
function checkAmbiguosRef(sch1, sch2, ref) {
if (sch2 !== undefined && !equal(sch1, sch2))
throw ambiguos(ref);
}
function ambiguos(ref) {
return new Error(`reference "${ref}" resolves to more than one schema`);
}
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map
/***/ }),
/***/ 52744:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
const groups = {
number: { type: "number", rules: [] },
string: { type: "string", rules: [] },
array: { type: "array", rules: [] },
object: { type: "object", rules: [] },
};
return {
types: { ...groups, integer: true, boolean: true, null: true },
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
post: { rules: [] },
all: {},
keywords: {},
};
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map
/***/ }),
/***/ 63149:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = __nccwpck_require__(20893);
const code_1 = __nccwpck_require__(8476);
// TODO refactor to use Set
function toHash(arr) {
const hash = {};
for (const item of arr)
hash[item] = true;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
if (typeof schema == "boolean")
return schema;
if (Object.keys(schema).length === 0)
return true;
checkUnknownRules(it, schema);
return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
const { opts, self } = it;
if (!opts.strictSchema)
return;
if (typeof schema === "boolean")
return;
const rules = self.RULES.keywords;
for (const key in schema) {
if (!rules[key])
checkStrictMode(it, `unknown keyword: "${key}"`);
}
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (rules[key])
return true;
return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (key !== "$ref" && RULES.all[key])
return true;
return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean")
return schema;
if (typeof schema == "string")
return (0, codegen_1._) `${schema}`;
}
return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
if (typeof str == "number")
return `${str}`;
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
if (Array.isArray(xs)) {
for (const x of xs)
f(x);
}
else {
f(xs);
}
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
return (gen, from, to, toName) => {
const res = to === undefined
? from
: to instanceof codegen_1.Name
? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
: from instanceof codegen_1.Name
? (mergeToName(gen, to, from), from)
: mergeValues(from, to);
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
};
}
exports.mergeEvaluated = {
props: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
}),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
if (from === true) {
gen.assign(to, true);
}
else {
gen.assign(to, (0, codegen_1._) `${to} || {}`);
setEvaluated(gen, to, from);
}
}),
mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
resultToName: evaluatedPropsToName,
}),
items: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
resultToName: (gen, items) => gen.var("items", items),
}),
};
function evaluatedPropsToName(gen, ps) {
if (ps === true)
return gen.var("props", true);
const props = gen.var("props", (0, codegen_1._) `{}`);
if (ps !== undefined)
setEvaluated(gen, props, ps);
return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
});
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
Type[Type["Num"] = 0] = "Num";
Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
// let path
if (dataProp instanceof codegen_1.Name) {
const isNumber = dataPropType === Type.Num;
return jsPropertySyntax
? isNumber
? (0, codegen_1._) `"[" + ${dataProp} + "]"`
: (0, codegen_1._) `"['" + ${dataProp} + "']"`
: isNumber
? (0, codegen_1._) `"/" + ${dataProp}`
: (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
}
return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
if (!mode)
return;
msg = `strict mode: ${msg}`;
if (mode === true)
throw new Error(msg);
it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map
/***/ }),
/***/ 36649:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
const group = self.RULES.types[type];
return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
var _a;
return (schema[rule.keyword] !== undefined ||
((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map
/***/ }),
/***/ 36302:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = __nccwpck_require__(4118);
const codegen_1 = __nccwpck_require__(20893);
const names_1 = __nccwpck_require__(77416);
const boolError = {
message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
const { gen, schema, validateName } = it;
if (schema === false) {
falseSchemaError(it, false);
}
else if (typeof schema == "object" && schema.$async === true) {
gen.return(names_1.default.data);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, null);
gen.return(true);
}
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
const { gen, schema } = it;
if (schema === false) {
gen.var(valid, false); // TODO var
falseSchemaError(it);
}
else {
gen.var(valid, true); // TODO var
}
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
const { gen, data } = it;
// TODO maybe some other interface should be used for non-keyword validation errors...
const cxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it,
};
(0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map
/***/ }),
/***/ 78570:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = __nccwpck_require__(52744);
const applicability_1 = __nccwpck_require__(36649);
const errors_1 = __nccwpck_require__(4118);
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
var DataType;
(function (DataType) {
DataType[DataType["Correct"] = 0] = "Correct";
DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
const types = getJSONTypes(schema.type);
const hasNull = types.includes("null");
if (hasNull) {
if (schema.nullable === false)
throw new Error("type: null contradicts nullable: false");
}
else {
if (!types.length && schema.nullable !== undefined) {
throw new Error('"nullable" cannot be used without "type"');
}
if (schema.nullable === true)
types.push("null");
}
return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
if (types.every(rules_1.isJSONType))
return types;
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
const { gen, data, opts } = it;
const coerceTo = coerceToTypes(types, opts.coerceTypes);
const checkTypes = types.length > 0 &&
!(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
gen.if(wrongType, () => {
if (coerceTo.length)
coerceData(it, types, coerceTo);
else
reportTypeError(it);
});
}
return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
return coerceTypes
? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
: [];
}
function coerceData(it, types, coerceTo) {
const { gen, data, opts } = it;
const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
if (opts.coerceTypes === "array") {
gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
.assign(data, (0, codegen_1._) `${data}[0]`)
.assign(dataType, (0, codegen_1._) `typeof ${data}`)
.if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
}
gen.if((0, codegen_1._) `${coerced} !== undefined`);
for (const t of coerceTo) {
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
coerceSpecificType(t);
}
}
gen.else();
reportTypeError(it);
gen.endIf();
gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
gen.assign(data, coerced);
assignParentData(it, coerced);
});
function coerceSpecificType(t) {
switch (t) {
case "string":
gen
.elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
.assign(coerced, (0, codegen_1._) `"" + ${data}`)
.elseIf((0, codegen_1._) `${data} === null`)
.assign(coerced, (0, codegen_1._) `""`);
return;
case "number":
gen
.elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "integer":
gen
.elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "boolean":
gen
.elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
.assign(coerced, false)
.elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
.assign(coerced, true);
return;
case "null":
gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
gen.assign(coerced, null);
return;
case "array":
gen
.elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
|| ${dataType} === "boolean" || ${data} === null`)
.assign(coerced, (0, codegen_1._) `[${data}]`);
}
}
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
// TODO use gen.property
gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
let cond;
switch (dataType) {
case "null":
return (0, codegen_1._) `${data} ${EQ} null`;
case "array":
cond = (0, codegen_1._) `Array.isArray(${data})`;
break;
case "object":
cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
break;
case "integer":
cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
break;
case "number":
cond = numCond();
break;
default:
return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
}
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
function numCond(_cond = codegen_1.nil) {
return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
}
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
if (dataTypes.length === 1) {
return checkDataType(dataTypes[0], data, strictNums, correct);
}
let cond;
const types = (0, util_1.toHash)(dataTypes);
if (types.array && types.object) {
const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
delete types.null;
delete types.array;
delete types.object;
}
else {
cond = codegen_1.nil;
}
if (types.number)
delete types.integer;
for (const t in types)
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
message: ({ schema }) => `must be ${schema}`,
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
const cxt = getTypeErrorContext(it);
(0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
const { gen, data, schema } = it;
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
return {
gen,
keyword: "type",
data,
schema: schema.type,
schemaCode,
schemaValue: schemaCode,
parentSchema: schema,
params: {},
it,
};
}
//# sourceMappingURL=dataType.js.map
/***/ }),
/***/ 80164:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.assignDefaults = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
function assignDefaults(it, ty) {
const { properties, items } = it.schema;
if (ty === "object" && properties) {
for (const key in properties) {
assignDefault(it, key, properties[key].default);
}
}
else if (ty === "array" && Array.isArray(items)) {
items.forEach((sch, i) => assignDefault(it, i, sch.default));
}
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
const { gen, compositeRule, data, opts } = it;
if (defaultValue === undefined)
return;
const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
if (compositeRule) {
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
return;
}
let condition = (0, codegen_1._) `${childData} === undefined`;
if (opts.useDefaults === "empty") {
condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
}
// `${childData} === undefined` +
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map
/***/ }),
/***/ 66569:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = __nccwpck_require__(36302);
const dataType_1 = __nccwpck_require__(78570);
const applicability_1 = __nccwpck_require__(36649);
const dataType_2 = __nccwpck_require__(78570);
const defaults_1 = __nccwpck_require__(80164);
const keyword_1 = __nccwpck_require__(53637);
const subschema_1 = __nccwpck_require__(83927);
const codegen_1 = __nccwpck_require__(20893);
const names_1 = __nccwpck_require__(77416);
const resolve_1 = __nccwpck_require__(4780);
const util_1 = __nccwpck_require__(63149);
const errors_1 = __nccwpck_require__(4118);
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
topSchemaObjCode(it);
return;
}
}
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
if (opts.code.es5) {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
destructureValCxtES5(gen, opts);
gen.code(body);
});
}
else {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
}
}
function destructureValCxt(opts) {
return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
gen.if(names_1.default.valCxt, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
}, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
gen.var(names_1.default.rootData, names_1.default.data);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
});
}
function topSchemaObjCode(it) {
const { schema, opts, gen } = it;
validateFunction(it, () => {
if (opts.$comment && schema.$comment)
commentKeyword(it);
checkNoDefault(it);
gen.let(names_1.default.vErrors, null);
gen.let(names_1.default.errors, 0);
if (opts.unevaluated)
resetEvaluated(it);
typeAndKeywords(it);
returnResults(it);
});
return;
}
function resetEvaluated(it) {
// TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
const { gen, validateName } = it;
it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
const schId = typeof schema == "object" && schema[opts.schemaId];
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid);
return;
}
}
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (self.RULES.all[key])
return true;
return false;
}
function isSchemaObj(it) {
return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
const { schema, gen, opts } = it;
if (opts.$comment && schema.$comment)
commentKeyword(it);
updateContext(it);
checkAsyncSchema(it);
const errsCount = gen.const("_errs", names_1.default.errors);
typeAndKeywords(it, errsCount);
// TODO var
gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
(0, util_1.checkUnknownRules)(it);
checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
if (it.opts.jtd)
return schemaKeywords(it, [], false, errsCount);
const types = (0, dataType_1.getSchemaTypes)(it.schema);
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
const { schema, errSchemaPath, opts, self } = it;
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
}
}
function checkNoDefault(it) {
const { schema, opts } = it;
if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
}
}
function updateContext(it) {
const schId = it.schema[it.opts.schemaId];
if (schId)
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
if (it.schema.$async && !it.schemaEnv.$async)
throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
const msg = schema.$comment;
if (opts.$comment === true) {
gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
}
else if (typeof opts.$comment == "function") {
const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
}
}
function returnResults(it) {
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
if (schemaEnv.$async) {
// TODO assign unevaluated
gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
if (opts.unevaluated)
assignEvaluated(it);
gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
}
}
function assignEvaluated({ gen, evaluated, props, items }) {
if (props instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.props`, props);
if (items instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
const { gen, schema, data, allErrors, opts, self } = it;
const { RULES } = self;
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
return;
}
if (!opts.jtd)
checkStrictTypes(it, types);
gen.block(() => {
for (const group of RULES.rules)
groupKeywords(group);
groupKeywords(RULES.post);
});
function groupKeywords(group) {
if (!(0, applicability_1.shouldUseGroup)(schema, group))
return;
if (group.type) {
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
iterateKeywords(it, group);
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else();
(0, dataType_2.reportTypeError)(it);
}
gen.endIf();
}
else {
iterateKeywords(it, group);
}
// TODO make it "ok" call?
if (!allErrors)
gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
}
}
function iterateKeywords(it, group) {
const { gen, schema, opts: { useDefaults }, } = it;
if (useDefaults)
(0, defaults_1.assignDefaults)(it, group.type);
gen.block(() => {
for (const rule of group.rules) {
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type);
}
}
});
}
function checkStrictTypes(it, types) {
if (it.schemaEnv.meta || !it.opts.strictTypes)
return;
checkContextTypes(it, types);
if (!it.opts.allowUnionTypes)
checkMultipleTypes(it, types);
checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
if (!types.length)
return;
if (!it.dataTypes.length) {
it.dataTypes = types;
return;
}
types.forEach((t) => {
if (!includesType(it.dataTypes, t)) {
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
}
});
narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
}
}
function checkKeywordTypes(it, ts) {
const rules = it.self.RULES.all;
for (const keyword in rules) {
const rule = rules[keyword];
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
const { type } = rule.definition;
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
}
}
}
}
function hasApplicableType(schTs, kwdT) {
return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
const ts = [];
for (const t of it.dataTypes) {
if (includesType(withTypes, t))
ts.push(t);
else if (withTypes.includes("integer") && t === "number")
ts.push("integer");
}
it.dataTypes = ts;
}
function strictTypesError(it, msg) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
msg += ` at "${schemaPath}" (strictTypes)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
constructor(it, def, keyword) {
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
this.gen = it.gen;
this.allErrors = it.allErrors;
this.keyword = keyword;
this.data = it.data;
this.schema = it.schema[keyword];
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
this.schemaType = def.schemaType;
this.parentSchema = it.schema;
this.params = {};
this.it = it;
this.def = def;
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
}
else {
this.schemaCode = this.schemaValue;
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", names_1.default.errors);
}
}
result(condition, successAction, failAction) {
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
}
failResult(condition, successAction, failAction) {
this.gen.if(condition);
if (failAction)
failAction();
else
this.error();
if (successAction) {
this.gen.else();
successAction();
if (this.allErrors)
this.gen.endIf();
}
else {
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
}
pass(condition, failAction) {
this.failResult((0, codegen_1.not)(condition), undefined, failAction);
}
fail(condition) {
if (condition === undefined) {
this.error();
if (!this.allErrors)
this.gen.if(false); // this branch will be removed by gen.optimize
return;
}
this.gen.if(condition);
this.error();
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
fail$data(condition) {
if (!this.$data)
return this.fail(condition);
const { schemaCode } = this;
this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
}
error(append, errorParams, errorPaths) {
if (errorParams) {
this.setParams(errorParams);
this._error(append, errorPaths);
this.setParams({});
return;
}
this._error(append, errorPaths);
}
_error(append, errorPaths) {
;
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
}
$dataError() {
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
}
reset() {
if (this.errsCount === undefined)
throw new Error('add "trackErrors" to keyword definition');
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
}
ok(cond) {
if (!this.allErrors)
this.gen.if(cond);
}
setParams(obj, assign) {
if (assign)
Object.assign(this.params, obj);
else
this.params = obj;
}
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
this.gen.block(() => {
this.check$data(valid, $dataValid);
codeBlock();
});
}
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
if (!this.$data)
return;
const { gen, schemaCode, schemaType, def } = this;
gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
if (valid !== codegen_1.nil)
gen.assign(valid, true);
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data());
this.$dataError();
if (valid !== codegen_1.nil)
gen.assign(valid, false);
}
gen.else();
}
invalid$data() {
const { gen, schemaCode, schemaType, def, it } = this;
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
function wrong$DataType() {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof codegen_1.Name))
throw new Error("ajv implementation error");
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
}
return codegen_1.nil;
}
function invalid$DataSchema() {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
}
return codegen_1.nil;
}
}
subschema(appl, valid) {
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
(0, subschema_1.extendSubschemaMode)(subschema, appl);
const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
subschemaCode(nextContext, valid);
return nextContext;
}
mergeEvaluated(schemaCxt, toName) {
const { it, gen } = this;
if (!it.opts.unevaluated)
return;
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
}
}
mergeValidEvaluated(schemaCxt, valid) {
const { it, gen } = this;
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
return true;
}
}
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
const cxt = new KeywordCxt(it, def, keyword);
if ("code" in def) {
def.code(cxt, ruleType);
}
else if (cxt.$data && def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
else if ("macro" in def) {
(0, keyword_1.macroKeywordCode)(cxt, def);
}
else if (def.compile || def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
let jsonPointer;
let data;
if ($data === "")
return names_1.default.rootData;
if ($data[0] === "/") {
if (!JSON_POINTER.test($data))
throw new Error(`Invalid JSON-pointer: ${$data}`);
jsonPointer = $data;
data = names_1.default.rootData;
}
else {
const matches = RELATIVE_JSON_POINTER.exec($data);
if (!matches)
throw new Error(`Invalid JSON-pointer: ${$data}`);
const up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer === "#") {
if (up >= dataLevel)
throw new Error(errorMsg("property/index", up));
return dataPathArr[dataLevel - up];
}
if (up > dataLevel)
throw new Error(errorMsg("data", up));
data = dataNames[dataLevel - up];
if (!jsonPointer)
return data;
}
let expr = data;
const segments = jsonPointer.split("/");
for (const segment of segments) {
if (segment) {
data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
expr = (0, codegen_1._) `${expr} && ${data}`;
}
}
return expr;
function errorMsg(pointerType, up) {
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
}
}
exports.getData = getData;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 53637:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = __nccwpck_require__(20893);
const names_1 = __nccwpck_require__(77416);
const code_1 = __nccwpck_require__(51457);
const errors_1 = __nccwpck_require__(4118);
function macroKeywordCode(cxt, def) {
const { gen, keyword, schema, parentSchema, it } = cxt;
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
const schemaRef = useKeyword(gen, keyword, macroSchema);
if (it.opts.validateSchema !== false)
it.self.validateSchema(macroSchema, true);
const valid = gen.name("valid");
cxt.subschema({
schema: macroSchema,
schemaPath: codegen_1.nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true,
}, valid);
cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
var _a;
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
checkAsyncKeyword(it, def);
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
const validateRef = useKeyword(gen, keyword, validate);
const valid = gen.let("valid");
cxt.block$data(valid, validateKeyword);
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
function validateKeyword() {
if (def.errors === false) {
assignValid();
if (def.modifying)
modifyData(cxt);
reportErrs(() => cxt.error());
}
else {
const ruleErrs = def.async ? validateAsync() : validateSync();
if (def.modifying)
modifyData(cxt);
reportErrs(() => addErrs(cxt, ruleErrs));
}
}
function validateAsync() {
const ruleErrs = gen.let("ruleErrs", null);
gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
return ruleErrs;
}
function validateSync() {
const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
gen.assign(validateErrs, null);
assignValid(codegen_1.nil);
return validateErrs;
}
function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
const passSchema = !(("compile" in def && !$data) || def.schema === false);
gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
}
function reportErrs(errors) {
var _a;
gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
}
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
const { gen, data, it } = cxt;
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
const { gen } = cxt;
gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
gen
.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
(0, errors_1.extendErrors)(cxt);
}, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
if (def.async && !schemaEnv.$async)
throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
if (result === undefined)
throw new Error(`keyword "${keyword}" failed to compile`);
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
// TODO add tests
return (!schemaType.length ||
schemaType.some((st) => st === "array"
? Array.isArray(schema)
: st === "object"
? schema && typeof schema == "object" && !Array.isArray(schema)
: typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error");
}
const deps = def.dependencies;
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword]);
if (!valid) {
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors);
if (opts.validateSchema === "log")
self.logger.error(msg);
else
throw new Error(msg);
}
}
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map
/***/ }),
/***/ 83927:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
if (keyword !== undefined && schema !== undefined) {
throw new Error('both "keyword" and "schema" passed, only one allowed');
}
if (keyword !== undefined) {
const sch = it.schema[keyword];
return schemaProp === undefined
? {
schema: sch,
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
}
: {
schema: sch[schemaProp],
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
};
}
if (schema !== undefined) {
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath,
};
}
throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed');
}
const { gen } = it;
if (dataProp !== undefined) {
const { errorPath, dataPathArr, opts } = it;
const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
dataContextProps(nextData);
subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
}
if (data !== undefined) {
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
dataContextProps(nextData);
if (propertyName !== undefined)
subschema.propertyName = propertyName;
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes)
subschema.dataTypes = dataTypes;
function dataContextProps(_nextData) {
subschema.data = _nextData;
subschema.dataLevel = it.dataLevel + 1;
subschema.dataTypes = [];
it.definedProperties = new Set();
subschema.parentData = it.data;
subschema.dataNames = [...it.dataNames, _nextData];
}
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
if (compositeRule !== undefined)
subschema.compositeRule = compositeRule;
if (createErrors !== undefined)
subschema.createErrors = createErrors;
if (allErrors !== undefined)
subschema.allErrors = allErrors;
subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map
/***/ }),
/***/ 77626:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = __nccwpck_require__(66569);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(20893);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
const validation_error_1 = __nccwpck_require__(9684);
const ref_error_1 = __nccwpck_require__(19083);
const rules_1 = __nccwpck_require__(52744);
const compile_1 = __nccwpck_require__(40879);
const codegen_2 = __nccwpck_require__(20893);
const resolve_1 = __nccwpck_require__(4780);
const dataType_1 = __nccwpck_require__(78570);
const util_1 = __nccwpck_require__(63149);
const $dataRefSchema = __nccwpck_require__(87099);
const uri_1 = __nccwpck_require__(57300);
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
"validate",
"serialize",
"parse",
"wrapper",
"root",
"schema",
"keyword",
"pattern",
"formats",
"validate$data",
"func",
"obj",
"Error",
]);
const removedOptions = {
errorDataPath: "",
format: "`validateFormats: false` can be used instead.",
nullable: '"nullable" keyword is supported by default.',
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
sourceCode: "Use option `code: {source: true}`",
strictDefaults: "It is default now, see option `strict`.",
strictKeywords: "It is default now, see option `strict`.",
uniqueItems: '"uniqueItems" keyword is always validated.',
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
cache: "Map is used as cache, schema object as key.",
serialize: "Map is used as cache, schema object as key.",
ajvErrors: "It is default now.",
};
const deprecatedOptions = {
ignoreKeywordsWithRef: "",
jsPropertySyntax: "",
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
return {
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
uriResolver: uriResolver,
};
}
class Ajv {
constructor(opts = {}) {
this.schemas = {};
this.refs = {};
this.formats = {};
this._compilations = new Set();
this._loading = {};
this._cache = new Map();
opts = this.opts = { ...opts, ...requiredOptions(opts) };
const { es5, lines } = this.opts.code;
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
this.logger = getLogger(opts.logger);
const formatOpt = opts.validateFormats;
opts.validateFormats = false;
this.RULES = (0, rules_1.getRules)();
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
this._metaOpts = getMetaSchemaOptions.call(this);
if (opts.formats)
addInitialFormats.call(this);
this._addVocabularies();
this._addDefaultMetaSchema();
if (opts.keywords)
addInitialKeywords.call(this, opts.keywords);
if (typeof opts.meta == "object")
this.addMetaSchema(opts.meta);
addInitialSchemas.call(this);
opts.validateFormats = formatOpt;
}
_addVocabularies() {
this.addKeyword("$async");
}
_addDefaultMetaSchema() {
const { $data, meta, schemaId } = this.opts;
let _dataRefSchema = $dataRefSchema;
if (schemaId === "id") {
_dataRefSchema = { ...$dataRefSchema };
_dataRefSchema.id = _dataRefSchema.$id;
delete _dataRefSchema.$id;
}
if (meta && $data)
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
}
defaultMeta() {
const { meta, schemaId } = this.opts;
return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
}
validate(schemaKeyRef, // key, ref or schema object
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
data // to be validated
) {
let v;
if (typeof schemaKeyRef == "string") {
v = this.getSchema(schemaKeyRef);
if (!v)
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
}
else {
v = this.compile(schemaKeyRef);
}
const valid = v(data);
if (!("$async" in v))
this.errors = v.errors;
return valid;
}
compile(schema, _meta) {
const sch = this._addSchema(schema, _meta);
return (sch.validate || this._compileSchemaEnv(sch));
}
compileAsync(schema, meta) {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function");
}
const { loadSchema } = this.opts;
return runCompileAsync.call(this, schema, meta);
async function runCompileAsync(_schema, _meta) {
await loadMetaSchema.call(this, _schema.$schema);
const sch = this._addSchema(_schema, _meta);
return sch.validate || _compileAsync.call(this, sch);
}
async function loadMetaSchema($ref) {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, { $ref }, true);
}
}
async function _compileAsync(sch) {
try {
return this._compileSchemaEnv(sch);
}
catch (e) {
if (!(e instanceof ref_error_1.default))
throw e;
checkLoaded.call(this, e);
await loadMissingSchema.call(this, e.missingSchema);
return _compileAsync.call(this, sch);
}
}
function checkLoaded({ missingSchema: ref, missingRef }) {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
}
}
async function loadMissingSchema(ref) {
const _schema = await _loadSchema.call(this, ref);
if (!this.refs[ref])
await loadMetaSchema.call(this, _schema.$schema);
if (!this.refs[ref])
this.addSchema(_schema, ref, meta);
}
async function _loadSchema(ref) {
const p = this._loading[ref];
if (p)
return p;
try {
return await (this._loading[ref] = loadSchema(ref));
}
finally {
delete this._loading[ref];
}
}
}
// Adds schema to the instance
addSchema(schema, // If array is passed, `key` will be ignored
key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
_meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
) {
if (Array.isArray(schema)) {
for (const sch of schema)
this.addSchema(sch, undefined, _meta, _validateSchema);
return this;
}
let id;
if (typeof schema === "object") {
const { schemaId } = this.opts;
id = schema[schemaId];
if (id !== undefined && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`);
}
}
key = (0, resolve_1.normalizeId)(key || id);
this._checkUnique(key);
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
return this;
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(schema, key, // schema key
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
) {
this.addSchema(schema, key, true, _validateSchema);
return this;
}
// Validate schema against its meta-schema
validateSchema(schema, throwOrLogError) {
if (typeof schema == "boolean")
return true;
let $schema;
$schema = schema.$schema;
if ($schema !== undefined && typeof $schema != "string") {
throw new Error("$schema must be a string");
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
if (!$schema) {
this.logger.warn("meta-schema not available");
this.errors = null;
return true;
}
const valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText();
if (this.opts.validateSchema === "log")
this.logger.error(message);
else
throw new Error(message);
}
return valid;
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema(keyRef) {
let sch;
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
keyRef = sch;
if (sch === undefined) {
const { schemaId } = this.opts;
const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
sch = compile_1.resolveSchema.call(this, root, keyRef);
if (!sch)
return;
this.refs[keyRef] = sch;
}
return (sch.validate || this._compileSchemaEnv(sch));
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef);
this._removeAllSchemas(this.refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas);
this._removeAllSchemas(this.refs);
this._cache.clear();
return this;
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef);
if (typeof sch == "object")
this._cache.delete(sch.schema);
delete this.schemas[schemaKeyRef];
delete this.refs[schemaKeyRef];
return this;
}
case "object": {
const cacheKey = schemaKeyRef;
this._cache.delete(cacheKey);
let id = schemaKeyRef[this.opts.schemaId];
if (id) {
id = (0, resolve_1.normalizeId)(id);
delete this.schemas[id];
delete this.refs[id];
}
return this;
}
default:
throw new Error("ajv.removeSchema: invalid parameter");
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions) {
for (const def of definitions)
this.addKeyword(def);
return this;
}
addKeyword(kwdOrDef, def // deprecated
) {
let keyword;
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef;
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
def.keyword = keyword;
}
}
else if (typeof kwdOrDef == "object" && def === undefined) {
def = kwdOrDef;
keyword = def.keyword;
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array");
}
}
else {
throw new Error("invalid addKeywords parameters");
}
checkKeyword.call(this, keyword, def);
if (!def) {
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
return this;
}
keywordMetaschema.call(this, def);
const definition = {
...def,
type: (0, dataType_1.getJSONTypes)(def.type),
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
};
(0, util_1.eachItem)(keyword, definition.type.length === 0
? (k) => addRule.call(this, k, definition)
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
return this;
}
getKeyword(keyword) {
const rule = this.RULES.all[keyword];
return typeof rule == "object" ? rule.definition : !!rule;
}
// Remove keyword
removeKeyword(keyword) {
// TODO return type should be Ajv
const { RULES } = this;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
if (i >= 0)
group.rules.splice(i, 1);
}
return this;
}
// Add format
addFormat(name, format) {
if (typeof format == "string")
format = new RegExp(format);
this.formats[name] = format;
return this;
}
errorsText(errors = this.errors, // optional array of validation errors
{ separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
) {
if (!errors || errors.length === 0)
return "No errors";
return errors
.map((e) => `${dataVar}${e.instancePath} ${e.message}`)
.reduce((text, msg) => text + separator + msg);
}
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
const rules = this.RULES.all;
metaSchema = JSON.parse(JSON.stringify(metaSchema));
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
let keywords = metaSchema;
for (const seg of segments)
keywords = keywords[seg];
for (const key in rules) {
const rule = rules[key];
if (typeof rule != "object")
continue;
const { $data } = rule.definition;
const schema = keywords[key];
if ($data && schema)
keywords[key] = schemaOrData(schema);
}
}
return metaSchema;
}
_removeAllSchemas(schemas, regex) {
for (const keyRef in schemas) {
const sch = schemas[keyRef];
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef];
}
else if (sch && !sch.meta) {
this._cache.delete(sch.schema);
delete schemas[keyRef];
}
}
}
}
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
let id;
const { schemaId } = this.opts;
if (typeof schema == "object") {
id = schema[schemaId];
}
else {
if (this.opts.jtd)
throw new Error("schema must be object");
else if (typeof schema != "boolean")
throw new Error("schema must be object or boolean");
}
let sch = this._cache.get(schema);
if (sch !== undefined)
return sch;
baseId = (0, resolve_1.normalizeId)(id || baseId);
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
this._cache.set(sch.schema, sch);
if (addSchema && !baseId.startsWith("#")) {
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
if (baseId)
this._checkUnique(baseId);
this.refs[baseId] = sch;
}
if (validateSchema)
this.validateSchema(schema, true);
return sch;
}
_checkUnique(id) {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`);
}
}
_compileSchemaEnv(sch) {
if (sch.meta)
this._compileMetaSchema(sch);
else
compile_1.compileSchema.call(this, sch);
/* istanbul ignore if */
if (!sch.validate)
throw new Error("ajv implementation error");
return sch.validate;
}
_compileMetaSchema(sch) {
const currentOpts = this.opts;
this.opts = this._metaOpts;
try {
compile_1.compileSchema.call(this, sch);
}
finally {
this.opts = currentOpts;
}
}
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports["default"] = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
for (const key in checkOpts) {
const opt = key;
if (opt in options)
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
}
}
function getSchEnv(keyRef) {
keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
const optsSchemas = this.opts.schemas;
if (!optsSchemas)
return;
if (Array.isArray(optsSchemas))
this.addSchema(optsSchemas);
else
for (const key in optsSchemas)
this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (const name in this.opts.formats) {
const format = this.opts.formats[name];
if (format)
this.addFormat(name, format);
}
}
function addInitialKeywords(defs) {
if (Array.isArray(defs)) {
this.addVocabulary(defs);
return;
}
this.logger.warn("keywords option as map is deprecated, pass array");
for (const keyword in defs) {
const def = defs[keyword];
if (!def.keyword)
def.keyword = keyword;
this.addKeyword(def);
}
}
function getMetaSchemaOptions() {
const metaOpts = { ...this.opts };
for (const opt of META_IGNORE_OPTIONS)
delete metaOpts[opt];
return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
if (logger === false)
return noLogs;
if (logger === undefined)
return console;
if (logger.log && logger.warn && logger.error)
return logger;
throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
const { RULES } = this;
(0, util_1.eachItem)(keyword, (kwd) => {
if (RULES.keywords[kwd])
throw new Error(`Keyword ${kwd} is already defined`);
if (!KEYWORD_NAME.test(kwd))
throw new Error(`Keyword ${kwd} has invalid name`);
});
if (!def)
return;
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function');
}
}
function addRule(keyword, definition, dataType) {
var _a;
const post = definition === null || definition === void 0 ? void 0 : definition.post;
if (dataType && post)
throw new Error('keyword with "post" flag cannot have "type"');
const { RULES } = this;
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.rules.push(ruleGroup);
}
RULES.keywords[keyword] = true;
if (!definition)
return;
const rule = {
keyword,
definition: {
...definition,
type: (0, dataType_1.getJSONTypes)(definition.type),
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
},
};
if (definition.before)
addBeforeRule.call(this, ruleGroup, rule, definition.before);
else
ruleGroup.rules.push(rule);
RULES.all[keyword] = rule;
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule);
}
else {
ruleGroup.rules.push(rule);
this.logger.warn(`rule ${before} is not defined`);
}
}
function keywordMetaschema(def) {
let { metaSchema } = def;
if (metaSchema === undefined)
return;
if (def.$data && this.opts.$data)
metaSchema = schemaOrData(metaSchema);
def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 23403:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://github.com/ajv-validator/ajv/issues/889
const equal = __nccwpck_require__(28206);
equal.code = 'require("ajv/dist/runtime/equal").default';
exports["default"] = equal;
//# sourceMappingURL=equal.js.map
/***/ }),
/***/ 39300:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
const len = str.length;
let length = 0;
let pos = 0;
let value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 0xd800 && value <= 0xdbff && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos);
if ((value & 0xfc00) === 0xdc00)
pos++; // low surrogate
}
}
return length;
}
exports["default"] = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map
/***/ }),
/***/ 57300:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const uri = __nccwpck_require__(70020);
uri.code = 'require("ajv/dist/runtime/uri").default';
exports["default"] = uri;
//# sourceMappingURL=uri.js.map
/***/ }),
/***/ 9684:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class ValidationError extends Error {
constructor(errors) {
super("validation failed");
this.errors = errors;
this.ajv = this.validation = true;
}
}
exports["default"] = ValidationError;
//# sourceMappingURL=validation_error.js.map
/***/ }),
/***/ 29753:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateAdditionalItems = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "additionalItems",
type: "array",
schemaType: ["boolean", "object"],
before: "uniqueItems",
error,
code(cxt) {
const { parentSchema, it } = cxt;
const { items } = parentSchema;
if (!Array.isArray(items)) {
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
return;
}
validateAdditionalItems(cxt, items);
},
};
function validateAdditionalItems(cxt, items) {
const { gen, schema, data, keyword, it } = cxt;
it.items = true;
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
if (schema === false) {
cxt.setParams({ len: items.length });
cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
}
else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
cxt.ok(valid);
}
function validateItems(valid) {
gen.forRange("i", items.length, len, (i) => {
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
if (!it.allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
});
}
}
exports.validateAdditionalItems = validateAdditionalItems;
exports["default"] = def;
//# sourceMappingURL=additionalItems.js.map
/***/ }),
/***/ 65906:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(51457);
const codegen_1 = __nccwpck_require__(20893);
const names_1 = __nccwpck_require__(77416);
const util_1 = __nccwpck_require__(63149);
const error = {
message: "must NOT have additional properties",
params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
keyword: "additionalProperties",
type: ["object"],
schemaType: ["boolean", "object"],
allowUndefined: true,
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
/* istanbul ignore if */
if (!errsCount)
throw new Error("ajv implementation error");
const { allErrors, opts } = it;
it.props = true;
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
return;
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
checkAdditionalProperties();
cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
function checkAdditionalProperties() {
gen.forIn("key", data, (key) => {
if (!props.length && !patProps.length)
additionalPropertyCode(key);
else
gen.if(isAdditional(key), () => additionalPropertyCode(key));
});
}
function isAdditional(key) {
let definedProp;
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
}
else if (props.length) {
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
}
else {
definedProp = codegen_1.nil;
}
if (patProps.length) {
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
}
return (0, codegen_1.not)(definedProp);
}
function deleteAdditional(key) {
gen.code((0, codegen_1._) `delete ${data}[${key}]`);
}
function additionalPropertyCode(key) {
if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
deleteAdditional(key);
return;
}
if (schema === false) {
cxt.setParams({ additionalProperty: key });
cxt.error();
if (!allErrors)
gen.break();
return;
}
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.name("valid");
if (opts.removeAdditional === "failing") {
applyAdditionalSchema(key, valid, false);
gen.if((0, codegen_1.not)(valid), () => {
cxt.reset();
deleteAdditional(key);
});
}
else {
applyAdditionalSchema(key, valid);
if (!allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
}
}
function applyAdditionalSchema(key, valid, errors) {
const subschema = {
keyword: "additionalProperties",
dataProp: key,
dataPropType: util_1.Type.Str,
};
if (errors === false) {
Object.assign(subschema, {
compositeRule: true,
createErrors: false,
allErrors: false,
});
}
cxt.subschema(subschema, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=additionalProperties.js.map
/***/ }),
/***/ 1325:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(63149);
const def = {
keyword: "allOf",
schemaType: "array",
code(cxt) {
const { gen, schema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const valid = gen.name("valid");
schema.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
cxt.ok(valid);
cxt.mergeEvaluated(schCxt);
});
},
};
exports["default"] = def;
//# sourceMappingURL=allOf.js.map
/***/ }),
/***/ 46152:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(51457);
const def = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in anyOf" },
};
exports["default"] = def;
//# sourceMappingURL=anyOf.js.map
/***/ }),
/***/ 45848:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: ({ params: { min, max } }) => max === undefined
? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
: (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
keyword: "contains",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
let min;
let max;
const { minContains, maxContains } = parentSchema;
if (it.opts.next) {
min = minContains === undefined ? 1 : minContains;
max = maxContains;
}
else {
min = 1;
}
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
cxt.setParams({ min, max });
if (max === undefined && min === 0) {
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
return;
}
if (max !== undefined && min > max) {
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
cxt.fail();
return;
}
if ((0, util_1.alwaysValidSchema)(it, schema)) {
let cond = (0, codegen_1._) `${len} >= ${min}`;
if (max !== undefined)
cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
cxt.pass(cond);
return;
}
it.items = true;
const valid = gen.name("valid");
if (max === undefined && min === 1) {
validateItems(valid, () => gen.if(valid, () => gen.break()));
}
else if (min === 0) {
gen.let(valid, true);
if (max !== undefined)
gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
}
else {
gen.let(valid, false);
validateItemsWithCount();
}
cxt.result(valid, () => cxt.reset());
function validateItemsWithCount() {
const schValid = gen.name("_valid");
const count = gen.let("count", 0);
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
}
function validateItems(_valid, block) {
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword: "contains",
dataProp: i,
dataPropType: util_1.Type.Num,
compositeRule: true,
}, _valid);
block();
});
}
function checkLimits(count) {
gen.code((0, codegen_1._) `${count}++`);
if (max === undefined) {
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
}
else {
gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
if (min === 1)
gen.assign(valid, true);
else
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=contains.js.map
/***/ }),
/***/ 2285:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const code_1 = __nccwpck_require__(51457);
exports.error = {
message: ({ params: { property, depsCount, deps } }) => {
const property_ies = depsCount === 1 ? "property" : "properties";
return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
},
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`, // TODO change to reference
};
const def = {
keyword: "dependencies",
type: "object",
schemaType: "object",
error: exports.error,
code(cxt) {
const [propDeps, schDeps] = splitDependencies(cxt);
validatePropertyDeps(cxt, propDeps);
validateSchemaDeps(cxt, schDeps);
},
};
function splitDependencies({ schema }) {
const propertyDeps = {};
const schemaDeps = {};
for (const key in schema) {
if (key === "__proto__")
continue;
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
deps[key] = schema[key];
}
return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
const { gen, data, it } = cxt;
if (Object.keys(propertyDeps).length === 0)
return;
const missing = gen.let("missing");
for (const prop in propertyDeps) {
const deps = propertyDeps[prop];
if (deps.length === 0)
continue;
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
cxt.setParams({
property: prop,
depsCount: deps.length,
deps: deps.join(", "),
});
if (it.allErrors) {
gen.if(hasProperty, () => {
for (const depProp of deps) {
(0, code_1.checkReportMissingProp)(cxt, depProp);
}
});
}
else {
gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
for (const prop in schemaDeps) {
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
continue;
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
cxt.mergeValidEvaluated(schCxt, valid);
}, () => gen.var(valid, true) // TODO var
);
cxt.ok(valid);
}
}
exports.validateSchemaDeps = validateSchemaDeps;
exports["default"] = def;
//# sourceMappingURL=dependencies.js.map
/***/ }),
/***/ 17859:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
keyword: "if",
schemaType: ["object", "boolean"],
trackErrors: true,
error,
code(cxt) {
const { gen, parentSchema, it } = cxt;
if (parentSchema.then === undefined && parentSchema.else === undefined) {
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
}
const hasThen = hasSchema(it, "then");
const hasElse = hasSchema(it, "else");
if (!hasThen && !hasElse)
return;
const valid = gen.let("valid", true);
const schValid = gen.name("_valid");
validateIf();
cxt.reset();
if (hasThen && hasElse) {
const ifClause = gen.let("ifClause");
cxt.setParams({ ifClause });
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
}
else if (hasThen) {
gen.if(schValid, validateClause("then"));
}
else {
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
}
cxt.pass(valid, () => cxt.error(true));
function validateIf() {
const schCxt = cxt.subschema({
keyword: "if",
compositeRule: true,
createErrors: false,
allErrors: false,
}, schValid);
cxt.mergeEvaluated(schCxt);
}
function validateClause(keyword, ifClause) {
return () => {
const schCxt = cxt.subschema({ keyword }, schValid);
gen.assign(valid, schValid);
cxt.mergeValidEvaluated(schCxt, valid);
if (ifClause)
gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
else
cxt.setParams({ ifClause: keyword });
};
}
},
};
function hasSchema(it, keyword) {
const schema = it.schema[keyword];
return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports["default"] = def;
//# sourceMappingURL=if.js.map
/***/ }),
/***/ 69193:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const additionalItems_1 = __nccwpck_require__(29753);
const prefixItems_1 = __nccwpck_require__(31285);
const items_1 = __nccwpck_require__(87977);
const items2020_1 = __nccwpck_require__(36937);
const contains_1 = __nccwpck_require__(45848);
const dependencies_1 = __nccwpck_require__(2285);
const propertyNames_1 = __nccwpck_require__(87493);
const additionalProperties_1 = __nccwpck_require__(65906);
const properties_1 = __nccwpck_require__(55566);
const patternProperties_1 = __nccwpck_require__(63008);
const not_1 = __nccwpck_require__(10326);
const anyOf_1 = __nccwpck_require__(46152);
const oneOf_1 = __nccwpck_require__(33760);
const allOf_1 = __nccwpck_require__(1325);
const if_1 = __nccwpck_require__(17859);
const thenElse_1 = __nccwpck_require__(48095);
function getApplicator(draft2020 = false) {
const applicator = [
// any
not_1.default,
anyOf_1.default,
oneOf_1.default,
allOf_1.default,
if_1.default,
thenElse_1.default,
// object
propertyNames_1.default,
additionalProperties_1.default,
dependencies_1.default,
properties_1.default,
patternProperties_1.default,
];
// array
if (draft2020)
applicator.push(prefixItems_1.default, items2020_1.default);
else
applicator.push(additionalItems_1.default, items_1.default);
applicator.push(contains_1.default);
return applicator;
}
exports["default"] = getApplicator;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 87977:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateTuple = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const code_1 = __nccwpck_require__(51457);
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "array", "boolean"],
before: "uniqueItems",
code(cxt) {
const { schema, it } = cxt;
if (Array.isArray(schema))
return validateTuple(cxt, "additionalItems", schema);
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
cxt.ok((0, code_1.validateArray)(cxt));
},
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
const { gen, parentSchema, data, keyword, it } = cxt;
checkStrictTuple(parentSchema);
if (it.opts.unevaluated && schArr.length && it.items !== true) {
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
}
const valid = gen.name("valid");
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
schArr.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
keyword,
schemaProp: i,
dataProp: i,
}, valid));
cxt.ok(valid);
});
function checkStrictTuple(sch) {
const { opts, errSchemaPath } = it;
const l = schArr.length;
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
if (opts.strictTuples && !fullTuple) {
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
}
}
}
exports.validateTuple = validateTuple;
exports["default"] = def;
//# sourceMappingURL=items.js.map
/***/ }),
/***/ 36937:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const code_1 = __nccwpck_require__(51457);
const additionalItems_1 = __nccwpck_require__(29753);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
error,
code(cxt) {
const { schema, parentSchema, it } = cxt;
const { prefixItems } = parentSchema;
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
if (prefixItems)
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
else
cxt.ok((0, code_1.validateArray)(cxt));
},
};
exports["default"] = def;
//# sourceMappingURL=items2020.js.map
/***/ }),
/***/ 10326:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(63149);
const def = {
keyword: "not",
schemaType: ["object", "boolean"],
trackErrors: true,
code(cxt) {
const { gen, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema)) {
cxt.fail();
return;
}
const valid = gen.name("valid");
cxt.subschema({
keyword: "not",
compositeRule: true,
createErrors: false,
allErrors: false,
}, valid);
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
},
error: { message: "must NOT be valid" },
};
exports["default"] = def;
//# sourceMappingURL=not.js.map
/***/ }),
/***/ 33760:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: "must match exactly one schema in oneOf",
params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
keyword: "oneOf",
schemaType: "array",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
if (it.opts.discriminator && parentSchema.discriminator)
return;
const schArr = schema;
const valid = gen.let("valid", false);
const passing = gen.let("passing", null);
const schValid = gen.name("_valid");
cxt.setParams({ passing });
// TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
gen.block(validateOneOf);
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
function validateOneOf() {
schArr.forEach((sch, i) => {
let schCxt;
if ((0, util_1.alwaysValidSchema)(it, sch)) {
gen.var(schValid, true);
}
else {
schCxt = cxt.subschema({
keyword: "oneOf",
schemaProp: i,
compositeRule: true,
}, schValid);
}
if (i > 0) {
gen
.if((0, codegen_1._) `${schValid} && ${valid}`)
.assign(valid, false)
.assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
.else();
}
gen.if(schValid, () => {
gen.assign(valid, true);
gen.assign(passing, i);
if (schCxt)
cxt.mergeEvaluated(schCxt, codegen_1.Name);
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=oneOf.js.map
/***/ }),
/***/ 63008:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(51457);
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const util_2 = __nccwpck_require__(63149);
const def = {
keyword: "patternProperties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, data, parentSchema, it } = cxt;
const { opts } = it;
const patterns = (0, code_1.allSchemaProperties)(schema);
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
if (patterns.length === 0 ||
(alwaysValidPatterns.length === patterns.length &&
(!it.opts.unevaluated || it.props === true))) {
return;
}
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
const valid = gen.name("valid");
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
}
const { props } = it;
validatePatternProperties();
function validatePatternProperties() {
for (const pat of patterns) {
if (checkProperties)
checkMatchingProperties(pat);
if (it.allErrors) {
validateProperties(pat);
}
else {
gen.var(valid, true); // TODO var
validateProperties(pat);
gen.if(valid);
}
}
}
function checkMatchingProperties(pat) {
for (const prop in checkProperties) {
if (new RegExp(pat).test(prop)) {
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
}
}
}
function validateProperties(pat) {
gen.forIn("key", data, (key) => {
gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
const alwaysValid = alwaysValidPatterns.includes(pat);
if (!alwaysValid) {
cxt.subschema({
keyword: "patternProperties",
schemaProp: pat,
dataProp: key,
dataPropType: util_2.Type.Str,
}, valid);
}
if (it.opts.unevaluated && props !== true) {
gen.assign((0, codegen_1._) `${props}[${key}]`, true);
}
else if (!alwaysValid && !it.allErrors) {
// can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
// or if all properties were evaluated (props === true)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=patternProperties.js.map
/***/ }),
/***/ 31285:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const items_1 = __nccwpck_require__(87977);
const def = {
keyword: "prefixItems",
type: "array",
schemaType: ["array"],
before: "uniqueItems",
code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports["default"] = def;
//# sourceMappingURL=prefixItems.js.map
/***/ }),
/***/ 55566:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const validate_1 = __nccwpck_require__(66569);
const code_1 = __nccwpck_require__(51457);
const util_1 = __nccwpck_require__(63149);
const additionalProperties_1 = __nccwpck_require__(65906);
const def = {
keyword: "properties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
}
const allProps = (0, code_1.allSchemaProperties)(schema);
for (const prop of allProps) {
it.definedProperties.add(prop);
}
if (it.opts.unevaluated && allProps.length && it.props !== true) {
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
}
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
if (properties.length === 0)
return;
const valid = gen.name("valid");
for (const prop of properties) {
if (hasDefault(prop)) {
applyPropertySchema(prop);
}
else {
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
applyPropertySchema(prop);
if (!it.allErrors)
gen.else().var(valid, true);
gen.endIf();
}
cxt.it.definedProperties.add(prop);
cxt.ok(valid);
}
function hasDefault(prop) {
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
}
function applyPropertySchema(prop) {
cxt.subschema({
keyword: "properties",
schemaProp: prop,
dataProp: prop,
}, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=properties.js.map
/***/ }),
/***/ 87493:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: "property name must be valid",
params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
keyword: "propertyNames",
type: "object",
schemaType: ["object", "boolean"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
gen.forIn("key", data, (key) => {
cxt.setParams({ propertyName: key });
cxt.subschema({
keyword: "propertyNames",
data: key,
dataTypes: ["string"],
propertyName: key,
compositeRule: true,
}, valid);
gen.if((0, codegen_1.not)(valid), () => {
cxt.error(true);
if (!it.allErrors)
gen.break();
});
});
cxt.ok(valid);
},
};
exports["default"] = def;
//# sourceMappingURL=propertyNames.js.map
/***/ }),
/***/ 48095:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(63149);
const def = {
keyword: ["then", "else"],
schemaType: ["object", "boolean"],
code({ keyword, parentSchema, it }) {
if (parentSchema.if === undefined)
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
},
};
exports["default"] = def;
//# sourceMappingURL=thenElse.js.map
/***/ }),
/***/ 51457:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const names_1 = __nccwpck_require__(77416);
const util_2 = __nccwpck_require__(63149);
function checkReportMissingProp(cxt, prop) {
const { gen, data, it } = cxt;
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
cxt.error();
});
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
cxt.setParams({ missingProperty: missing }, true);
cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
});
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
const valCxt = [
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
[names_1.default.parentData, it.parentData],
[names_1.default.parentDataProperty, it.parentDataProperty],
[names_1.default.rootData, names_1.default.rootData],
];
if (it.opts.dynamicRef)
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
const u = opts.unicodeRegExp ? "u" : "";
const { regExp } = opts.code;
const rx = regExp(pattern, u);
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
});
}
exports.usePattern = usePattern;
function validateArray(cxt) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
if (it.allErrors) {
const validArr = gen.let("valid", true);
validateItems(() => gen.assign(validArr, false));
return validArr;
}
gen.var(valid, true);
validateItems(() => gen.break());
return valid;
function validateItems(notValid) {
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword,
dataProp: i,
dataPropType: util_1.Type.Num,
}, valid);
gen.if((0, codegen_1.not)(valid), notValid);
});
}
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
const { gen, schema, keyword, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
if (alwaysValid && !it.opts.unevaluated)
return;
const valid = gen.let("valid", false);
const schValid = gen.name("_valid");
gen.block(() => schema.forEach((_sch, i) => {
const schCxt = cxt.subschema({
keyword,
schemaProp: i,
compositeRule: true,
}, schValid);
gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged)
gen.if((0, codegen_1.not)(valid));
}));
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 12829:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const def = {
keyword: "id",
code() {
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
},
};
exports["default"] = def;
//# sourceMappingURL=id.js.map
/***/ }),
/***/ 73336:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const id_1 = __nccwpck_require__(12829);
const ref_1 = __nccwpck_require__(71716);
const core = [
"$schema",
"$id",
"$defs",
"$vocabulary",
{ keyword: "$comment" },
"definitions",
id_1.default,
ref_1.default,
];
exports["default"] = core;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 71716:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = __nccwpck_require__(19083);
const code_1 = __nccwpck_require__(51457);
const codegen_1 = __nccwpck_require__(20893);
const names_1 = __nccwpck_require__(77416);
const compile_1 = __nccwpck_require__(40879);
const util_1 = __nccwpck_require__(63149);
const def = {
keyword: "$ref",
schemaType: "string",
code(cxt) {
const { gen, schema: $ref, it } = cxt;
const { baseId, schemaEnv: env, validateName, opts, self } = it;
const { root } = env;
if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
return callRootRef();
const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
if (schOrEnv === undefined)
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
if (schOrEnv instanceof compile_1.SchemaEnv)
return callValidate(schOrEnv);
return inlineRefSchema(schOrEnv);
function callRootRef() {
if (env === root)
return callRef(cxt, validateName, env, env.$async);
const rootName = gen.scopeValue("root", { ref: root });
return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
}
function callValidate(sch) {
const v = getValidate(cxt, sch);
callRef(cxt, v, sch, sch.$async);
}
function inlineRefSchema(sch) {
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
const valid = gen.name("valid");
const schCxt = cxt.subschema({
schema: sch,
dataTypes: [],
schemaPath: codegen_1.nil,
topSchemaRef: schName,
errSchemaPath: $ref,
}, valid);
cxt.mergeEvaluated(schCxt);
cxt.ok(valid);
}
},
};
function getValidate(cxt, sch) {
const { gen } = cxt;
return sch.validate
? gen.scopeValue("validate", { ref: sch.validate })
: (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
const { gen, it } = cxt;
const { allErrors, schemaEnv: env, opts } = it;
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
if ($async)
callAsyncRef();
else
callSyncRef();
function callAsyncRef() {
if (!env.$async)
throw new Error("async schema referenced by sync schema");
const valid = gen.let("valid");
gen.try(() => {
gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
if (!allErrors)
gen.assign(valid, true);
}, (e) => {
gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
addErrorsFrom(e);
if (!allErrors)
gen.assign(valid, false);
});
cxt.ok(valid);
}
function callSyncRef() {
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
}
function addErrorsFrom(source) {
const errs = (0, codegen_1._) `${source}.errors`;
gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
}
function addEvaluatedFrom(source) {
var _a;
if (!it.opts.unevaluated)
return;
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
// TODO refactor
if (it.props !== true) {
if (schEvaluated && !schEvaluated.dynamicProps) {
if (schEvaluated.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
}
}
else {
const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
}
}
if (it.items !== true) {
if (schEvaluated && !schEvaluated.dynamicItems) {
if (schEvaluated.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
}
}
else {
const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
}
}
}
}
exports.callRef = callRef;
exports["default"] = def;
//# sourceMappingURL=ref.js.map
/***/ }),
/***/ 32818:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const types_1 = __nccwpck_require__(63961);
const compile_1 = __nccwpck_require__(40879);
const ref_error_1 = __nccwpck_require__(19083);
const util_1 = __nccwpck_require__(63149);
const error = {
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
? `tag "${tagName}" must be string`
: `value of tag "${tagName}" must be in oneOf`,
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
keyword: "discriminator",
type: "object",
schemaType: "object",
error,
code(cxt) {
const { gen, data, schema, parentSchema, it } = cxt;
const { oneOf } = parentSchema;
if (!it.opts.discriminator) {
throw new Error("discriminator: requires discriminator option");
}
const tagName = schema.propertyName;
if (typeof tagName != "string")
throw new Error("discriminator: requires propertyName");
if (schema.mapping)
throw new Error("discriminator: mapping is not supported");
if (!oneOf)
throw new Error("discriminator: requires oneOf keyword");
const valid = gen.let("valid", false);
const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
cxt.ok(valid);
function validateMapping() {
const mapping = getMapping();
gen.if(false);
for (const tagValue in mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
gen.assign(valid, applyTagSchema(mapping[tagValue]));
}
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
gen.endIf();
}
function applyTagSchema(schemaProp) {
const _valid = gen.name("valid");
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
cxt.mergeEvaluated(schCxt, codegen_1.Name);
return _valid;
}
function getMapping() {
var _a;
const oneOfMapping = {};
const topRequired = hasRequired(parentSchema);
let tagRequired = true;
for (let i = 0; i < oneOf.length; i++) {
let sch = oneOf[i];
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
const ref = sch.$ref;
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
if (sch instanceof compile_1.SchemaEnv)
sch = sch.schema;
if (sch === undefined)
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
}
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
if (typeof propSch != "object") {
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
}
tagRequired = tagRequired && (topRequired || hasRequired(sch));
addMappings(propSch, i);
}
if (!tagRequired)
throw new Error(`discriminator: "${tagName}" must be required`);
return oneOfMapping;
function hasRequired({ required }) {
return Array.isArray(required) && required.includes(tagName);
}
function addMappings(sch, i) {
if (sch.const) {
addMapping(sch.const, i);
}
else if (sch.enum) {
for (const tagValue of sch.enum) {
addMapping(tagValue, i);
}
}
else {
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
}
}
function addMapping(tagValue, i) {
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
}
oneOfMapping[tagValue] = i;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 63961:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
DiscrError["Tag"] = "tag";
DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 49329:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const core_1 = __nccwpck_require__(73336);
const validation_1 = __nccwpck_require__(20737);
const applicator_1 = __nccwpck_require__(69193);
const format_1 = __nccwpck_require__(77111);
const metadata_1 = __nccwpck_require__(24042);
const draft7Vocabularies = [
core_1.default,
validation_1.default,
(0, applicator_1.default)(),
format_1.default,
metadata_1.metadataVocabulary,
metadata_1.contentVocabulary,
];
exports["default"] = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map
/***/ }),
/***/ 11430:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
keyword: "format",
type: ["number", "string"],
schemaType: "string",
$data: true,
error,
code(cxt, ruleType) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
const { opts, errSchemaPath, schemaEnv, self } = it;
if (!opts.validateFormats)
return;
if ($data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
});
const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
const fType = gen.let("fType");
const format = gen.let("format");
// TODO simplify
gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
function unknownFmt() {
if (opts.strictSchema === false)
return codegen_1.nil;
return (0, codegen_1._) `${schemaCode} && !${format}`;
}
function invalidFmt() {
const callFormat = schemaEnv.$async
? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
: (0, codegen_1._) `${format}(${data})`;
const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
}
}
function validateFormat() {
const formatDef = self.formats[schema];
if (!formatDef) {
unknownFormat();
return;
}
if (formatDef === true)
return;
const [fmtType, format, fmtRef] = getFormat(formatDef);
if (fmtType === ruleType)
cxt.pass(validCondition());
function unknownFormat() {
if (opts.strictSchema === false) {
self.logger.warn(unknownMsg());
return;
}
throw new Error(unknownMsg());
function unknownMsg() {
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
}
}
function getFormat(fmtDef) {
const code = fmtDef instanceof RegExp
? (0, codegen_1.regexpCode)(fmtDef)
: opts.code.formats
? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
: undefined;
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
}
return ["string", fmtDef, fmt];
}
function validCondition() {
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
if (!schemaEnv.$async)
throw new Error("async format in sync schema");
return (0, codegen_1._) `await ${fmtRef}(${data})`;
}
return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=format.js.map
/***/ }),
/***/ 77111:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const format_1 = __nccwpck_require__(11430);
const format = [format_1.default];
exports["default"] = format;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 24042:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
"title",
"description",
"default",
"deprecated",
"readOnly",
"writeOnly",
"examples",
];
exports.contentVocabulary = [
"contentMediaType",
"contentEncoding",
"contentSchema",
];
//# sourceMappingURL=metadata.js.map
/***/ }),
/***/ 4551:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const equal_1 = __nccwpck_require__(23403);
const error = {
message: "must be equal to constant",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
keyword: "const",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schemaCode, schema } = cxt;
if ($data || (schema && typeof schema == "object")) {
cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
}
else {
cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
}
},
};
exports["default"] = def;
//# sourceMappingURL=const.js.map
/***/ }),
/***/ 76502:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const equal_1 = __nccwpck_require__(23403);
const error = {
message: "must be equal to one of the allowed values",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
keyword: "enum",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
if (!$data && schema.length === 0)
throw new Error("enum must have non-empty array");
const useLoop = schema.length >= it.opts.loopEnum;
let eql;
const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
let valid;
if (useLoop || $data) {
valid = gen.let("valid");
cxt.block$data(valid, loopEnum);
}
else {
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const vSchema = gen.const("vSchema", schemaCode);
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
}
cxt.pass(valid);
function loopEnum() {
gen.assign(valid, false);
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
}
function equalCode(vSchema, i) {
const sch = schema[i];
return typeof sch === "object" && sch !== null
? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
: (0, codegen_1._) `${data} === ${sch}`;
}
},
};
exports["default"] = def;
//# sourceMappingURL=enum.js.map
/***/ }),
/***/ 20737:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const limitNumber_1 = __nccwpck_require__(80643);
const multipleOf_1 = __nccwpck_require__(6069);
const limitLength_1 = __nccwpck_require__(71995);
const pattern_1 = __nccwpck_require__(28196);
const limitProperties_1 = __nccwpck_require__(74549);
const required_1 = __nccwpck_require__(18956);
const limitItems_1 = __nccwpck_require__(75780);
const uniqueItems_1 = __nccwpck_require__(78591);
const const_1 = __nccwpck_require__(4551);
const enum_1 = __nccwpck_require__(76502);
const validation = [
// number
limitNumber_1.default,
multipleOf_1.default,
// string
limitLength_1.default,
pattern_1.default,
// object
limitProperties_1.default,
required_1.default,
// array
limitItems_1.default,
uniqueItems_1.default,
// any
{ keyword: "type", schemaType: ["string", "array"] },
{ keyword: "nullable", schemaType: "boolean" },
const_1.default,
enum_1.default,
];
exports["default"] = validation;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 75780:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxItems" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxItems", "minItems"],
type: "array",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitItems.js.map
/***/ }),
/***/ 71995:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const ucs2length_1 = __nccwpck_require__(39300);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxLength" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode, it } = cxt;
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitLength.js.map
/***/ }),
/***/ 80643:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const ops = codegen_1.operators;
const KWDs = {
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
keyword: Object.keys(KWDs),
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitNumber.js.map
/***/ }),
/***/ 74549:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxProperties" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxProperties", "minProperties"],
type: "object",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitProperties.js.map
/***/ }),
/***/ 6069:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(20893);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
keyword: "multipleOf",
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, it } = cxt;
// const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
const prec = it.opts.multipleOfPrecision;
const res = gen.let("res");
const invalid = prec
? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
: (0, codegen_1._) `${res} !== parseInt(${res})`;
cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
},
};
exports["default"] = def;
//# sourceMappingURL=multipleOf.js.map
/***/ }),
/***/ 28196:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(51457);
const codegen_1 = __nccwpck_require__(20893);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
keyword: "pattern",
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { data, $data, schema, schemaCode, it } = cxt;
// TODO regexp should be wrapped in try/catchs
const u = it.opts.unicodeRegExp ? "u" : "";
const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=pattern.js.map
/***/ }),
/***/ 18956:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(51457);
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const error = {
message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
keyword: "required",
type: "object",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, schema, schemaCode, data, $data, it } = cxt;
const { opts } = it;
if (!$data && schema.length === 0)
return;
const useLoop = schema.length >= opts.loopRequired;
if (it.allErrors)
allErrorsMode();
else
exitOnErrorMode();
if (opts.strictRequired) {
const props = cxt.parentSchema.properties;
const { definedProperties } = cxt.it;
for (const requiredKey of schema) {
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
}
}
}
function allErrorsMode() {
if (useLoop || $data) {
cxt.block$data(codegen_1.nil, loopAllRequired);
}
else {
for (const prop of schema) {
(0, code_1.checkReportMissingProp)(cxt, prop);
}
}
}
function exitOnErrorMode() {
const missing = gen.let("missing");
if (useLoop || $data) {
const valid = gen.let("valid", true);
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
cxt.ok(valid);
}
else {
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
function loopAllRequired() {
gen.forOf("prop", schemaCode, (prop) => {
cxt.setParams({ missingProperty: prop });
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
});
}
function loopUntilMissing(missing, valid) {
cxt.setParams({ missingProperty: missing });
gen.forOf(missing, schemaCode, () => {
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
gen.if((0, codegen_1.not)(valid), () => {
cxt.error();
gen.break();
});
}, codegen_1.nil);
}
},
};
exports["default"] = def;
//# sourceMappingURL=required.js.map
/***/ }),
/***/ 78591:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const dataType_1 = __nccwpck_require__(78570);
const codegen_1 = __nccwpck_require__(20893);
const util_1 = __nccwpck_require__(63149);
const equal_1 = __nccwpck_require__(23403);
const error = {
message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
keyword: "uniqueItems",
type: "array",
schemaType: "boolean",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
if (!$data && !schema)
return;
const valid = gen.let("valid");
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
cxt.ok(valid);
function validateUniqueItems() {
const i = gen.let("i", (0, codegen_1._) `${data}.length`);
const j = gen.let("j");
cxt.setParams({ i, j });
gen.assign(valid, true);
gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
}
function canOptimize() {
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
}
function loopN(i, j) {
const item = gen.name("item");
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
const indices = gen.const("indices", (0, codegen_1._) `{}`);
gen.for((0, codegen_1._) `;${i}--;`, () => {
gen.let(item, (0, codegen_1._) `${data}[${i}]`);
gen.if(wrongType, (0, codegen_1._) `continue`);
if (itemTypes.length > 1)
gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
gen
.if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
cxt.error();
gen.assign(valid, false).break();
})
.code((0, codegen_1._) `${indices}[${item}] = ${i}`);
});
}
function loopN2(i, j) {
const eql = (0, util_1.useFunc)(gen, equal_1.default);
const outer = gen.name("outer");
gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
cxt.error();
gen.assign(valid, false).break(outer);
})));
}
},
};
exports["default"] = def;
//# sourceMappingURL=uniqueItems.js.map
/***/ }),
/***/ 6702:
/***/ ((module) => {
"use strict";
var traverse = module.exports = function (schema, opts, cb) {
// Legacy support for v0.3.1 and earlier.
if (typeof opts == 'function') {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
var post = cb.post || function() {};
_traverse(opts, pre, post, schema, '', schema);
};
traverse.keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
if: true,
then: true,
else: true
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
$defs: true,
definitions: true,
properties: true,
patternProperties: true,
dependencies: true
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
maximum: true,
minimum: true,
exclusiveMaximum: true,
exclusiveMinimum: true,
multipleOf: true,
maxLength: true,
minLength: true,
pattern: true,
format: true,
maxItems: true,
minItems: true,
uniqueItems: true,
maxProperties: true,
minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i=0; i<sch.length; i++)
_traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == 'object') {
for (var prop in sch)
_traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
_traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
function escapeJsonPtr(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
/***/ }),
/***/ 55768:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
module.exports = __nccwpck_require__(56196)().Promise
/***/ }),
/***/ 34549:
/***/ ((module) => {
"use strict";
// global key for user preferred registration
var REGISTRATION_KEY = '@@any-promise/REGISTRATION',
// Prior registration (preferred or detected)
registered = null
/**
* Registers the given implementation. An implementation must
* be registered prior to any call to `require("any-promise")`,
* typically on application load.
*
* If called with no arguments, will return registration in
* following priority:
*
* For Node.js:
*
* 1. Previous registration
* 2. global.Promise if node.js version >= 0.12
* 3. Auto detected promise based on first sucessful require of
* known promise libraries. Note this is a last resort, as the
* loaded library is non-deterministic. node.js >= 0.12 will
* always use global.Promise over this priority list.
* 4. Throws error.
*
* For Browser:
*
* 1. Previous registration
* 2. window.Promise
* 3. Throws error.
*
* Options:
*
* Promise: Desired Promise constructor
* global: Boolean - Should the registration be cached in a global variable to
* allow cross dependency/bundle registration? (default true)
*/
module.exports = function(root, loadImplementation){
return function register(implementation, opts){
implementation = implementation || null
opts = opts || {}
// global registration unless explicitly {global: false} in options (default true)
var registerGlobal = opts.global !== false;
// load any previous global registration
if(registered === null && registerGlobal){
registered = root[REGISTRATION_KEY] || null
}
if(registered !== null
&& implementation !== null
&& registered.implementation !== implementation){
// Throw error if attempting to redefine implementation
throw new Error('any-promise already defined as "'+registered.implementation+
'". You can only register an implementation before the first '+
' call to require("any-promise") and an implementation cannot be changed')
}
if(registered === null){
// use provided implementation
if(implementation !== null && typeof opts.Promise !== 'undefined'){
registered = {
Promise: opts.Promise,
implementation: implementation
}
} else {
// require implementation if implementation is specified but not provided
registered = loadImplementation(implementation)
}
if(registerGlobal){
// register preference globally in case multiple installations
root[REGISTRATION_KEY] = registered
}
}
return registered
}
}
/***/ }),
/***/ 56196:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports = __nccwpck_require__(34549)(global, loadImplementation);
/**
* Node.js version of loadImplementation.
*
* Requires the given implementation and returns the registration
* containing {Promise, implementation}
*
* If implementation is undefined or global.Promise, loads it
* Otherwise uses require
*/
function loadImplementation(implementation){
var impl = null
if(shouldPreferGlobalPromise(implementation)){
// if no implementation or env specified use global.Promise
impl = {
Promise: global.Promise,
implementation: 'global.Promise'
}
} else if(implementation){
// if implementation specified, require it
var lib = require(implementation)
impl = {
Promise: lib.Promise || lib,
implementation: implementation
}
} else {
// try to auto detect implementation. This is non-deterministic
// and should prefer other branches, but this is our last chance
// to load something without throwing error
impl = tryAutoDetect()
}
if(impl === null){
throw new Error('Cannot find any-promise implementation nor'+
' global.Promise. You must install polyfill or call'+
' require("any-promise/register") with your preferred'+
' implementation, e.g. require("any-promise/register/bluebird")'+
' on application load prior to any require("any-promise").')
}
return impl
}
/**
* Determines if the global.Promise should be preferred if an implementation
* has not been registered.
*/
function shouldPreferGlobalPromise(implementation){
if(implementation){
return implementation === 'global.Promise'
} else if(typeof global.Promise !== 'undefined'){
// Load global promise if implementation not specified
// Versions < 0.11 did not have global Promise
// Do not use for version < 0.12 as version 0.11 contained buggy versions
var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version)
return !(version && +version[1] == 0 && +version[2] < 12)
}
// do not have global.Promise or another implementation was specified
return false
}
/**
* Look for common libs as last resort there is no guarantee that
* this will return a desired implementation or even be deterministic.
* The priority is also nearly arbitrary. We are only doing this
* for older versions of Node.js <0.12 that do not have a reasonable
* global.Promise implementation and we the user has not registered
* the preference. This preserves the behavior of any-promise <= 0.1
* and may be deprecated or removed in the future
*/
function tryAutoDetect(){
var libs = [
"es6-promise",
"promise",
"native-promise-only",
"bluebird",
"rsvp",
"when",
"q",
"pinkie",
"lie",
"vow"]
var i = 0, len = libs.length
for(; i < len; i++){
try {
return loadImplementation(libs[i])
} catch(e){}
}
return null
}
/***/ }),
/***/ 14812:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
module.exports =
{
parallel : __nccwpck_require__(8210),
serial : __nccwpck_require__(50445),
serialOrdered : __nccwpck_require__(3578)
};
/***/ }),
/***/ 1700:
/***/ ((module) => {
// API
module.exports = abort;
/**
* Aborts leftover active jobs
*
* @param {object} state - current state object
*/
function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
}
/**
* Cleans up leftover job by invoking abort function for the provided job id
*
* @this state
* @param {string|number} key - job id to abort
*/
function clean(key)
{
if (typeof this.jobs[key] == 'function')
{
this.jobs[key]();
}
}
/***/ }),
/***/ 72794:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var defer = __nccwpck_require__(15295);
// API
module.exports = async;
/**
* Runs provided callback asynchronously
* even if callback itself is not
*
* @param {function} callback - callback to invoke
* @returns {function} - augmented callback
*/
function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
}
/***/ }),
/***/ 15295:
/***/ ((module) => {
module.exports = defer;
/**
* Runs provided function on next iteration of the event loop
*
* @param {function} fn - function to run
*/
function defer(fn)
{
var nextTick = typeof setImmediate == 'function'
? setImmediate
: (
typeof process == 'object' && typeof process.nextTick == 'function'
? process.nextTick
: null
);
if (nextTick)
{
nextTick(fn);
}
else
{
setTimeout(fn, 0);
}
}
/***/ }),
/***/ 9023:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var async = __nccwpck_require__(72794)
, abort = __nccwpck_require__(1700)
;
// API
module.exports = iterate;
/**
* Iterates over each job object
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {object} state - current job status
* @param {function} callback - invoked when all elements processed
*/
function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
}
/**
* Runs iterator over provided job element
*
* @param {function} iterator - iterator to invoke
* @param {string|number} key - key/index of the element in the list of jobs
* @param {mixed} item - job description
* @param {function} callback - invoked after iterator is done with the job
* @returns {function|mixed} - job abort function or something else
*/
function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
}
/***/ }),
/***/ 42474:
/***/ ((module) => {
// API
module.exports = state;
/**
* Creates initial state object
* for iteration over list
*
* @param {array|object} list - list to iterate over
* @param {function|null} sortMethod - function to use for keys sort,
* or `null` to keep them as is
* @returns {object} - initial state object
*/
function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
}
/***/ }),
/***/ 37942:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var abort = __nccwpck_require__(1700)
, async = __nccwpck_require__(72794)
;
// API
module.exports = terminator;
/**
* Terminates jobs in the attached state context
*
* @this AsyncKitState#
* @param {function} callback - final callback to invoke after termination
*/
function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
}
/***/ }),
/***/ 8210:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var iterate = __nccwpck_require__(9023)
, initState = __nccwpck_require__(42474)
, terminator = __nccwpck_require__(37942)
;
// Public API
module.exports = parallel;
/**
* Runs iterator over provided array elements in parallel
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
}
/***/ }),
/***/ 50445:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var serialOrdered = __nccwpck_require__(3578);
// Public API
module.exports = serial;
/**
* Runs iterator over provided array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serial(list, iterator, callback)
{
return serialOrdered(list, iterator, null, callback);
}
/***/ }),
/***/ 3578:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var iterate = __nccwpck_require__(9023)
, initState = __nccwpck_require__(42474)
, terminator = __nccwpck_require__(37942)
;
// Public API
module.exports = serialOrdered;
// sorting helpers
module.exports.ascending = ascending;
module.exports.descending = descending;
/**
* Runs iterator over provided sorted array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
}
/*
* -- Sort methods
*/
/**
* sort helper to sort array elements in ascending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function ascending(a, b)
{
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* sort helper to sort array elements in descending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function descending(a, b)
{
return -1 * ascending(a, b);
}
/***/ }),
/***/ 86950:
/***/ ((module) => {
"use strict";
/* global SharedArrayBuffer, Atomics */
if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {
const nil = new Int32Array(new SharedArrayBuffer(4))
function sleep (ms) {
// also filters out NaN, non-number types, including empty strings, but allows bigints
const valid = ms > 0 && ms < Infinity
if (valid === false) {
if (typeof ms !== 'number' && typeof ms !== 'bigint') {
throw TypeError('sleep: ms must be a number')
}
throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')
}
Atomics.wait(nil, 0, 0, Number(ms))
}
module.exports = sleep
} else {
function sleep (ms) {
// also filters out NaN, non-number types, including empty strings, but allows bigints
const valid = ms > 0 && ms < Infinity
if (valid === false) {
if (typeof ms !== 'number' && typeof ms !== 'bigint') {
throw TypeError('sleep: ms must be a number')
}
throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')
}
const target = Date.now() + Number(ms)
while (target > Date.now()){}
}
module.exports = sleep
}
/***/ }),
/***/ 85443:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var util = __nccwpck_require__(73837);
var Stream = (__nccwpck_require__(12781).Stream);
var DelayedStream = __nccwpck_require__(18611);
module.exports = CombinedStream;
function CombinedStream() {
this.writable = false;
this.readable = true;
this.dataSize = 0;
this.maxDataSize = 2 * 1024 * 1024;
this.pauseStreams = true;
this._released = false;
this._streams = [];
this._currentStream = null;
this._insideLoop = false;
this._pendingNext = false;
}
util.inherits(CombinedStream, Stream);
CombinedStream.create = function(options) {
var combinedStream = new this();
options = options || {};
for (var option in options) {
combinedStream[option] = options[option];
}
return combinedStream;
};
CombinedStream.isStreamLike = function(stream) {
return (typeof stream !== 'function')
&& (typeof stream !== 'string')
&& (typeof stream !== 'boolean')
&& (typeof stream !== 'number')
&& (!Buffer.isBuffer(stream));
};
CombinedStream.prototype.append = function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
if (!(stream instanceof DelayedStream)) {
var newStream = DelayedStream.create(stream, {
maxDataSize: Infinity,
pauseStream: this.pauseStreams,
});
stream.on('data', this._checkDataSize.bind(this));
stream = newStream;
}
this._handleErrors(stream);
if (this.pauseStreams) {
stream.pause();
}
}
this._streams.push(stream);
return this;
};
CombinedStream.prototype.pipe = function(dest, options) {
Stream.prototype.pipe.call(this, dest, options);
this.resume();
return dest;
};
CombinedStream.prototype._getNext = function() {
this._currentStream = null;
if (this._insideLoop) {
this._pendingNext = true;
return; // defer call
}
this._insideLoop = true;
try {
do {
this._pendingNext = false;
this._realGetNext();
} while (this._pendingNext);
} finally {
this._insideLoop = false;
}
};
CombinedStream.prototype._realGetNext = function() {
var stream = this._streams.shift();
if (typeof stream == 'undefined') {
this.end();
return;
}
if (typeof stream !== 'function') {
this._pipeNext(stream);
return;
}
var getStream = stream;
getStream(function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('data', this._checkDataSize.bind(this));
this._handleErrors(stream);
}
this._pipeNext(stream);
}.bind(this));
};
CombinedStream.prototype._pipeNext = function(stream) {
this._currentStream = stream;
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('end', this._getNext.bind(this));
stream.pipe(this, {end: false});
return;
}
var value = stream;
this.write(value);
this._getNext();
};
CombinedStream.prototype._handleErrors = function(stream) {
var self = this;
stream.on('error', function(err) {
self._emitError(err);
});
};
CombinedStream.prototype.write = function(data) {
this.emit('data', data);
};
CombinedStream.prototype.pause = function() {
if (!this.pauseStreams) {
return;
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
this.emit('pause');
};
CombinedStream.prototype.resume = function() {
if (!this._released) {
this._released = true;
this.writable = true;
this._getNext();
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
this.emit('resume');
};
CombinedStream.prototype.end = function() {
this._reset();
this.emit('end');
};
CombinedStream.prototype.destroy = function() {
this._reset();
this.emit('close');
};
CombinedStream.prototype._reset = function() {
this.writable = false;
this._streams = [];
this._currentStream = null;
};
CombinedStream.prototype._checkDataSize = function() {
this._updateDataSize();
if (this.dataSize <= this.maxDataSize) {
return;
}
var message =
'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
this._emitError(new Error(message));
};
CombinedStream.prototype._updateDataSize = function() {
this.dataSize = 0;
var self = this;
this._streams.forEach(function(stream) {
if (!stream.dataSize) {
return;
}
self.dataSize += stream.dataSize;
});
if (this._currentStream && this._currentStream.dataSize) {
this.dataSize += this._currentStream.dataSize;
}
};
CombinedStream.prototype._emitError = function(err) {
this._reset();
this.emit('error', err);
};
/***/ }),
/***/ 93658:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
* @public
*/
exports.parse = parse;
exports.serialize = serialize;
/**
* Module variables.
* @private
*/
var __toString = Object.prototype.toString
/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*
* @param {string} str
* @param {object} [options]
* @return {object}
* @public
*/
function parse(str, options) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
var obj = {}
var opt = options || {};
var dec = opt.decode || decode;
var index = 0
while (index < str.length) {
var eqIdx = str.indexOf('=', index)
// no more cookie pairs
if (eqIdx === -1) {
break
}
var endIdx = str.indexOf(';', index)
if (endIdx === -1) {
endIdx = str.length
} else if (endIdx < eqIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(';', eqIdx - 1) + 1
continue
}
var key = str.slice(index, eqIdx).trim()
// only assign once
if (undefined === obj[key]) {
var val = str.slice(eqIdx + 1, endIdx).trim()
// quoted values
if (val.charCodeAt(0) === 0x22) {
val = val.slice(1, -1)
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1
}
return obj;
}
/**
* Serialize data into a cookie header.
*
* Serialize the a name value pair into a cookie string suitable for
* http headers. An optional options object specified cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*
* @param {string} name
* @param {string} val
* @param {object} [options]
* @return {string}
* @public
*/
function serialize(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid');
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError('argument name is invalid');
}
var value = enc(val);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError('argument val is invalid');
}
var str = name + '=' + value;
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge) || !isFinite(maxAge)) {
throw new TypeError('option maxAge is invalid')
}
str += '; Max-Age=' + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += '; Domain=' + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += '; Path=' + opt.path;
}
if (opt.expires) {
var expires = opt.expires
if (!isDate(expires) || isNaN(expires.valueOf())) {
throw new TypeError('option expires is invalid');
}
str += '; Expires=' + expires.toUTCString()
}
if (opt.httpOnly) {
str += '; HttpOnly';
}
if (opt.secure) {
str += '; Secure';
}
if (opt.partitioned) {
str += '; Partitioned'
}
if (opt.priority) {
var priority = typeof opt.priority === 'string'
? opt.priority.toLowerCase()
: opt.priority
switch (priority) {
case 'low':
str += '; Priority=Low'
break
case 'medium':
str += '; Priority=Medium'
break
case 'high':
str += '; Priority=High'
break
default:
throw new TypeError('option priority is invalid')
}
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === 'string'
? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += '; SameSite=Strict';
break;
case 'lax':
str += '; SameSite=Lax';
break;
case 'strict':
str += '; SameSite=Strict';
break;
case 'none':
str += '; SameSite=None';
break;
default:
throw new TypeError('option sameSite is invalid');
}
}
return str;
}
/**
* URL-decode string value. Optimized to skip native call when no %.
*
* @param {string} str
* @returns {string}
*/
function decode (str) {
return str.indexOf('%') !== -1
? decodeURIComponent(str)
: str
}
/**
* URL-encode value.
*
* @param {string} val
* @returns {string}
*/
function encode (val) {
return encodeURIComponent(val)
}
/**
* Determine if value is a Date.
*
* @param {*} val
* @private
*/
function isDate (val) {
return __toString.call(val) === '[object Date]' ||
val instanceof Date
}
/**
* Try decoding a string using a decoding function.
*
* @param {string} str
* @param {function} decode
* @private
*/
function tryDecode(str, decode) {
try {
return decode(str);
} catch (e) {
return str;
}
}
/***/ }),
/***/ 28222:
/***/ ((module, exports, __nccwpck_require__) => {
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = __nccwpck_require__(46243)(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
/***/ }),
/***/ 46243:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = __nccwpck_require__(80900);
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
/***/ }),
/***/ 38237:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = __nccwpck_require__(28222);
} else {
module.exports = __nccwpck_require__(35332);
}
/***/ }),
/***/ 35332:
/***/ ((module, exports, __nccwpck_require__) => {
/**
* Module dependencies.
*/
const tty = __nccwpck_require__(76224);
const util = __nccwpck_require__(73837);
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = __nccwpck_require__(59318);
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = __nccwpck_require__(46243)(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/***/ }),
/***/ 18611:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var Stream = (__nccwpck_require__(12781).Stream);
var util = __nccwpck_require__(73837);
module.exports = DelayedStream;
function DelayedStream() {
this.source = null;
this.dataSize = 0;
this.maxDataSize = 1024 * 1024;
this.pauseStream = true;
this._maxDataSizeExceeded = false;
this._released = false;
this._bufferedEvents = [];
}
util.inherits(DelayedStream, Stream);
DelayedStream.create = function(source, options) {
var delayedStream = new this();
options = options || {};
for (var option in options) {
delayedStream[option] = options[option];
}
delayedStream.source = source;
var realEmit = source.emit;
source.emit = function() {
delayedStream._handleEmit(arguments);
return realEmit.apply(source, arguments);
};
source.on('error', function() {});
if (delayedStream.pauseStream) {
source.pause();
}
return delayedStream;
};
Object.defineProperty(DelayedStream.prototype, 'readable', {
configurable: true,
enumerable: true,
get: function() {
return this.source.readable;
}
});
DelayedStream.prototype.setEncoding = function() {
return this.source.setEncoding.apply(this.source, arguments);
};
DelayedStream.prototype.resume = function() {
if (!this._released) {
this.release();
}
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;
}
if (args[0] === 'data') {
this.dataSize += args[1].length;
this._checkIfMaxDataSizeExceeded();
}
this._bufferedEvents.push(args);
};
DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
if (this._maxDataSizeExceeded) {
return;
}
if (this.dataSize <= this.maxDataSize) {
return;
}
this._maxDataSizeExceeded = true;
var message =
'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
this.emit('error', new Error(message));
};
/***/ }),
/***/ 81205:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var once = __nccwpck_require__(1223);
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var cancelled = false;
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback.call(stream);
};
var onend = function() {
readable = false;
if (!writable) callback.call(stream);
};
var onexit = function(exitCode) {
callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
};
var onerror = function(err) {
callback.call(stream, err);
};
var onclose = function() {
process.nextTick(onclosenexttick);
};
var onclosenexttick = function() {
if (cancelled) return;
if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
if (isChildProcess(stream)) stream.on('exit', onexit);
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function() {
cancelled = true;
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('exit', onexit);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
/***/ }),
/***/ 46673:
/***/ ((module) => {
"use strict";
const NullObject = function NullObject () { }
NullObject.prototype = Object.create(null)
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
* obs-text = %x80-FF
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
const paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu
/**
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
*
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
* obs-text = %x80-FF
*/
const quotedPairRE = /\\([\v\u0020-\u00ff])/gu
/**
* RegExp to match type in RFC 7231 sec 3.1.1.1
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
const mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u
// default ContentType to prevent repeated object creation
const defaultContentType = { type: '', parameters: new NullObject() }
Object.freeze(defaultContentType.parameters)
Object.freeze(defaultContentType)
/**
* Parse media type to object.
*
* @param {string|object} header
* @return {Object}
* @public
*/
function parse (header) {
if (typeof header !== 'string') {
throw new TypeError('argument header is required and must be a string')
}
let index = header.indexOf(';')
const type = index !== -1
? header.slice(0, index).trim()
: header.trim()
if (mediaTypeRE.test(type) === false) {
throw new TypeError('invalid media type')
}
const result = {
type: type.toLowerCase(),
parameters: new NullObject()
}
// parse parameters
if (index === -1) {
return result
}
let key
let match
let value
paramRE.lastIndex = index
while ((match = paramRE.exec(header))) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.slice(1, value.length - 1)
quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
}
result.parameters[key] = value
}
if (index !== header.length) {
throw new TypeError('invalid parameter format')
}
return result
}
function safeParse (header) {
if (typeof header !== 'string') {
return defaultContentType
}
let index = header.indexOf(';')
const type = index !== -1
? header.slice(0, index).trim()
: header.trim()
if (mediaTypeRE.test(type) === false) {
return defaultContentType
}
const result = {
type: type.toLowerCase(),
parameters: new NullObject()
}
// parse parameters
if (index === -1) {
return result
}
let key
let match
let value
paramRE.lastIndex = index
while ((match = paramRE.exec(header))) {
if (match.index !== index) {
return defaultContentType
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.slice(1, value.length - 1)
quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
}
result.parameters[key] = value
}
if (index !== header.length) {
return defaultContentType
}
return result
}
module.exports["default"] = { parse, safeParse }
module.exports.parse = parse
module.exports.safeParse = safeParse
module.exports.defaultContentType = defaultContentType
/***/ }),
/***/ 1960:
/***/ ((module) => {
"use strict";
var UTF8_ACCEPT = 12
var UTF8_REJECT = 0
var UTF8_DATA = [
// The first part of the table maps bytes to character to a transition.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 7,
10, 9, 9, 9, 11, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
// The second part of the table maps a state to a new state when adding a
// transition.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 24, 36, 48, 60, 72, 84, 96,
0, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0,
0, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0,
0, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 48, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0,
0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// The third part maps the current transition to a mask that needs to apply
// to the byte.
0x7F, 0x3F, 0x3F, 0x3F, 0x00, 0x1F, 0x0F, 0x0F, 0x0F, 0x07, 0x07, 0x07
]
function decodeURIComponent (uri) {
var percentPosition = uri.indexOf('%')
if (percentPosition === -1) return uri
var length = uri.length
var decoded = ''
var last = 0
var codepoint = 0
var startOfOctets = percentPosition
var state = UTF8_ACCEPT
while (percentPosition > -1 && percentPosition < length) {
var high = hexCodeToInt(uri[percentPosition + 1], 4)
var low = hexCodeToInt(uri[percentPosition + 2], 0)
var byte = high | low
var type = UTF8_DATA[byte]
state = UTF8_DATA[256 + state + type]
codepoint = (codepoint << 6) | (byte & UTF8_DATA[364 + type])
if (state === UTF8_ACCEPT) {
decoded += uri.slice(last, startOfOctets)
decoded += (codepoint <= 0xFFFF)
? String.fromCharCode(codepoint)
: String.fromCharCode(
(0xD7C0 + (codepoint >> 10)),
(0xDC00 + (codepoint & 0x3FF))
)
codepoint = 0
last = percentPosition + 3
percentPosition = startOfOctets = uri.indexOf('%', last)
} else if (state === UTF8_REJECT) {
return null
} else {
percentPosition += 3
if (percentPosition < length && uri.charCodeAt(percentPosition) === 37) continue
return null
}
}
return decoded + uri.slice(last)
}
var HEX = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'a': 10,
'A': 10,
'b': 11,
'B': 11,
'c': 12,
'C': 12,
'd': 13,
'D': 13,
'e': 14,
'E': 14,
'f': 15,
'F': 15
}
function hexCodeToInt (c, shift) {
var i = HEX[c]
return i === undefined ? 255 : i << shift
}
module.exports = decodeURIComponent
/***/ }),
/***/ 28206:
/***/ ((module) => {
"use strict";
// do not edit .js files directly - edit src/index.jst
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
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;
}
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();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 66124:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
function fmtDef(validate, compare) {
return { validate, compare };
}
exports.fullFormats = {
// date: http://tools.ietf.org/html/rfc3339#section-5.6
date: fmtDef(date, compareDate),
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
time: fmtDef(getTime(true), compareTime),
"date-time": fmtDef(getDateTime(true), compareDateTime),
"iso-time": fmtDef(getTime(), compareIsoTime),
"iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
// duration: https://tools.ietf.org/html/rfc3339#appendix-A
duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
uri,
"uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
// uri-template: https://tools.ietf.org/html/rfc6570
"uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
regex,
// uuid: http://tools.ietf.org/html/rfc4122
uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
// JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
"json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
"relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
// the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
// byte: https://github.com/miguelmota/is-base64
byte,
// signed 32 bit integer
int32: { type: "number", validate: validateInt32 },
// signed 64 bit integer
int64: { type: "number", validate: validateInt64 },
// C-type float
float: { type: "number", validate: validateNumber },
// C-type double
double: { type: "number", validate: validateNumber },
// hint to the UI to hide input strings
password: true,
// unchecked string payload
binary: true,
};
exports.fastFormats = {
...exports.fullFormats,
date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
"date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
"iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
"iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
"uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
// email (sources from jsen validator):
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
};
exports.formatNames = Object.keys(exports.fullFormats);
function isLeapYear(year) {
// https://tools.ietf.org/html/rfc3339#appendix-C
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
const matches = DATE.exec(str);
if (!matches)
return false;
const year = +matches[1];
const month = +matches[2];
const day = +matches[3];
return (month >= 1 &&
month <= 12 &&
day >= 1 &&
day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));
}
function compareDate(d1, d2) {
if (!(d1 && d2))
return undefined;
if (d1 > d2)
return 1;
if (d1 < d2)
return -1;
return 0;
}
const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
function getTime(strictTimeZone) {
return function time(str) {
const matches = TIME.exec(str);
if (!matches)
return false;
const hr = +matches[1];
const min = +matches[2];
const sec = +matches[3];
const tz = matches[4];
const tzSign = matches[5] === "-" ? -1 : 1;
const tzH = +(matches[6] || 0);
const tzM = +(matches[7] || 0);
if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))
return false;
if (hr <= 23 && min <= 59 && sec < 60)
return true;
// leap second
const utcMin = min - tzM * tzSign;
const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
};
}
function compareTime(s1, s2) {
if (!(s1 && s2))
return undefined;
const t1 = new Date("2020-01-01T" + s1).valueOf();
const t2 = new Date("2020-01-01T" + s2).valueOf();
if (!(t1 && t2))
return undefined;
return t1 - t2;
}
function compareIsoTime(t1, t2) {
if (!(t1 && t2))
return undefined;
const a1 = TIME.exec(t1);
const a2 = TIME.exec(t2);
if (!(a1 && a2))
return undefined;
t1 = a1[1] + a1[2] + a1[3];
t2 = a2[1] + a2[2] + a2[3];
if (t1 > t2)
return 1;
if (t1 < t2)
return -1;
return 0;
}
const DATE_TIME_SEPARATOR = /t|\s/i;
function getDateTime(strictTimeZone) {
const time = getTime(strictTimeZone);
return function date_time(str) {
// http://tools.ietf.org/html/rfc3339#section-5.6
const dateTime = str.split(DATE_TIME_SEPARATOR);
return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
};
}
function compareDateTime(dt1, dt2) {
if (!(dt1 && dt2))
return undefined;
const d1 = new Date(dt1).valueOf();
const d2 = new Date(dt2).valueOf();
if (!(d1 && d2))
return undefined;
return d1 - d2;
}
function compareIsoDateTime(dt1, dt2) {
if (!(dt1 && dt2))
return undefined;
const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
const res = compareDate(d1, d2);
if (res === undefined)
return undefined;
return res || compareTime(t1, t2);
}
const NOT_URI_FRAGMENT = /\/|:/;
const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
function uri(str) {
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
function byte(str) {
BYTE.lastIndex = 0;
return BYTE.test(str);
}
const MIN_INT32 = -(2 ** 31);
const MAX_INT32 = 2 ** 31 - 1;
function validateInt32(value) {
return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
}
function validateInt64(value) {
// JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64
return Number.isInteger(value);
}
function validateNumber() {
return true;
}
const Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
if (Z_ANCHOR.test(str))
return false;
try {
new RegExp(str);
return true;
}
catch (e) {
return false;
}
}
//# sourceMappingURL=formats.js.map
/***/ }),
/***/ 40281:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const formats_1 = __nccwpck_require__(66124);
const limit_1 = __nccwpck_require__(67482);
const codegen_1 = __nccwpck_require__(56771);
const fullName = new codegen_1.Name("fullFormats");
const fastName = new codegen_1.Name("fastFormats");
const formatsPlugin = (ajv, opts = { keywords: true }) => {
if (Array.isArray(opts)) {
addFormats(ajv, opts, formats_1.fullFormats, fullName);
return ajv;
}
const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
const list = opts.formats || formats_1.formatNames;
addFormats(ajv, list, formats, exportName);
if (opts.keywords)
(0, limit_1.default)(ajv);
return ajv;
};
formatsPlugin.get = (name, mode = "full") => {
const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
const f = formats[name];
if (!f)
throw new Error(`Unknown format "${name}"`);
return f;
};
function addFormats(ajv, list, fs, exportName) {
var _a;
var _b;
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`);
for (const f of list)
ajv.addFormat(f, fs[f]);
}
module.exports = exports = formatsPlugin;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = formatsPlugin;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 67482:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatLimitDefinition = void 0;
const ajv_1 = __nccwpck_require__(41848);
const codegen_1 = __nccwpck_require__(56771);
const ops = codegen_1.operators;
const KWDs = {
formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
exports.formatLimitDefinition = {
keyword: Object.keys(KWDs),
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, keyword, it } = cxt;
const { opts, self } = it;
if (!opts.validateFormats)
return;
const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
if (fCxt.$data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
});
const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);
cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt)));
}
function validateFormat() {
const format = fCxt.schema;
const fmtDef = self.formats[format];
if (!fmtDef || fmtDef === true)
return;
if (typeof fmtDef != "object" ||
fmtDef instanceof RegExp ||
typeof fmtDef.compare != "function") {
throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
}
const fmt = gen.scopeValue("formats", {
key: format,
ref: fmtDef,
code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,
});
cxt.fail$data(compareCode(fmt));
}
function compareCode(fmt) {
return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
}
},
dependencies: ["format"],
};
const formatLimitPlugin = (ajv) => {
ajv.addKeyword(exports.formatLimitDefinition);
return ajv;
};
exports["default"] = formatLimitPlugin;
//# sourceMappingURL=limit.js.map
/***/ }),
/***/ 41848:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = __nccwpck_require__(10641);
const draft7_1 = __nccwpck_require__(73684);
const discriminator_1 = __nccwpck_require__(539);
const draft7MetaSchema = __nccwpck_require__(62570);
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
_addVocabularies() {
super._addVocabularies();
draft7_1.default.forEach((v) => this.addVocabulary(v));
if (this.opts.discriminator)
this.addKeyword(discriminator_1.default);
}
_addDefaultMetaSchema() {
super._addDefaultMetaSchema();
if (!this.opts.meta)
return;
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema;
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
}
defaultMeta() {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
}
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = Ajv;
var validate_1 = __nccwpck_require__(74504);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(56771);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
var validation_error_1 = __nccwpck_require__(19975);
Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } }));
var ref_error_1 = __nccwpck_require__(43857);
Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } }));
//# sourceMappingURL=ajv.js.map
/***/ }),
/***/ 82514:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
constructor(s) {
super();
if (!exports.IDENTIFIER.test(s))
throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return false;
}
get names() {
return { [this.str]: 1 };
}
}
exports.Name = Name;
class _Code extends _CodeOrName {
constructor(code) {
super();
this._items = typeof code === "string" ? [code] : code;
}
toString() {
return this.str;
}
emptyStr() {
if (this._items.length > 1)
return false;
const item = this._items[0];
return item === "" || item === '""';
}
get str() {
var _a;
return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
}
get names() {
var _a;
return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
if (c instanceof Name)
names[c.str] = (names[c.str] || 0) + 1;
return names;
}, {})));
}
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
const code = [strs[0]];
let i = 0;
while (i < args.length) {
addCodeArg(code, args[i]);
code.push(strs[++i]);
}
return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
const expr = [safeStringify(strs[0])];
let i = 0;
while (i < args.length) {
expr.push(plus);
addCodeArg(expr, args[i]);
expr.push(plus, safeStringify(strs[++i]));
}
optimize(expr);
return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
if (arg instanceof _Code)
code.push(...arg._items);
else if (arg instanceof Name)
code.push(arg);
else
code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
while (i < expr.length - 1) {
if (expr[i] === plus) {
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
if (res !== undefined) {
expr.splice(i - 1, 3, res);
continue;
}
expr[i++] = "+";
}
i++;
}
}
function mergeExprItems(a, b) {
if (b === '""')
return a;
if (a === '""')
return b;
if (typeof a == "string") {
if (b instanceof Name || a[a.length - 1] !== '"')
return;
if (typeof b != "string")
return `${a.slice(0, -1)}${b}"`;
if (b[0] === '"')
return a.slice(0, -1) + b.slice(1);
return;
}
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
return `"${a}${b.slice(1)}`;
return;
}
function strConcat(c1, c2) {
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
return typeof x == "number" || typeof x == "boolean" || x === null
? x
: safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
return JSON.stringify(x)
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
return new _Code(`${key}`);
}
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 56771:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = __nccwpck_require__(82514);
const scope_1 = __nccwpck_require__(20217);
var code_2 = __nccwpck_require__(82514);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return code_2._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return code_2.str; } }));
Object.defineProperty(exports, "strConcat", ({ enumerable: true, get: function () { return code_2.strConcat; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return code_2.nil; } }));
Object.defineProperty(exports, "getProperty", ({ enumerable: true, get: function () { return code_2.getProperty; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return code_2.stringify; } }));
Object.defineProperty(exports, "regexpCode", ({ enumerable: true, get: function () { return code_2.regexpCode; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return code_2.Name; } }));
var scope_2 = __nccwpck_require__(20217);
Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return scope_2.Scope; } }));
Object.defineProperty(exports, "ValueScope", ({ enumerable: true, get: function () { return scope_2.ValueScope; } }));
Object.defineProperty(exports, "ValueScopeName", ({ enumerable: true, get: function () { return scope_2.ValueScopeName; } }));
Object.defineProperty(exports, "varKinds", ({ enumerable: true, get: function () { return scope_2.varKinds; } }));
exports.operators = {
GT: new code_1._Code(">"),
GTE: new code_1._Code(">="),
LT: new code_1._Code("<"),
LTE: new code_1._Code("<="),
EQ: new code_1._Code("==="),
NEQ: new code_1._Code("!=="),
NOT: new code_1._Code("!"),
OR: new code_1._Code("||"),
AND: new code_1._Code("&&"),
ADD: new code_1._Code("+"),
};
class Node {
optimizeNodes() {
return this;
}
optimizeNames(_names, _constants) {
return this;
}
}
class Def extends Node {
constructor(varKind, name, rhs) {
super();
this.varKind = varKind;
this.name = name;
this.rhs = rhs;
}
render({ es5, _n }) {
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names, constants) {
if (!names[this.name.str])
return;
if (this.rhs)
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
}
class Assign extends Node {
constructor(lhs, rhs, sideEffects) {
super();
this.lhs = lhs;
this.rhs = rhs;
this.sideEffects = sideEffects;
}
render({ _n }) {
return `${this.lhs} = ${this.rhs};` + _n;
}
optimizeNames(names, constants) {
if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
return;
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
return addExprNames(names, this.rhs);
}
}
class AssignOp extends Assign {
constructor(lhs, op, rhs, sideEffects) {
super(lhs, rhs, sideEffects);
this.op = op;
}
render({ _n }) {
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
}
}
class Label extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
}
class Break extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
const label = this.label ? ` ${this.label}` : "";
return `break${label};` + _n;
}
}
class Throw extends Node {
constructor(error) {
super();
this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
}
class AnyCode extends Node {
constructor(code) {
super();
this.code = code;
}
render({ _n }) {
return `${this.code};` + _n;
}
optimizeNodes() {
return `${this.code}` ? this : undefined;
}
optimizeNames(names, constants) {
this.code = optimizeExpr(this.code, names, constants);
return this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
}
class ParentNode extends Node {
constructor(nodes = []) {
super();
this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i].optimizeNodes();
if (Array.isArray(n))
nodes.splice(i, 1, ...n);
else if (n)
nodes[i] = n;
else
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
optimizeNames(names, constants) {
const { nodes } = this;
let i = nodes.length;
while (i--) {
// iterating backwards improves 1-pass optimization
const n = nodes[i];
if (n.optimizeNames(names, constants))
continue;
subtractNames(names, n.names);
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : undefined;
}
get names() {
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
}
}
class BlockNode extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
constructor(condition, nodes) {
super(nodes);
this.condition = condition;
}
render(opts) {
let code = `if(${this.condition})` + super.render(opts);
if (this.else)
code += "else " + this.else.render(opts);
return code;
}
optimizeNodes() {
super.optimizeNodes();
const cond = this.condition;
if (cond === true)
return this.nodes; // else is ignored here
let e = this.else;
if (e) {
const ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e) {
if (cond === false)
return e instanceof If ? e : e.nodes;
if (this.nodes.length)
return this;
return new If(not(cond), e instanceof If ? [e] : e.nodes);
}
if (cond === false || !this.nodes.length)
return undefined;
return this;
}
optimizeNames(names, constants) {
var _a;
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
if (!(super.optimizeNames(names, constants) || this.else))
return;
this.condition = optimizeExpr(this.condition, names, constants);
return this;
}
get names() {
const names = super.names;
addExprNames(names, this.condition);
if (this.else)
addNames(names, this.else.names);
return names;
}
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
constructor(iteration) {
super();
this.iteration = iteration;
}
render(opts) {
return `for(${this.iteration})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iteration = optimizeExpr(this.iteration, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
}
class ForRange extends For {
constructor(varKind, name, from, to) {
super();
this.varKind = varKind;
this.name = name;
this.from = from;
this.to = to;
}
render(opts) {
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
const { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
const names = addExprNames(super.names, this.from);
return addExprNames(names, this.to);
}
}
class ForIter extends For {
constructor(loop, varKind, name, iterable) {
super();
this.loop = loop;
this.varKind = varKind;
this.name = name;
this.iterable = iterable;
}
render(opts) {
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants))
return;
this.iterable = optimizeExpr(this.iterable, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
}
class Func extends BlockNode {
constructor(name, args, async) {
super();
this.name = name;
this.args = args;
this.async = async;
}
render(opts) {
const _async = this.async ? "async " : "";
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
}
}
Func.kind = "func";
class Return extends ParentNode {
render(opts) {
return "return " + super.render(opts);
}
}
Return.kind = "return";
class Try extends BlockNode {
render(opts) {
let code = "try" + super.render(opts);
if (this.catch)
code += this.catch.render(opts);
if (this.finally)
code += this.finally.render(opts);
return code;
}
optimizeNodes() {
var _a, _b;
super.optimizeNodes();
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
return this;
}
optimizeNames(names, constants) {
var _a, _b;
super.optimizeNames(names, constants);
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
return this;
}
get names() {
const names = super.names;
if (this.catch)
addNames(names, this.catch.names);
if (this.finally)
addNames(names, this.finally.names);
return names;
}
}
class Catch extends BlockNode {
constructor(error) {
super();
this.error = error;
}
render(opts) {
return `catch(${this.error})` + super.render(opts);
}
}
Catch.kind = "catch";
class Finally extends BlockNode {
render(opts) {
return "finally" + super.render(opts);
}
}
Finally.kind = "finally";
class CodeGen {
constructor(extScope, opts = {}) {
this._values = {};
this._blockStarts = [];
this._constants = {};
this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
this._extScope = extScope;
this._scope = new scope_1.Scope({ parent: extScope });
this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
// returns unique name in the internal scope
name(prefix) {
return this._scope.name(prefix);
}
// reserves unique name in the external scope
scopeName(prefix) {
return this._extScope.name(prefix);
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName, value) {
const name = this._extScope.value(prefixOrName, value);
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
vs.add(name);
return name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
const name = this._scope.toName(nameOrPrefix);
if (rhs !== undefined && constant)
this._constants[name.str] = rhs;
this._leafNode(new Def(varKind, name, rhs));
return name;
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
// `var` declaration with optional assignment
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
// assignment code
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
// `+=` code
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
// appends passed SafeExpr to code or executes Block
code(c) {
if (typeof c == "function")
c();
else if (c !== code_1.nil)
this._leafNode(new AnyCode(c));
return this;
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues) {
const code = ["{"];
for (const [key, value] of keyValues) {
if (code.length > 1)
code.push(",");
code.push(key);
if (key !== value || this.opts.es5) {
code.push(":");
(0, code_1.addCodeArg)(code, value);
}
}
code.push("}");
return new code_1._Code(code);
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition, thenBody, elseBody) {
this._blockNode(new If(condition));
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf();
}
else if (thenBody) {
this.code(thenBody).endIf();
}
else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body');
}
return this;
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition) {
return this._elseNode(new If(condition));
}
// `else` clause - only valid after `if` or `else if` clauses
else() {
return this._elseNode(new Else());
}
// end `if` statement (needed if gen.if was used only with condition)
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
this._blockNode(node);
if (forBody)
this.code(forBody).endFor();
return this;
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
// `for` statement for a range of values
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
const name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
this.var(name, (0, code_1._) `${arr}[${i}]`);
forBody(name);
});
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
}
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
// end `for` loop
endFor() {
return this._endBlockNode(For);
}
// `label` statement
label(label) {
return this._leafNode(new Label(label));
}
// `break` statement
break(label) {
return this._leafNode(new Break(label));
}
// `return` statement
return(value) {
const node = new Return();
this._blockNode(node);
this.code(value);
if (node.nodes.length !== 1)
throw new Error('CodeGen: "return" should have one node');
return this._endBlockNode(Return);
}
// `try` statement
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode)
throw new Error('CodeGen: "try" without "catch" and "finally"');
const node = new Try();
this._blockNode(node);
this.code(tryBody);
if (catchCode) {
const error = this.name("e");
this._currNode = node.catch = new Catch(error);
catchCode(error);
}
if (finallyCode) {
this._currNode = node.finally = new Finally();
this.code(finallyCode);
}
return this._endBlockNode(Catch, Finally);
}
// `throw` statement
throw(error) {
return this._leafNode(new Throw(error));
}
// start self-balancing block
block(body, nodeCount) {
this._blockStarts.push(this._nodes.length);
if (body)
this.code(body).endBlock(nodeCount);
return this;
}
// end the current self-balancing block
endBlock(nodeCount) {
const len = this._blockStarts.pop();
if (len === undefined)
throw new Error("CodeGen: not in self-balancing block");
const toClose = this._nodes.length - len;
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
}
this._nodes.length = len;
return this;
}
// `function` heading (or definition if funcBody is passed)
func(name, args = code_1.nil, async, funcBody) {
this._blockNode(new Func(name, args, async));
if (funcBody)
this.code(funcBody).endFunc();
return this;
}
// end function definition
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
while (n-- > 0) {
this._root.optimizeNodes();
this._root.optimizeNames(this._root.names, this._constants);
}
}
_leafNode(node) {
this._currNode.nodes.push(node);
return this;
}
_blockNode(node) {
this._currNode.nodes.push(node);
this._nodes.push(node);
}
_endBlockNode(N1, N2) {
const n = this._currNode;
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop();
return this;
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
const n = this._currNode;
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"');
}
this._currNode = n.else = node;
return this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
const ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
const ns = this._nodes;
ns[ns.length - 1] = node;
}
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) + (from[n] || 0);
return names;
}
function addExprNames(names, from) {
return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
if (expr instanceof code_1.Name)
return replaceName(expr);
if (!canOptimize(expr))
return expr;
return new code_1._Code(expr._items.reduce((items, c) => {
if (c instanceof code_1.Name)
c = replaceName(c);
if (c instanceof code_1._Code)
items.push(...c._items);
else
items.push(c);
return items;
}, []));
function replaceName(n) {
const c = constants[n.str];
if (c === undefined || names[n.str] !== 1)
return n;
delete names[n.str];
return c;
}
function canOptimize(e) {
return (e instanceof code_1._Code &&
e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
}
}
function subtractNames(names, from) {
for (const n in from)
names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 20217:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = __nccwpck_require__(82514);
class ValueError extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`);
this.value = name.value;
}
}
var UsedValueState;
(function (UsedValueState) {
UsedValueState[UsedValueState["Started"] = 0] = "Started";
UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
const: new code_1.Name("const"),
let: new code_1.Name("let"),
var: new code_1.Name("var"),
};
class Scope {
constructor({ prefixes, parent } = {}) {
this._names = {};
this._prefixes = prefixes;
this._parent = parent;
}
toName(nameOrPrefix) {
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
}
name(prefix) {
return new code_1.Name(this._newName(prefix));
}
_newName(prefix) {
const ng = this._names[prefix] || this._nameGroup(prefix);
return `${prefix}${ng.index++}`;
}
_nameGroup(prefix) {
var _a, _b;
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
}
return (this._names[prefix] = { prefix, index: 0 });
}
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
constructor(prefix, nameStr) {
super(nameStr);
this.prefix = prefix;
}
setValue(value, { property, itemIndex }) {
this.value = value;
this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
}
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
constructor(opts) {
super(opts);
this._values = {};
this._scope = opts.scope;
this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
}
get() {
return this._scope;
}
name(prefix) {
return new ValueScopeName(prefix, this._newName(prefix));
}
value(nameOrPrefix, value) {
var _a;
if (value.ref === undefined)
throw new Error("CodeGen: ref must be passed in value");
const name = this.toName(nameOrPrefix);
const { prefix } = name;
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
let vs = this._values[prefix];
if (vs) {
const _name = vs.get(valueKey);
if (_name)
return _name;
}
else {
vs = this._values[prefix] = new Map();
}
vs.set(valueKey, name);
const s = this._scope[prefix] || (this._scope[prefix] = []);
const itemIndex = s.length;
s[itemIndex] = value.ref;
name.setValue(value, { property: prefix, itemIndex });
return name;
}
getValue(prefix, keyOrRef) {
const vs = this._values[prefix];
if (!vs)
return;
return vs.get(keyOrRef);
}
scopeRefs(scopeName, values = this._values) {
return this._reduceValues(values, (name) => {
if (name.scopePath === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return (0, code_1._) `${scopeName}${name.scopePath}`;
});
}
scopeCode(values = this._values, usedValues, getCode) {
return this._reduceValues(values, (name) => {
if (name.value === undefined)
throw new Error(`CodeGen: name "${name}" has no value`);
return name.value.code;
}, usedValues, getCode);
}
_reduceValues(values, valueCode, usedValues = {}, getCode) {
let code = code_1.nil;
for (const prefix in values) {
const vs = values[prefix];
if (!vs)
continue;
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
vs.forEach((name) => {
if (nameSet.has(name))
return;
nameSet.set(name, UsedValueState.Started);
let c = valueCode(name);
if (c) {
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
}
else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
code = (0, code_1._) `${code}${c}${this.opts._n}`;
}
else {
throw new ValueError(name);
}
nameSet.set(name, UsedValueState.Completed);
});
}
return code;
}
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map
/***/ }),
/***/ 30084:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const names_1 = __nccwpck_require__(20717);
exports.keywordError = {
message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
message: ({ keyword, schemaType }) => schemaType
? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
: (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
addError(gen, errObj);
}
else {
returnErrors(it, (0, codegen_1._) `[${errObj}]`);
}
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
addError(gen, errObj);
if (!(compositeRule || allErrors)) {
returnErrors(it, names_1.default.vErrors);
}
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
gen.assign(names_1.default.errors, errsCount);
gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
/* istanbul ignore if */
if (errsCount === undefined)
throw new Error("ajv implementation error");
const err = gen.name("err");
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
if (it.opts.verbose) {
gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
gen.assign((0, codegen_1._) `${err}.data`, data);
}
});
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
const err = gen.const("err", errObj);
gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
const { gen, validateName, schemaEnv } = it;
if (schemaEnv.$async) {
gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
gen.return(false);
}
}
const E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
params: new codegen_1.Name("params"),
propertyName: new codegen_1.Name("propertyName"),
message: new codegen_1.Name("message"),
schema: new codegen_1.Name("schema"),
parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
const { createErrors } = cxt.it;
if (createErrors === false)
return (0, codegen_1._) `{}`;
return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
const { gen, it } = cxt;
const keyValues = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
];
extraErrorProps(cxt, error, keyValues);
return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
const instPath = instancePath
? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
: errorPath;
return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
if (schemaPath) {
schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
}
return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
const { keyword, data, schemaValue, it } = cxt;
const { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
}
if (opts.verbose) {
keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
}
if (propertyName)
keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ 56501:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = __nccwpck_require__(56771);
const validation_error_1 = __nccwpck_require__(19975);
const names_1 = __nccwpck_require__(20717);
const resolve_1 = __nccwpck_require__(37324);
const util_1 = __nccwpck_require__(28311);
const validate_1 = __nccwpck_require__(74504);
class SchemaEnv {
constructor(env) {
var _a;
this.refs = {};
this.dynamicAnchors = {};
let schema;
if (typeof env.schema == "object")
schema = env.schema;
this.schema = env.schema;
this.schemaId = env.schemaId;
this.root = env.root || this;
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
this.schemaPath = env.schemaPath;
this.localRefs = env.localRefs;
this.meta = env.meta;
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
this.refs = {};
}
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
// TODO refactor - remove compilations
const _sch = getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
let _ValidationError;
if (sch.$async) {
_ValidationError = gen.scopeValue("Error", {
ref: validation_error_1.default,
code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
});
}
const validateName = gen.scopeName("validate");
sch.validateName = validateName;
const schemaCxt = {
gen,
allErrors: this.opts.allErrors,
data: names_1.default.data,
parentData: names_1.default.parentData,
parentDataProperty: names_1.default.parentDataProperty,
dataNames: [names_1.default.data],
dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
dataLevel: 0,
dataTypes: [],
definedProperties: new Set(),
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
: { ref: sch.schema }),
validateName,
ValidationError: _ValidationError,
schema: sch.schema,
schemaEnv: sch,
rootId,
baseId: sch.baseId || rootId,
schemaPath: codegen_1.nil,
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
errorPath: (0, codegen_1._) `""`,
opts: this.opts,
self: this,
};
let sourceCode;
try {
this._compilations.add(sch);
(0, validate_1.validateFunctionCode)(schemaCxt);
gen.optimize(this.opts.code.optimize);
// gen.optimize(1)
const validateCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
if (this.opts.code.process)
sourceCode = this.opts.code.process(sourceCode, sch);
// console.log("\n\n\n *** \n", sourceCode)
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
const validate = makeValidate(this, this.scope.get());
this.scope.value(validateName, { ref: validate });
validate.errors = null;
validate.schema = sch.schema;
validate.schemaEnv = sch;
if (sch.$async)
validate.$async = true;
if (this.opts.code.source === true) {
validate.source = { validateName, validateCode, scopeValues: gen._values };
}
if (this.opts.unevaluated) {
const { props, items } = schemaCxt;
validate.evaluated = {
props: props instanceof codegen_1.Name ? undefined : props,
items: items instanceof codegen_1.Name ? undefined : items,
dynamicProps: props instanceof codegen_1.Name,
dynamicItems: items instanceof codegen_1.Name,
};
if (validate.source)
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
}
sch.validate = validate;
return sch;
}
catch (e) {
delete sch.validate;
delete sch.validateName;
if (sourceCode)
this.logger.error("Error compiling schema, function code:", sourceCode);
// console.log("\n\n\n *** \n", sourceCode, this.opts)
throw e;
}
finally {
this._compilations.delete(sch);
}
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
var _a;
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
const schOrFunc = root.refs[ref];
if (schOrFunc)
return schOrFunc;
let _sch = resolve.call(this, root, ref);
if (_sch === undefined) {
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
const { schemaId } = this.opts;
if (schema)
_sch = new SchemaEnv({ schema, schemaId, root, baseId });
}
if (_sch === undefined)
return;
return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
return sch.schema;
return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
for (const sch of this._compilations) {
if (sameSchemaEnv(sch, schEnv))
return sch;
}
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
let sch;
while (typeof (sch = this.refs[ref]) == "string")
ref = sch;
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
const p = this.opts.uriResolver.parse(ref);
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root);
}
const id = (0, resolve_1.normalizeId)(refPath);
const schOrRef = this.refs[id] || this.schemas[id];
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef);
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
return;
return getJsonPointer.call(this, p, sch);
}
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
return;
if (!schOrRef.validate)
compileSchema.call(this, schOrRef);
if (id === (0, resolve_1.normalizeId)(ref)) {
const { schema } = schOrRef;
const { schemaId } = this.opts;
const schId = schema[schemaId];
if (schId)
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
return new SchemaEnv({ schema, schemaId, root, baseId });
}
return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
"properties",
"patternProperties",
"enum",
"dependencies",
"definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
var _a;
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
return;
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean")
return;
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
if (partSchema === undefined)
return;
schema = partSchema;
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId];
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
}
}
let env;
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
env = resolveSchema.call(this, root, $ref);
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const { schemaId } = this.opts;
env = env || new SchemaEnv({ schema, schemaId, root, baseId });
if (env.schema !== env.root.schema)
return env;
return undefined;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 20717:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const names = {
// validation function arguments
data: new codegen_1.Name("data"), // data passed to validation function
// args passed from referencing schema
valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
// function scoped variables
vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
errors: new codegen_1.Name("errors"), // counter of validation errors
this: new codegen_1.Name("this"),
// "globals"
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
// JTD serialize/parse name for JSON string and position
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart"),
};
exports["default"] = names;
//# sourceMappingURL=names.js.map
/***/ }),
/***/ 43857:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const resolve_1 = __nccwpck_require__(37324);
class MissingRefError extends Error {
constructor(resolver, baseId, ref, msg) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
}
}
exports["default"] = MissingRefError;
//# sourceMappingURL=ref_error.js.map
/***/ }),
/***/ 37324:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = __nccwpck_require__(28311);
const equal = __nccwpck_require__(28206);
const traverse = __nccwpck_require__(67786);
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
"type",
"format",
"pattern",
"maxLength",
"minLength",
"maxProperties",
"minProperties",
"maxItems",
"minItems",
"maximum",
"minimum",
"uniqueItems",
"multipleOf",
"required",
"enum",
"const",
]);
function inlineRef(schema, limit = true) {
if (typeof schema == "boolean")
return true;
if (limit === true)
return !hasRef(schema);
if (!limit)
return false;
return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
"$ref",
"$recursiveRef",
"$recursiveAnchor",
"$dynamicRef",
"$dynamicAnchor",
]);
function hasRef(schema) {
for (const key in schema) {
if (REF_KEYWORDS.has(key))
return true;
const sch = schema[key];
if (Array.isArray(sch) && sch.some(hasRef))
return true;
if (typeof sch == "object" && hasRef(sch))
return true;
}
return false;
}
function countKeys(schema) {
let count = 0;
for (const key in schema) {
if (key === "$ref")
return Infinity;
count++;
if (SIMPLE_INLINED.has(key))
continue;
if (typeof schema[key] == "object") {
(0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
}
if (count === Infinity)
return Infinity;
}
return count;
}
function getFullPath(resolver, id = "", normalize) {
if (normalize !== false)
id = normalizeId(id);
const p = resolver.parse(id);
return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
const serialized = resolver.serialize(p);
return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
id = normalizeId(id);
return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
if (typeof schema == "boolean")
return {};
const { schemaId, uriResolver } = this.opts;
const schId = normalizeId(schema[schemaId] || baseId);
const baseIds = { "": schId };
const pathPrefix = getFullPath(uriResolver, schId, false);
const localRefs = {};
const schemaRefs = new Set();
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined)
return;
const fullPath = pathPrefix + jsonPtr;
let innerBaseId = baseIds[parentJsonPtr];
if (typeof sch[schemaId] == "string")
innerBaseId = addRef.call(this, sch[schemaId]);
addAnchor.call(this, sch.$anchor);
addAnchor.call(this, sch.$dynamicAnchor);
baseIds[jsonPtr] = innerBaseId;
function addRef(ref) {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve;
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
if (schemaRefs.has(ref))
throw ambiguos(ref);
schemaRefs.add(ref);
let schOrRef = this.refs[ref];
if (typeof schOrRef == "string")
schOrRef = this.refs[schOrRef];
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref);
}
else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref);
localRefs[ref] = sch;
}
else {
this.refs[ref] = fullPath;
}
}
return ref;
}
function addAnchor(anchor) {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor))
throw new Error(`invalid anchor "${anchor}"`);
addRef.call(this, `#${anchor}`);
}
}
});
return localRefs;
function checkAmbiguosRef(sch1, sch2, ref) {
if (sch2 !== undefined && !equal(sch1, sch2))
throw ambiguos(ref);
}
function ambiguos(ref) {
return new Error(`reference "${ref}" resolves to more than one schema`);
}
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map
/***/ }),
/***/ 33098:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
const groups = {
number: { type: "number", rules: [] },
string: { type: "string", rules: [] },
array: { type: "array", rules: [] },
object: { type: "object", rules: [] },
};
return {
types: { ...groups, integer: true, boolean: true, null: true },
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
post: { rules: [] },
all: {},
keywords: {},
};
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map
/***/ }),
/***/ 28311:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = __nccwpck_require__(56771);
const code_1 = __nccwpck_require__(82514);
// TODO refactor to use Set
function toHash(arr) {
const hash = {};
for (const item of arr)
hash[item] = true;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
if (typeof schema == "boolean")
return schema;
if (Object.keys(schema).length === 0)
return true;
checkUnknownRules(it, schema);
return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
const { opts, self } = it;
if (!opts.strictSchema)
return;
if (typeof schema === "boolean")
return;
const rules = self.RULES.keywords;
for (const key in schema) {
if (!rules[key])
checkStrictMode(it, `unknown keyword: "${key}"`);
}
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (rules[key])
return true;
return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (key !== "$ref" && RULES.all[key])
return true;
return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean")
return schema;
if (typeof schema == "string")
return (0, codegen_1._) `${schema}`;
}
return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
if (typeof str == "number")
return `${str}`;
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
if (Array.isArray(xs)) {
for (const x of xs)
f(x);
}
else {
f(xs);
}
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
return (gen, from, to, toName) => {
const res = to === undefined
? from
: to instanceof codegen_1.Name
? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
: from instanceof codegen_1.Name
? (mergeToName(gen, to, from), from)
: mergeValues(from, to);
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
};
}
exports.mergeEvaluated = {
props: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
}),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
if (from === true) {
gen.assign(to, true);
}
else {
gen.assign(to, (0, codegen_1._) `${to} || {}`);
setEvaluated(gen, to, from);
}
}),
mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
resultToName: evaluatedPropsToName,
}),
items: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
resultToName: (gen, items) => gen.var("items", items),
}),
};
function evaluatedPropsToName(gen, ps) {
if (ps === true)
return gen.var("props", true);
const props = gen.var("props", (0, codegen_1._) `{}`);
if (ps !== undefined)
setEvaluated(gen, props, ps);
return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
});
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
Type[Type["Num"] = 0] = "Num";
Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
// let path
if (dataProp instanceof codegen_1.Name) {
const isNumber = dataPropType === Type.Num;
return jsPropertySyntax
? isNumber
? (0, codegen_1._) `"[" + ${dataProp} + "]"`
: (0, codegen_1._) `"['" + ${dataProp} + "']"`
: isNumber
? (0, codegen_1._) `"/" + ${dataProp}`
: (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
}
return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
if (!mode)
return;
msg = `strict mode: ${msg}`;
if (mode === true)
throw new Error(msg);
it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map
/***/ }),
/***/ 99368:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
const group = self.RULES.types[type];
return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
var _a;
return (schema[rule.keyword] !== undefined ||
((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map
/***/ }),
/***/ 3390:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = __nccwpck_require__(30084);
const codegen_1 = __nccwpck_require__(56771);
const names_1 = __nccwpck_require__(20717);
const boolError = {
message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
const { gen, schema, validateName } = it;
if (schema === false) {
falseSchemaError(it, false);
}
else if (typeof schema == "object" && schema.$async === true) {
gen.return(names_1.default.data);
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, null);
gen.return(true);
}
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
const { gen, schema } = it;
if (schema === false) {
gen.var(valid, false); // TODO var
falseSchemaError(it);
}
else {
gen.var(valid, true); // TODO var
}
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
const { gen, data } = it;
// TODO maybe some other interface should be used for non-keyword validation errors...
const cxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it,
};
(0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map
/***/ }),
/***/ 79954:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = __nccwpck_require__(33098);
const applicability_1 = __nccwpck_require__(99368);
const errors_1 = __nccwpck_require__(30084);
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
var DataType;
(function (DataType) {
DataType[DataType["Correct"] = 0] = "Correct";
DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
const types = getJSONTypes(schema.type);
const hasNull = types.includes("null");
if (hasNull) {
if (schema.nullable === false)
throw new Error("type: null contradicts nullable: false");
}
else {
if (!types.length && schema.nullable !== undefined) {
throw new Error('"nullable" cannot be used without "type"');
}
if (schema.nullable === true)
types.push("null");
}
return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
if (types.every(rules_1.isJSONType))
return types;
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
const { gen, data, opts } = it;
const coerceTo = coerceToTypes(types, opts.coerceTypes);
const checkTypes = types.length > 0 &&
!(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
gen.if(wrongType, () => {
if (coerceTo.length)
coerceData(it, types, coerceTo);
else
reportTypeError(it);
});
}
return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
return coerceTypes
? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
: [];
}
function coerceData(it, types, coerceTo) {
const { gen, data, opts } = it;
const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
if (opts.coerceTypes === "array") {
gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
.assign(data, (0, codegen_1._) `${data}[0]`)
.assign(dataType, (0, codegen_1._) `typeof ${data}`)
.if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
}
gen.if((0, codegen_1._) `${coerced} !== undefined`);
for (const t of coerceTo) {
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
coerceSpecificType(t);
}
}
gen.else();
reportTypeError(it);
gen.endIf();
gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
gen.assign(data, coerced);
assignParentData(it, coerced);
});
function coerceSpecificType(t) {
switch (t) {
case "string":
gen
.elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
.assign(coerced, (0, codegen_1._) `"" + ${data}`)
.elseIf((0, codegen_1._) `${data} === null`)
.assign(coerced, (0, codegen_1._) `""`);
return;
case "number":
gen
.elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "integer":
gen
.elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
.assign(coerced, (0, codegen_1._) `+${data}`);
return;
case "boolean":
gen
.elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
.assign(coerced, false)
.elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
.assign(coerced, true);
return;
case "null":
gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
gen.assign(coerced, null);
return;
case "array":
gen
.elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
|| ${dataType} === "boolean" || ${data} === null`)
.assign(coerced, (0, codegen_1._) `[${data}]`);
}
}
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
// TODO use gen.property
gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
let cond;
switch (dataType) {
case "null":
return (0, codegen_1._) `${data} ${EQ} null`;
case "array":
cond = (0, codegen_1._) `Array.isArray(${data})`;
break;
case "object":
cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
break;
case "integer":
cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
break;
case "number":
cond = numCond();
break;
default:
return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
}
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
function numCond(_cond = codegen_1.nil) {
return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
}
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
if (dataTypes.length === 1) {
return checkDataType(dataTypes[0], data, strictNums, correct);
}
let cond;
const types = (0, util_1.toHash)(dataTypes);
if (types.array && types.object) {
const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
delete types.null;
delete types.array;
delete types.object;
}
else {
cond = codegen_1.nil;
}
if (types.number)
delete types.integer;
for (const t in types)
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
message: ({ schema }) => `must be ${schema}`,
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
const cxt = getTypeErrorContext(it);
(0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
const { gen, data, schema } = it;
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
return {
gen,
keyword: "type",
data,
schema: schema.type,
schemaCode,
schemaValue: schemaCode,
parentSchema: schema,
params: {},
it,
};
}
//# sourceMappingURL=dataType.js.map
/***/ }),
/***/ 47742:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.assignDefaults = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
function assignDefaults(it, ty) {
const { properties, items } = it.schema;
if (ty === "object" && properties) {
for (const key in properties) {
assignDefault(it, key, properties[key].default);
}
}
else if (ty === "array" && Array.isArray(items)) {
items.forEach((sch, i) => assignDefault(it, i, sch.default));
}
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
const { gen, compositeRule, data, opts } = it;
if (defaultValue === undefined)
return;
const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
if (compositeRule) {
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
return;
}
let condition = (0, codegen_1._) `${childData} === undefined`;
if (opts.useDefaults === "empty") {
condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
}
// `${childData} === undefined` +
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map
/***/ }),
/***/ 74504:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = __nccwpck_require__(3390);
const dataType_1 = __nccwpck_require__(79954);
const applicability_1 = __nccwpck_require__(99368);
const dataType_2 = __nccwpck_require__(79954);
const defaults_1 = __nccwpck_require__(47742);
const keyword_1 = __nccwpck_require__(11003);
const subschema_1 = __nccwpck_require__(47923);
const codegen_1 = __nccwpck_require__(56771);
const names_1 = __nccwpck_require__(20717);
const resolve_1 = __nccwpck_require__(37324);
const util_1 = __nccwpck_require__(28311);
const errors_1 = __nccwpck_require__(30084);
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
topSchemaObjCode(it);
return;
}
}
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
if (opts.code.es5) {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
destructureValCxtES5(gen, opts);
gen.code(body);
});
}
else {
gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
}
}
function destructureValCxt(opts) {
return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
gen.if(names_1.default.valCxt, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
}, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
gen.var(names_1.default.rootData, names_1.default.data);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
});
}
function topSchemaObjCode(it) {
const { schema, opts, gen } = it;
validateFunction(it, () => {
if (opts.$comment && schema.$comment)
commentKeyword(it);
checkNoDefault(it);
gen.let(names_1.default.vErrors, null);
gen.let(names_1.default.errors, 0);
if (opts.unevaluated)
resetEvaluated(it);
typeAndKeywords(it);
returnResults(it);
});
return;
}
function resetEvaluated(it) {
// TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
const { gen, validateName } = it;
it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
const schId = typeof schema == "object" && schema[opts.schemaId];
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid);
return;
}
}
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (self.RULES.all[key])
return true;
return false;
}
function isSchemaObj(it) {
return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
const { schema, gen, opts } = it;
if (opts.$comment && schema.$comment)
commentKeyword(it);
updateContext(it);
checkAsyncSchema(it);
const errsCount = gen.const("_errs", names_1.default.errors);
typeAndKeywords(it, errsCount);
// TODO var
gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
(0, util_1.checkUnknownRules)(it);
checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
if (it.opts.jtd)
return schemaKeywords(it, [], false, errsCount);
const types = (0, dataType_1.getSchemaTypes)(it.schema);
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
const { schema, errSchemaPath, opts, self } = it;
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
}
}
function checkNoDefault(it) {
const { schema, opts } = it;
if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
}
}
function updateContext(it) {
const schId = it.schema[it.opts.schemaId];
if (schId)
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
if (it.schema.$async && !it.schemaEnv.$async)
throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
const msg = schema.$comment;
if (opts.$comment === true) {
gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
}
else if (typeof opts.$comment == "function") {
const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
}
}
function returnResults(it) {
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
if (schemaEnv.$async) {
// TODO assign unevaluated
gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
}
else {
gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
if (opts.unevaluated)
assignEvaluated(it);
gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
}
}
function assignEvaluated({ gen, evaluated, props, items }) {
if (props instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.props`, props);
if (items instanceof codegen_1.Name)
gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
const { gen, schema, data, allErrors, opts, self } = it;
const { RULES } = self;
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
return;
}
if (!opts.jtd)
checkStrictTypes(it, types);
gen.block(() => {
for (const group of RULES.rules)
groupKeywords(group);
groupKeywords(RULES.post);
});
function groupKeywords(group) {
if (!(0, applicability_1.shouldUseGroup)(schema, group))
return;
if (group.type) {
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
iterateKeywords(it, group);
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else();
(0, dataType_2.reportTypeError)(it);
}
gen.endIf();
}
else {
iterateKeywords(it, group);
}
// TODO make it "ok" call?
if (!allErrors)
gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
}
}
function iterateKeywords(it, group) {
const { gen, schema, opts: { useDefaults }, } = it;
if (useDefaults)
(0, defaults_1.assignDefaults)(it, group.type);
gen.block(() => {
for (const rule of group.rules) {
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type);
}
}
});
}
function checkStrictTypes(it, types) {
if (it.schemaEnv.meta || !it.opts.strictTypes)
return;
checkContextTypes(it, types);
if (!it.opts.allowUnionTypes)
checkMultipleTypes(it, types);
checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
if (!types.length)
return;
if (!it.dataTypes.length) {
it.dataTypes = types;
return;
}
types.forEach((t) => {
if (!includesType(it.dataTypes, t)) {
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
}
});
narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
}
}
function checkKeywordTypes(it, ts) {
const rules = it.self.RULES.all;
for (const keyword in rules) {
const rule = rules[keyword];
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
const { type } = rule.definition;
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
}
}
}
}
function hasApplicableType(schTs, kwdT) {
return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
const ts = [];
for (const t of it.dataTypes) {
if (includesType(withTypes, t))
ts.push(t);
else if (withTypes.includes("integer") && t === "number")
ts.push("integer");
}
it.dataTypes = ts;
}
function strictTypesError(it, msg) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
msg += ` at "${schemaPath}" (strictTypes)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
constructor(it, def, keyword) {
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
this.gen = it.gen;
this.allErrors = it.allErrors;
this.keyword = keyword;
this.data = it.data;
this.schema = it.schema[keyword];
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
this.schemaType = def.schemaType;
this.parentSchema = it.schema;
this.params = {};
this.it = it;
this.def = def;
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
}
else {
this.schemaCode = this.schemaValue;
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", names_1.default.errors);
}
}
result(condition, successAction, failAction) {
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
}
failResult(condition, successAction, failAction) {
this.gen.if(condition);
if (failAction)
failAction();
else
this.error();
if (successAction) {
this.gen.else();
successAction();
if (this.allErrors)
this.gen.endIf();
}
else {
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
}
pass(condition, failAction) {
this.failResult((0, codegen_1.not)(condition), undefined, failAction);
}
fail(condition) {
if (condition === undefined) {
this.error();
if (!this.allErrors)
this.gen.if(false); // this branch will be removed by gen.optimize
return;
}
this.gen.if(condition);
this.error();
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
fail$data(condition) {
if (!this.$data)
return this.fail(condition);
const { schemaCode } = this;
this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
}
error(append, errorParams, errorPaths) {
if (errorParams) {
this.setParams(errorParams);
this._error(append, errorPaths);
this.setParams({});
return;
}
this._error(append, errorPaths);
}
_error(append, errorPaths) {
;
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
}
$dataError() {
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
}
reset() {
if (this.errsCount === undefined)
throw new Error('add "trackErrors" to keyword definition');
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
}
ok(cond) {
if (!this.allErrors)
this.gen.if(cond);
}
setParams(obj, assign) {
if (assign)
Object.assign(this.params, obj);
else
this.params = obj;
}
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
this.gen.block(() => {
this.check$data(valid, $dataValid);
codeBlock();
});
}
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
if (!this.$data)
return;
const { gen, schemaCode, schemaType, def } = this;
gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
if (valid !== codegen_1.nil)
gen.assign(valid, true);
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data());
this.$dataError();
if (valid !== codegen_1.nil)
gen.assign(valid, false);
}
gen.else();
}
invalid$data() {
const { gen, schemaCode, schemaType, def, it } = this;
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
function wrong$DataType() {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof codegen_1.Name))
throw new Error("ajv implementation error");
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
}
return codegen_1.nil;
}
function invalid$DataSchema() {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
}
return codegen_1.nil;
}
}
subschema(appl, valid) {
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
(0, subschema_1.extendSubschemaMode)(subschema, appl);
const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
subschemaCode(nextContext, valid);
return nextContext;
}
mergeEvaluated(schemaCxt, toName) {
const { it, gen } = this;
if (!it.opts.unevaluated)
return;
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
}
}
mergeValidEvaluated(schemaCxt, valid) {
const { it, gen } = this;
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
return true;
}
}
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
const cxt = new KeywordCxt(it, def, keyword);
if ("code" in def) {
def.code(cxt, ruleType);
}
else if (cxt.$data && def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
else if ("macro" in def) {
(0, keyword_1.macroKeywordCode)(cxt, def);
}
else if (def.compile || def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
let jsonPointer;
let data;
if ($data === "")
return names_1.default.rootData;
if ($data[0] === "/") {
if (!JSON_POINTER.test($data))
throw new Error(`Invalid JSON-pointer: ${$data}`);
jsonPointer = $data;
data = names_1.default.rootData;
}
else {
const matches = RELATIVE_JSON_POINTER.exec($data);
if (!matches)
throw new Error(`Invalid JSON-pointer: ${$data}`);
const up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer === "#") {
if (up >= dataLevel)
throw new Error(errorMsg("property/index", up));
return dataPathArr[dataLevel - up];
}
if (up > dataLevel)
throw new Error(errorMsg("data", up));
data = dataNames[dataLevel - up];
if (!jsonPointer)
return data;
}
let expr = data;
const segments = jsonPointer.split("/");
for (const segment of segments) {
if (segment) {
data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
expr = (0, codegen_1._) `${expr} && ${data}`;
}
}
return expr;
function errorMsg(pointerType, up) {
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
}
}
exports.getData = getData;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 11003:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = __nccwpck_require__(56771);
const names_1 = __nccwpck_require__(20717);
const code_1 = __nccwpck_require__(22975);
const errors_1 = __nccwpck_require__(30084);
function macroKeywordCode(cxt, def) {
const { gen, keyword, schema, parentSchema, it } = cxt;
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
const schemaRef = useKeyword(gen, keyword, macroSchema);
if (it.opts.validateSchema !== false)
it.self.validateSchema(macroSchema, true);
const valid = gen.name("valid");
cxt.subschema({
schema: macroSchema,
schemaPath: codegen_1.nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true,
}, valid);
cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
var _a;
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
checkAsyncKeyword(it, def);
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
const validateRef = useKeyword(gen, keyword, validate);
const valid = gen.let("valid");
cxt.block$data(valid, validateKeyword);
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
function validateKeyword() {
if (def.errors === false) {
assignValid();
if (def.modifying)
modifyData(cxt);
reportErrs(() => cxt.error());
}
else {
const ruleErrs = def.async ? validateAsync() : validateSync();
if (def.modifying)
modifyData(cxt);
reportErrs(() => addErrs(cxt, ruleErrs));
}
}
function validateAsync() {
const ruleErrs = gen.let("ruleErrs", null);
gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
return ruleErrs;
}
function validateSync() {
const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
gen.assign(validateErrs, null);
assignValid(codegen_1.nil);
return validateErrs;
}
function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
const passSchema = !(("compile" in def && !$data) || def.schema === false);
gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
}
function reportErrs(errors) {
var _a;
gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
}
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
const { gen, data, it } = cxt;
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
const { gen } = cxt;
gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
gen
.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
(0, errors_1.extendErrors)(cxt);
}, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
if (def.async && !schemaEnv.$async)
throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
if (result === undefined)
throw new Error(`keyword "${keyword}" failed to compile`);
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
// TODO add tests
return (!schemaType.length ||
schemaType.some((st) => st === "array"
? Array.isArray(schema)
: st === "object"
? schema && typeof schema == "object" && !Array.isArray(schema)
: typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error");
}
const deps = def.dependencies;
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword]);
if (!valid) {
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors);
if (opts.validateSchema === "log")
self.logger.error(msg);
else
throw new Error(msg);
}
}
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map
/***/ }),
/***/ 47923:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
if (keyword !== undefined && schema !== undefined) {
throw new Error('both "keyword" and "schema" passed, only one allowed');
}
if (keyword !== undefined) {
const sch = it.schema[keyword];
return schemaProp === undefined
? {
schema: sch,
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
}
: {
schema: sch[schemaProp],
schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
};
}
if (schema !== undefined) {
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath,
};
}
throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed');
}
const { gen } = it;
if (dataProp !== undefined) {
const { errorPath, dataPathArr, opts } = it;
const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
dataContextProps(nextData);
subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
}
if (data !== undefined) {
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
dataContextProps(nextData);
if (propertyName !== undefined)
subschema.propertyName = propertyName;
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes)
subschema.dataTypes = dataTypes;
function dataContextProps(_nextData) {
subschema.data = _nextData;
subschema.dataLevel = it.dataLevel + 1;
subschema.dataTypes = [];
it.definedProperties = new Set();
subschema.parentData = it.data;
subschema.dataNames = [...it.dataNames, _nextData];
}
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
if (compositeRule !== undefined)
subschema.compositeRule = compositeRule;
if (createErrors !== undefined)
subschema.createErrors = createErrors;
if (allErrors !== undefined)
subschema.allErrors = allErrors;
subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map
/***/ }),
/***/ 10641:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = __nccwpck_require__(74504);
Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }));
var codegen_1 = __nccwpck_require__(56771);
Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } }));
Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } }));
Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } }));
Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } }));
Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } }));
Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }));
const validation_error_1 = __nccwpck_require__(19975);
const ref_error_1 = __nccwpck_require__(43857);
const rules_1 = __nccwpck_require__(33098);
const compile_1 = __nccwpck_require__(56501);
const codegen_2 = __nccwpck_require__(56771);
const resolve_1 = __nccwpck_require__(37324);
const dataType_1 = __nccwpck_require__(79954);
const util_1 = __nccwpck_require__(28311);
const $dataRefSchema = __nccwpck_require__(26338);
const uri_1 = __nccwpck_require__(16546);
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
"validate",
"serialize",
"parse",
"wrapper",
"root",
"schema",
"keyword",
"pattern",
"formats",
"validate$data",
"func",
"obj",
"Error",
]);
const removedOptions = {
errorDataPath: "",
format: "`validateFormats: false` can be used instead.",
nullable: '"nullable" keyword is supported by default.',
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
sourceCode: "Use option `code: {source: true}`",
strictDefaults: "It is default now, see option `strict`.",
strictKeywords: "It is default now, see option `strict`.",
uniqueItems: '"uniqueItems" keyword is always validated.',
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
cache: "Map is used as cache, schema object as key.",
serialize: "Map is used as cache, schema object as key.",
ajvErrors: "It is default now.",
};
const deprecatedOptions = {
ignoreKeywordsWithRef: "",
jsPropertySyntax: "",
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
return {
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
uriResolver: uriResolver,
};
}
class Ajv {
constructor(opts = {}) {
this.schemas = {};
this.refs = {};
this.formats = {};
this._compilations = new Set();
this._loading = {};
this._cache = new Map();
opts = this.opts = { ...opts, ...requiredOptions(opts) };
const { es5, lines } = this.opts.code;
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
this.logger = getLogger(opts.logger);
const formatOpt = opts.validateFormats;
opts.validateFormats = false;
this.RULES = (0, rules_1.getRules)();
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
this._metaOpts = getMetaSchemaOptions.call(this);
if (opts.formats)
addInitialFormats.call(this);
this._addVocabularies();
this._addDefaultMetaSchema();
if (opts.keywords)
addInitialKeywords.call(this, opts.keywords);
if (typeof opts.meta == "object")
this.addMetaSchema(opts.meta);
addInitialSchemas.call(this);
opts.validateFormats = formatOpt;
}
_addVocabularies() {
this.addKeyword("$async");
}
_addDefaultMetaSchema() {
const { $data, meta, schemaId } = this.opts;
let _dataRefSchema = $dataRefSchema;
if (schemaId === "id") {
_dataRefSchema = { ...$dataRefSchema };
_dataRefSchema.id = _dataRefSchema.$id;
delete _dataRefSchema.$id;
}
if (meta && $data)
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
}
defaultMeta() {
const { meta, schemaId } = this.opts;
return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
}
validate(schemaKeyRef, // key, ref or schema object
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
data // to be validated
) {
let v;
if (typeof schemaKeyRef == "string") {
v = this.getSchema(schemaKeyRef);
if (!v)
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
}
else {
v = this.compile(schemaKeyRef);
}
const valid = v(data);
if (!("$async" in v))
this.errors = v.errors;
return valid;
}
compile(schema, _meta) {
const sch = this._addSchema(schema, _meta);
return (sch.validate || this._compileSchemaEnv(sch));
}
compileAsync(schema, meta) {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function");
}
const { loadSchema } = this.opts;
return runCompileAsync.call(this, schema, meta);
async function runCompileAsync(_schema, _meta) {
await loadMetaSchema.call(this, _schema.$schema);
const sch = this._addSchema(_schema, _meta);
return sch.validate || _compileAsync.call(this, sch);
}
async function loadMetaSchema($ref) {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, { $ref }, true);
}
}
async function _compileAsync(sch) {
try {
return this._compileSchemaEnv(sch);
}
catch (e) {
if (!(e instanceof ref_error_1.default))
throw e;
checkLoaded.call(this, e);
await loadMissingSchema.call(this, e.missingSchema);
return _compileAsync.call(this, sch);
}
}
function checkLoaded({ missingSchema: ref, missingRef }) {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
}
}
async function loadMissingSchema(ref) {
const _schema = await _loadSchema.call(this, ref);
if (!this.refs[ref])
await loadMetaSchema.call(this, _schema.$schema);
if (!this.refs[ref])
this.addSchema(_schema, ref, meta);
}
async function _loadSchema(ref) {
const p = this._loading[ref];
if (p)
return p;
try {
return await (this._loading[ref] = loadSchema(ref));
}
finally {
delete this._loading[ref];
}
}
}
// Adds schema to the instance
addSchema(schema, // If array is passed, `key` will be ignored
key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
_meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
) {
if (Array.isArray(schema)) {
for (const sch of schema)
this.addSchema(sch, undefined, _meta, _validateSchema);
return this;
}
let id;
if (typeof schema === "object") {
const { schemaId } = this.opts;
id = schema[schemaId];
if (id !== undefined && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`);
}
}
key = (0, resolve_1.normalizeId)(key || id);
this._checkUnique(key);
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
return this;
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(schema, key, // schema key
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
) {
this.addSchema(schema, key, true, _validateSchema);
return this;
}
// Validate schema against its meta-schema
validateSchema(schema, throwOrLogError) {
if (typeof schema == "boolean")
return true;
let $schema;
$schema = schema.$schema;
if ($schema !== undefined && typeof $schema != "string") {
throw new Error("$schema must be a string");
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
if (!$schema) {
this.logger.warn("meta-schema not available");
this.errors = null;
return true;
}
const valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText();
if (this.opts.validateSchema === "log")
this.logger.error(message);
else
throw new Error(message);
}
return valid;
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema(keyRef) {
let sch;
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
keyRef = sch;
if (sch === undefined) {
const { schemaId } = this.opts;
const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
sch = compile_1.resolveSchema.call(this, root, keyRef);
if (!sch)
return;
this.refs[keyRef] = sch;
}
return (sch.validate || this._compileSchemaEnv(sch));
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef);
this._removeAllSchemas(this.refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas);
this._removeAllSchemas(this.refs);
this._cache.clear();
return this;
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef);
if (typeof sch == "object")
this._cache.delete(sch.schema);
delete this.schemas[schemaKeyRef];
delete this.refs[schemaKeyRef];
return this;
}
case "object": {
const cacheKey = schemaKeyRef;
this._cache.delete(cacheKey);
let id = schemaKeyRef[this.opts.schemaId];
if (id) {
id = (0, resolve_1.normalizeId)(id);
delete this.schemas[id];
delete this.refs[id];
}
return this;
}
default:
throw new Error("ajv.removeSchema: invalid parameter");
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions) {
for (const def of definitions)
this.addKeyword(def);
return this;
}
addKeyword(kwdOrDef, def // deprecated
) {
let keyword;
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef;
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
def.keyword = keyword;
}
}
else if (typeof kwdOrDef == "object" && def === undefined) {
def = kwdOrDef;
keyword = def.keyword;
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array");
}
}
else {
throw new Error("invalid addKeywords parameters");
}
checkKeyword.call(this, keyword, def);
if (!def) {
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
return this;
}
keywordMetaschema.call(this, def);
const definition = {
...def,
type: (0, dataType_1.getJSONTypes)(def.type),
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
};
(0, util_1.eachItem)(keyword, definition.type.length === 0
? (k) => addRule.call(this, k, definition)
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
return this;
}
getKeyword(keyword) {
const rule = this.RULES.all[keyword];
return typeof rule == "object" ? rule.definition : !!rule;
}
// Remove keyword
removeKeyword(keyword) {
// TODO return type should be Ajv
const { RULES } = this;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
if (i >= 0)
group.rules.splice(i, 1);
}
return this;
}
// Add format
addFormat(name, format) {
if (typeof format == "string")
format = new RegExp(format);
this.formats[name] = format;
return this;
}
errorsText(errors = this.errors, // optional array of validation errors
{ separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
) {
if (!errors || errors.length === 0)
return "No errors";
return errors
.map((e) => `${dataVar}${e.instancePath} ${e.message}`)
.reduce((text, msg) => text + separator + msg);
}
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
const rules = this.RULES.all;
metaSchema = JSON.parse(JSON.stringify(metaSchema));
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
let keywords = metaSchema;
for (const seg of segments)
keywords = keywords[seg];
for (const key in rules) {
const rule = rules[key];
if (typeof rule != "object")
continue;
const { $data } = rule.definition;
const schema = keywords[key];
if ($data && schema)
keywords[key] = schemaOrData(schema);
}
}
return metaSchema;
}
_removeAllSchemas(schemas, regex) {
for (const keyRef in schemas) {
const sch = schemas[keyRef];
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef];
}
else if (sch && !sch.meta) {
this._cache.delete(sch.schema);
delete schemas[keyRef];
}
}
}
}
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
let id;
const { schemaId } = this.opts;
if (typeof schema == "object") {
id = schema[schemaId];
}
else {
if (this.opts.jtd)
throw new Error("schema must be object");
else if (typeof schema != "boolean")
throw new Error("schema must be object or boolean");
}
let sch = this._cache.get(schema);
if (sch !== undefined)
return sch;
baseId = (0, resolve_1.normalizeId)(id || baseId);
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
this._cache.set(sch.schema, sch);
if (addSchema && !baseId.startsWith("#")) {
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
if (baseId)
this._checkUnique(baseId);
this.refs[baseId] = sch;
}
if (validateSchema)
this.validateSchema(schema, true);
return sch;
}
_checkUnique(id) {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`);
}
}
_compileSchemaEnv(sch) {
if (sch.meta)
this._compileMetaSchema(sch);
else
compile_1.compileSchema.call(this, sch);
/* istanbul ignore if */
if (!sch.validate)
throw new Error("ajv implementation error");
return sch.validate;
}
_compileMetaSchema(sch) {
const currentOpts = this.opts;
this.opts = this._metaOpts;
try {
compile_1.compileSchema.call(this, sch);
}
finally {
this.opts = currentOpts;
}
}
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports["default"] = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
for (const key in checkOpts) {
const opt = key;
if (opt in options)
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
}
}
function getSchEnv(keyRef) {
keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
const optsSchemas = this.opts.schemas;
if (!optsSchemas)
return;
if (Array.isArray(optsSchemas))
this.addSchema(optsSchemas);
else
for (const key in optsSchemas)
this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (const name in this.opts.formats) {
const format = this.opts.formats[name];
if (format)
this.addFormat(name, format);
}
}
function addInitialKeywords(defs) {
if (Array.isArray(defs)) {
this.addVocabulary(defs);
return;
}
this.logger.warn("keywords option as map is deprecated, pass array");
for (const keyword in defs) {
const def = defs[keyword];
if (!def.keyword)
def.keyword = keyword;
this.addKeyword(def);
}
}
function getMetaSchemaOptions() {
const metaOpts = { ...this.opts };
for (const opt of META_IGNORE_OPTIONS)
delete metaOpts[opt];
return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
if (logger === false)
return noLogs;
if (logger === undefined)
return console;
if (logger.log && logger.warn && logger.error)
return logger;
throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
const { RULES } = this;
(0, util_1.eachItem)(keyword, (kwd) => {
if (RULES.keywords[kwd])
throw new Error(`Keyword ${kwd} is already defined`);
if (!KEYWORD_NAME.test(kwd))
throw new Error(`Keyword ${kwd} has invalid name`);
});
if (!def)
return;
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function');
}
}
function addRule(keyword, definition, dataType) {
var _a;
const post = definition === null || definition === void 0 ? void 0 : definition.post;
if (dataType && post)
throw new Error('keyword with "post" flag cannot have "type"');
const { RULES } = this;
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.rules.push(ruleGroup);
}
RULES.keywords[keyword] = true;
if (!definition)
return;
const rule = {
keyword,
definition: {
...definition,
type: (0, dataType_1.getJSONTypes)(definition.type),
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
},
};
if (definition.before)
addBeforeRule.call(this, ruleGroup, rule, definition.before);
else
ruleGroup.rules.push(rule);
RULES.all[keyword] = rule;
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule);
}
else {
ruleGroup.rules.push(rule);
this.logger.warn(`rule ${before} is not defined`);
}
}
function keywordMetaschema(def) {
let { metaSchema } = def;
if (metaSchema === undefined)
return;
if (def.$data && this.opts.$data)
metaSchema = schemaOrData(metaSchema);
def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 73938:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://github.com/ajv-validator/ajv/issues/889
const equal = __nccwpck_require__(28206);
equal.code = 'require("ajv/dist/runtime/equal").default';
exports["default"] = equal;
//# sourceMappingURL=equal.js.map
/***/ }),
/***/ 56966:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
const len = str.length;
let length = 0;
let pos = 0;
let value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 0xd800 && value <= 0xdbff && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos);
if ((value & 0xfc00) === 0xdc00)
pos++; // low surrogate
}
}
return length;
}
exports["default"] = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map
/***/ }),
/***/ 16546:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const uri = __nccwpck_require__(70020);
uri.code = 'require("ajv/dist/runtime/uri").default';
exports["default"] = uri;
//# sourceMappingURL=uri.js.map
/***/ }),
/***/ 19975:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class ValidationError extends Error {
constructor(errors) {
super("validation failed");
this.errors = errors;
this.ajv = this.validation = true;
}
}
exports["default"] = ValidationError;
//# sourceMappingURL=validation_error.js.map
/***/ }),
/***/ 91231:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateAdditionalItems = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "additionalItems",
type: "array",
schemaType: ["boolean", "object"],
before: "uniqueItems",
error,
code(cxt) {
const { parentSchema, it } = cxt;
const { items } = parentSchema;
if (!Array.isArray(items)) {
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
return;
}
validateAdditionalItems(cxt, items);
},
};
function validateAdditionalItems(cxt, items) {
const { gen, schema, data, keyword, it } = cxt;
it.items = true;
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
if (schema === false) {
cxt.setParams({ len: items.length });
cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
}
else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
cxt.ok(valid);
}
function validateItems(valid) {
gen.forRange("i", items.length, len, (i) => {
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
if (!it.allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
});
}
}
exports.validateAdditionalItems = validateAdditionalItems;
exports["default"] = def;
//# sourceMappingURL=additionalItems.js.map
/***/ }),
/***/ 59222:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(22975);
const codegen_1 = __nccwpck_require__(56771);
const names_1 = __nccwpck_require__(20717);
const util_1 = __nccwpck_require__(28311);
const error = {
message: "must NOT have additional properties",
params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
keyword: "additionalProperties",
type: ["object"],
schemaType: ["boolean", "object"],
allowUndefined: true,
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
/* istanbul ignore if */
if (!errsCount)
throw new Error("ajv implementation error");
const { allErrors, opts } = it;
it.props = true;
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
return;
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
checkAdditionalProperties();
cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
function checkAdditionalProperties() {
gen.forIn("key", data, (key) => {
if (!props.length && !patProps.length)
additionalPropertyCode(key);
else
gen.if(isAdditional(key), () => additionalPropertyCode(key));
});
}
function isAdditional(key) {
let definedProp;
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
}
else if (props.length) {
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
}
else {
definedProp = codegen_1.nil;
}
if (patProps.length) {
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
}
return (0, codegen_1.not)(definedProp);
}
function deleteAdditional(key) {
gen.code((0, codegen_1._) `delete ${data}[${key}]`);
}
function additionalPropertyCode(key) {
if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
deleteAdditional(key);
return;
}
if (schema === false) {
cxt.setParams({ additionalProperty: key });
cxt.error();
if (!allErrors)
gen.break();
return;
}
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.name("valid");
if (opts.removeAdditional === "failing") {
applyAdditionalSchema(key, valid, false);
gen.if((0, codegen_1.not)(valid), () => {
cxt.reset();
deleteAdditional(key);
});
}
else {
applyAdditionalSchema(key, valid);
if (!allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
}
}
function applyAdditionalSchema(key, valid, errors) {
const subschema = {
keyword: "additionalProperties",
dataProp: key,
dataPropType: util_1.Type.Str,
};
if (errors === false) {
Object.assign(subschema, {
compositeRule: true,
createErrors: false,
allErrors: false,
});
}
cxt.subschema(subschema, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=additionalProperties.js.map
/***/ }),
/***/ 66376:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(28311);
const def = {
keyword: "allOf",
schemaType: "array",
code(cxt) {
const { gen, schema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const valid = gen.name("valid");
schema.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
cxt.ok(valid);
cxt.mergeEvaluated(schCxt);
});
},
};
exports["default"] = def;
//# sourceMappingURL=allOf.js.map
/***/ }),
/***/ 52010:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(22975);
const def = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in anyOf" },
};
exports["default"] = def;
//# sourceMappingURL=anyOf.js.map
/***/ }),
/***/ 62924:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: ({ params: { min, max } }) => max === undefined
? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
: (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
keyword: "contains",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
let min;
let max;
const { minContains, maxContains } = parentSchema;
if (it.opts.next) {
min = minContains === undefined ? 1 : minContains;
max = maxContains;
}
else {
min = 1;
}
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
cxt.setParams({ min, max });
if (max === undefined && min === 0) {
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
return;
}
if (max !== undefined && min > max) {
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
cxt.fail();
return;
}
if ((0, util_1.alwaysValidSchema)(it, schema)) {
let cond = (0, codegen_1._) `${len} >= ${min}`;
if (max !== undefined)
cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
cxt.pass(cond);
return;
}
it.items = true;
const valid = gen.name("valid");
if (max === undefined && min === 1) {
validateItems(valid, () => gen.if(valid, () => gen.break()));
}
else if (min === 0) {
gen.let(valid, true);
if (max !== undefined)
gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
}
else {
gen.let(valid, false);
validateItemsWithCount();
}
cxt.result(valid, () => cxt.reset());
function validateItemsWithCount() {
const schValid = gen.name("_valid");
const count = gen.let("count", 0);
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
}
function validateItems(_valid, block) {
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword: "contains",
dataProp: i,
dataPropType: util_1.Type.Num,
compositeRule: true,
}, _valid);
block();
});
}
function checkLimits(count) {
gen.code((0, codegen_1._) `${count}++`);
if (max === undefined) {
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
}
else {
gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
if (min === 1)
gen.assign(valid, true);
else
gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=contains.js.map
/***/ }),
/***/ 58190:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const code_1 = __nccwpck_require__(22975);
exports.error = {
message: ({ params: { property, depsCount, deps } }) => {
const property_ies = depsCount === 1 ? "property" : "properties";
return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
},
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`, // TODO change to reference
};
const def = {
keyword: "dependencies",
type: "object",
schemaType: "object",
error: exports.error,
code(cxt) {
const [propDeps, schDeps] = splitDependencies(cxt);
validatePropertyDeps(cxt, propDeps);
validateSchemaDeps(cxt, schDeps);
},
};
function splitDependencies({ schema }) {
const propertyDeps = {};
const schemaDeps = {};
for (const key in schema) {
if (key === "__proto__")
continue;
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
deps[key] = schema[key];
}
return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
const { gen, data, it } = cxt;
if (Object.keys(propertyDeps).length === 0)
return;
const missing = gen.let("missing");
for (const prop in propertyDeps) {
const deps = propertyDeps[prop];
if (deps.length === 0)
continue;
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
cxt.setParams({
property: prop,
depsCount: deps.length,
deps: deps.join(", "),
});
if (it.allErrors) {
gen.if(hasProperty, () => {
for (const depProp of deps) {
(0, code_1.checkReportMissingProp)(cxt, depProp);
}
});
}
else {
gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
for (const prop in schemaDeps) {
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
continue;
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
cxt.mergeValidEvaluated(schCxt, valid);
}, () => gen.var(valid, true) // TODO var
);
cxt.ok(valid);
}
}
exports.validateSchemaDeps = validateSchemaDeps;
exports["default"] = def;
//# sourceMappingURL=dependencies.js.map
/***/ }),
/***/ 46259:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
keyword: "if",
schemaType: ["object", "boolean"],
trackErrors: true,
error,
code(cxt) {
const { gen, parentSchema, it } = cxt;
if (parentSchema.then === undefined && parentSchema.else === undefined) {
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
}
const hasThen = hasSchema(it, "then");
const hasElse = hasSchema(it, "else");
if (!hasThen && !hasElse)
return;
const valid = gen.let("valid", true);
const schValid = gen.name("_valid");
validateIf();
cxt.reset();
if (hasThen && hasElse) {
const ifClause = gen.let("ifClause");
cxt.setParams({ ifClause });
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
}
else if (hasThen) {
gen.if(schValid, validateClause("then"));
}
else {
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
}
cxt.pass(valid, () => cxt.error(true));
function validateIf() {
const schCxt = cxt.subschema({
keyword: "if",
compositeRule: true,
createErrors: false,
allErrors: false,
}, schValid);
cxt.mergeEvaluated(schCxt);
}
function validateClause(keyword, ifClause) {
return () => {
const schCxt = cxt.subschema({ keyword }, schValid);
gen.assign(valid, schValid);
cxt.mergeValidEvaluated(schCxt, valid);
if (ifClause)
gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
else
cxt.setParams({ ifClause: keyword });
};
}
},
};
function hasSchema(it, keyword) {
const schema = it.schema[keyword];
return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports["default"] = def;
//# sourceMappingURL=if.js.map
/***/ }),
/***/ 48407:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const additionalItems_1 = __nccwpck_require__(91231);
const prefixItems_1 = __nccwpck_require__(5673);
const items_1 = __nccwpck_require__(82844);
const items2020_1 = __nccwpck_require__(37392);
const contains_1 = __nccwpck_require__(62924);
const dependencies_1 = __nccwpck_require__(58190);
const propertyNames_1 = __nccwpck_require__(16366);
const additionalProperties_1 = __nccwpck_require__(59222);
const properties_1 = __nccwpck_require__(93906);
const patternProperties_1 = __nccwpck_require__(12238);
const not_1 = __nccwpck_require__(77491);
const anyOf_1 = __nccwpck_require__(52010);
const oneOf_1 = __nccwpck_require__(77883);
const allOf_1 = __nccwpck_require__(66376);
const if_1 = __nccwpck_require__(46259);
const thenElse_1 = __nccwpck_require__(26705);
function getApplicator(draft2020 = false) {
const applicator = [
// any
not_1.default,
anyOf_1.default,
oneOf_1.default,
allOf_1.default,
if_1.default,
thenElse_1.default,
// object
propertyNames_1.default,
additionalProperties_1.default,
dependencies_1.default,
properties_1.default,
patternProperties_1.default,
];
// array
if (draft2020)
applicator.push(prefixItems_1.default, items2020_1.default);
else
applicator.push(additionalItems_1.default, items_1.default);
applicator.push(contains_1.default);
return applicator;
}
exports["default"] = getApplicator;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 82844:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateTuple = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const code_1 = __nccwpck_require__(22975);
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "array", "boolean"],
before: "uniqueItems",
code(cxt) {
const { schema, it } = cxt;
if (Array.isArray(schema))
return validateTuple(cxt, "additionalItems", schema);
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
cxt.ok((0, code_1.validateArray)(cxt));
},
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
const { gen, parentSchema, data, keyword, it } = cxt;
checkStrictTuple(parentSchema);
if (it.opts.unevaluated && schArr.length && it.items !== true) {
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
}
const valid = gen.name("valid");
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
schArr.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
keyword,
schemaProp: i,
dataProp: i,
}, valid));
cxt.ok(valid);
});
function checkStrictTuple(sch) {
const { opts, errSchemaPath } = it;
const l = schArr.length;
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
if (opts.strictTuples && !fullTuple) {
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
}
}
}
exports.validateTuple = validateTuple;
exports["default"] = def;
//# sourceMappingURL=items.js.map
/***/ }),
/***/ 37392:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const code_1 = __nccwpck_require__(22975);
const additionalItems_1 = __nccwpck_require__(91231);
const error = {
message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
keyword: "items",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
error,
code(cxt) {
const { schema, parentSchema, it } = cxt;
const { prefixItems } = parentSchema;
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
if (prefixItems)
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
else
cxt.ok((0, code_1.validateArray)(cxt));
},
};
exports["default"] = def;
//# sourceMappingURL=items2020.js.map
/***/ }),
/***/ 77491:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(28311);
const def = {
keyword: "not",
schemaType: ["object", "boolean"],
trackErrors: true,
code(cxt) {
const { gen, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema)) {
cxt.fail();
return;
}
const valid = gen.name("valid");
cxt.subschema({
keyword: "not",
compositeRule: true,
createErrors: false,
allErrors: false,
}, valid);
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
},
error: { message: "must NOT be valid" },
};
exports["default"] = def;
//# sourceMappingURL=not.js.map
/***/ }),
/***/ 77883:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: "must match exactly one schema in oneOf",
params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
keyword: "oneOf",
schemaType: "array",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
if (it.opts.discriminator && parentSchema.discriminator)
return;
const schArr = schema;
const valid = gen.let("valid", false);
const passing = gen.let("passing", null);
const schValid = gen.name("_valid");
cxt.setParams({ passing });
// TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
gen.block(validateOneOf);
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
function validateOneOf() {
schArr.forEach((sch, i) => {
let schCxt;
if ((0, util_1.alwaysValidSchema)(it, sch)) {
gen.var(schValid, true);
}
else {
schCxt = cxt.subschema({
keyword: "oneOf",
schemaProp: i,
compositeRule: true,
}, schValid);
}
if (i > 0) {
gen
.if((0, codegen_1._) `${schValid} && ${valid}`)
.assign(valid, false)
.assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
.else();
}
gen.if(schValid, () => {
gen.assign(valid, true);
gen.assign(passing, i);
if (schCxt)
cxt.mergeEvaluated(schCxt, codegen_1.Name);
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=oneOf.js.map
/***/ }),
/***/ 12238:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(22975);
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const util_2 = __nccwpck_require__(28311);
const def = {
keyword: "patternProperties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, data, parentSchema, it } = cxt;
const { opts } = it;
const patterns = (0, code_1.allSchemaProperties)(schema);
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
if (patterns.length === 0 ||
(alwaysValidPatterns.length === patterns.length &&
(!it.opts.unevaluated || it.props === true))) {
return;
}
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
const valid = gen.name("valid");
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
}
const { props } = it;
validatePatternProperties();
function validatePatternProperties() {
for (const pat of patterns) {
if (checkProperties)
checkMatchingProperties(pat);
if (it.allErrors) {
validateProperties(pat);
}
else {
gen.var(valid, true); // TODO var
validateProperties(pat);
gen.if(valid);
}
}
}
function checkMatchingProperties(pat) {
for (const prop in checkProperties) {
if (new RegExp(pat).test(prop)) {
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
}
}
}
function validateProperties(pat) {
gen.forIn("key", data, (key) => {
gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
const alwaysValid = alwaysValidPatterns.includes(pat);
if (!alwaysValid) {
cxt.subschema({
keyword: "patternProperties",
schemaProp: pat,
dataProp: key,
dataPropType: util_2.Type.Str,
}, valid);
}
if (it.opts.unevaluated && props !== true) {
gen.assign((0, codegen_1._) `${props}[${key}]`, true);
}
else if (!alwaysValid && !it.allErrors) {
// can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
// or if all properties were evaluated (props === true)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
});
});
}
},
};
exports["default"] = def;
//# sourceMappingURL=patternProperties.js.map
/***/ }),
/***/ 5673:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const items_1 = __nccwpck_require__(82844);
const def = {
keyword: "prefixItems",
type: "array",
schemaType: ["array"],
before: "uniqueItems",
code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports["default"] = def;
//# sourceMappingURL=prefixItems.js.map
/***/ }),
/***/ 93906:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const validate_1 = __nccwpck_require__(74504);
const code_1 = __nccwpck_require__(22975);
const util_1 = __nccwpck_require__(28311);
const additionalProperties_1 = __nccwpck_require__(59222);
const def = {
keyword: "properties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
}
const allProps = (0, code_1.allSchemaProperties)(schema);
for (const prop of allProps) {
it.definedProperties.add(prop);
}
if (it.opts.unevaluated && allProps.length && it.props !== true) {
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
}
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
if (properties.length === 0)
return;
const valid = gen.name("valid");
for (const prop of properties) {
if (hasDefault(prop)) {
applyPropertySchema(prop);
}
else {
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
applyPropertySchema(prop);
if (!it.allErrors)
gen.else().var(valid, true);
gen.endIf();
}
cxt.it.definedProperties.add(prop);
cxt.ok(valid);
}
function hasDefault(prop) {
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
}
function applyPropertySchema(prop) {
cxt.subschema({
keyword: "properties",
schemaProp: prop,
dataProp: prop,
}, valid);
}
},
};
exports["default"] = def;
//# sourceMappingURL=properties.js.map
/***/ }),
/***/ 16366:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: "property name must be valid",
params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
keyword: "propertyNames",
type: "object",
schemaType: ["object", "boolean"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
gen.forIn("key", data, (key) => {
cxt.setParams({ propertyName: key });
cxt.subschema({
keyword: "propertyNames",
data: key,
dataTypes: ["string"],
propertyName: key,
compositeRule: true,
}, valid);
gen.if((0, codegen_1.not)(valid), () => {
cxt.error(true);
if (!it.allErrors)
gen.break();
});
});
cxt.ok(valid);
},
};
exports["default"] = def;
//# sourceMappingURL=propertyNames.js.map
/***/ }),
/***/ 26705:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __nccwpck_require__(28311);
const def = {
keyword: ["then", "else"],
schemaType: ["object", "boolean"],
code({ keyword, parentSchema, it }) {
if (parentSchema.if === undefined)
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
},
};
exports["default"] = def;
//# sourceMappingURL=thenElse.js.map
/***/ }),
/***/ 22975:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const names_1 = __nccwpck_require__(20717);
const util_2 = __nccwpck_require__(28311);
function checkReportMissingProp(cxt, prop) {
const { gen, data, it } = cxt;
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
cxt.error();
});
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
cxt.setParams({ missingProperty: missing }, true);
cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
});
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
const valCxt = [
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
[names_1.default.parentData, it.parentData],
[names_1.default.parentDataProperty, it.parentDataProperty],
[names_1.default.rootData, names_1.default.rootData],
];
if (it.opts.dynamicRef)
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
const u = opts.unicodeRegExp ? "u" : "";
const { regExp } = opts.code;
const rx = regExp(pattern, u);
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
});
}
exports.usePattern = usePattern;
function validateArray(cxt) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
if (it.allErrors) {
const validArr = gen.let("valid", true);
validateItems(() => gen.assign(validArr, false));
return validArr;
}
gen.var(valid, true);
validateItems(() => gen.break());
return valid;
function validateItems(notValid) {
const len = gen.const("len", (0, codegen_1._) `${data}.length`);
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword,
dataProp: i,
dataPropType: util_1.Type.Num,
}, valid);
gen.if((0, codegen_1.not)(valid), notValid);
});
}
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
const { gen, schema, keyword, it } = cxt;
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
if (alwaysValid && !it.opts.unevaluated)
return;
const valid = gen.let("valid", false);
const schValid = gen.name("_valid");
gen.block(() => schema.forEach((_sch, i) => {
const schCxt = cxt.subschema({
keyword,
schemaProp: i,
compositeRule: true,
}, schValid);
gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged)
gen.if((0, codegen_1.not)(valid));
}));
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map
/***/ }),
/***/ 39752:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const def = {
keyword: "id",
code() {
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
},
};
exports["default"] = def;
//# sourceMappingURL=id.js.map
/***/ }),
/***/ 38978:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const id_1 = __nccwpck_require__(39752);
const ref_1 = __nccwpck_require__(7506);
const core = [
"$schema",
"$id",
"$defs",
"$vocabulary",
{ keyword: "$comment" },
"definitions",
id_1.default,
ref_1.default,
];
exports["default"] = core;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 7506:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = __nccwpck_require__(43857);
const code_1 = __nccwpck_require__(22975);
const codegen_1 = __nccwpck_require__(56771);
const names_1 = __nccwpck_require__(20717);
const compile_1 = __nccwpck_require__(56501);
const util_1 = __nccwpck_require__(28311);
const def = {
keyword: "$ref",
schemaType: "string",
code(cxt) {
const { gen, schema: $ref, it } = cxt;
const { baseId, schemaEnv: env, validateName, opts, self } = it;
const { root } = env;
if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
return callRootRef();
const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
if (schOrEnv === undefined)
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
if (schOrEnv instanceof compile_1.SchemaEnv)
return callValidate(schOrEnv);
return inlineRefSchema(schOrEnv);
function callRootRef() {
if (env === root)
return callRef(cxt, validateName, env, env.$async);
const rootName = gen.scopeValue("root", { ref: root });
return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
}
function callValidate(sch) {
const v = getValidate(cxt, sch);
callRef(cxt, v, sch, sch.$async);
}
function inlineRefSchema(sch) {
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
const valid = gen.name("valid");
const schCxt = cxt.subschema({
schema: sch,
dataTypes: [],
schemaPath: codegen_1.nil,
topSchemaRef: schName,
errSchemaPath: $ref,
}, valid);
cxt.mergeEvaluated(schCxt);
cxt.ok(valid);
}
},
};
function getValidate(cxt, sch) {
const { gen } = cxt;
return sch.validate
? gen.scopeValue("validate", { ref: sch.validate })
: (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
const { gen, it } = cxt;
const { allErrors, schemaEnv: env, opts } = it;
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
if ($async)
callAsyncRef();
else
callSyncRef();
function callAsyncRef() {
if (!env.$async)
throw new Error("async schema referenced by sync schema");
const valid = gen.let("valid");
gen.try(() => {
gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
if (!allErrors)
gen.assign(valid, true);
}, (e) => {
gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
addErrorsFrom(e);
if (!allErrors)
gen.assign(valid, false);
});
cxt.ok(valid);
}
function callSyncRef() {
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
}
function addErrorsFrom(source) {
const errs = (0, codegen_1._) `${source}.errors`;
gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
}
function addEvaluatedFrom(source) {
var _a;
if (!it.opts.unevaluated)
return;
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
// TODO refactor
if (it.props !== true) {
if (schEvaluated && !schEvaluated.dynamicProps) {
if (schEvaluated.props !== undefined) {
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
}
}
else {
const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
}
}
if (it.items !== true) {
if (schEvaluated && !schEvaluated.dynamicItems) {
if (schEvaluated.items !== undefined) {
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
}
}
else {
const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
}
}
}
}
exports.callRef = callRef;
exports["default"] = def;
//# sourceMappingURL=ref.js.map
/***/ }),
/***/ 539:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const types_1 = __nccwpck_require__(93967);
const compile_1 = __nccwpck_require__(56501);
const ref_error_1 = __nccwpck_require__(43857);
const util_1 = __nccwpck_require__(28311);
const error = {
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
? `tag "${tagName}" must be string`
: `value of tag "${tagName}" must be in oneOf`,
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
keyword: "discriminator",
type: "object",
schemaType: "object",
error,
code(cxt) {
const { gen, data, schema, parentSchema, it } = cxt;
const { oneOf } = parentSchema;
if (!it.opts.discriminator) {
throw new Error("discriminator: requires discriminator option");
}
const tagName = schema.propertyName;
if (typeof tagName != "string")
throw new Error("discriminator: requires propertyName");
if (schema.mapping)
throw new Error("discriminator: mapping is not supported");
if (!oneOf)
throw new Error("discriminator: requires oneOf keyword");
const valid = gen.let("valid", false);
const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
cxt.ok(valid);
function validateMapping() {
const mapping = getMapping();
gen.if(false);
for (const tagValue in mapping) {
gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
gen.assign(valid, applyTagSchema(mapping[tagValue]));
}
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
gen.endIf();
}
function applyTagSchema(schemaProp) {
const _valid = gen.name("valid");
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
cxt.mergeEvaluated(schCxt, codegen_1.Name);
return _valid;
}
function getMapping() {
var _a;
const oneOfMapping = {};
const topRequired = hasRequired(parentSchema);
let tagRequired = true;
for (let i = 0; i < oneOf.length; i++) {
let sch = oneOf[i];
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
const ref = sch.$ref;
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
if (sch instanceof compile_1.SchemaEnv)
sch = sch.schema;
if (sch === undefined)
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
}
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
if (typeof propSch != "object") {
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
}
tagRequired = tagRequired && (topRequired || hasRequired(sch));
addMappings(propSch, i);
}
if (!tagRequired)
throw new Error(`discriminator: "${tagName}" must be required`);
return oneOfMapping;
function hasRequired({ required }) {
return Array.isArray(required) && required.includes(tagName);
}
function addMappings(sch, i) {
if (sch.const) {
addMapping(sch.const, i);
}
else if (sch.enum) {
for (const tagValue of sch.enum) {
addMapping(tagValue, i);
}
}
else {
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
}
}
function addMapping(tagValue, i) {
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
}
oneOfMapping[tagValue] = i;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 93967:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
DiscrError["Tag"] = "tag";
DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 73684:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const core_1 = __nccwpck_require__(38978);
const validation_1 = __nccwpck_require__(82275);
const applicator_1 = __nccwpck_require__(48407);
const format_1 = __nccwpck_require__(7896);
const metadata_1 = __nccwpck_require__(44228);
const draft7Vocabularies = [
core_1.default,
validation_1.default,
(0, applicator_1.default)(),
format_1.default,
metadata_1.metadataVocabulary,
metadata_1.contentVocabulary,
];
exports["default"] = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map
/***/ }),
/***/ 96256:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
keyword: "format",
type: ["number", "string"],
schemaType: "string",
$data: true,
error,
code(cxt, ruleType) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
const { opts, errSchemaPath, schemaEnv, self } = it;
if (!opts.validateFormats)
return;
if ($data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
});
const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
const fType = gen.let("fType");
const format = gen.let("format");
// TODO simplify
gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
function unknownFmt() {
if (opts.strictSchema === false)
return codegen_1.nil;
return (0, codegen_1._) `${schemaCode} && !${format}`;
}
function invalidFmt() {
const callFormat = schemaEnv.$async
? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
: (0, codegen_1._) `${format}(${data})`;
const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
}
}
function validateFormat() {
const formatDef = self.formats[schema];
if (!formatDef) {
unknownFormat();
return;
}
if (formatDef === true)
return;
const [fmtType, format, fmtRef] = getFormat(formatDef);
if (fmtType === ruleType)
cxt.pass(validCondition());
function unknownFormat() {
if (opts.strictSchema === false) {
self.logger.warn(unknownMsg());
return;
}
throw new Error(unknownMsg());
function unknownMsg() {
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
}
}
function getFormat(fmtDef) {
const code = fmtDef instanceof RegExp
? (0, codegen_1.regexpCode)(fmtDef)
: opts.code.formats
? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
: undefined;
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
}
return ["string", fmtDef, fmt];
}
function validCondition() {
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
if (!schemaEnv.$async)
throw new Error("async format in sync schema");
return (0, codegen_1._) `await ${fmtRef}(${data})`;
}
return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
}
}
},
};
exports["default"] = def;
//# sourceMappingURL=format.js.map
/***/ }),
/***/ 7896:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const format_1 = __nccwpck_require__(96256);
const format = [format_1.default];
exports["default"] = format;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 44228:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
"title",
"description",
"default",
"deprecated",
"readOnly",
"writeOnly",
"examples",
];
exports.contentVocabulary = [
"contentMediaType",
"contentEncoding",
"contentSchema",
];
//# sourceMappingURL=metadata.js.map
/***/ }),
/***/ 61260:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const equal_1 = __nccwpck_require__(73938);
const error = {
message: "must be equal to constant",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
keyword: "const",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schemaCode, schema } = cxt;
if ($data || (schema && typeof schema == "object")) {
cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
}
else {
cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
}
},
};
exports["default"] = def;
//# sourceMappingURL=const.js.map
/***/ }),
/***/ 98221:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const equal_1 = __nccwpck_require__(73938);
const error = {
message: "must be equal to one of the allowed values",
params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
keyword: "enum",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
if (!$data && schema.length === 0)
throw new Error("enum must have non-empty array");
const useLoop = schema.length >= it.opts.loopEnum;
let eql;
const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
let valid;
if (useLoop || $data) {
valid = gen.let("valid");
cxt.block$data(valid, loopEnum);
}
else {
/* istanbul ignore if */
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const vSchema = gen.const("vSchema", schemaCode);
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
}
cxt.pass(valid);
function loopEnum() {
gen.assign(valid, false);
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
}
function equalCode(vSchema, i) {
const sch = schema[i];
return typeof sch === "object" && sch !== null
? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
: (0, codegen_1._) `${data} === ${sch}`;
}
},
};
exports["default"] = def;
//# sourceMappingURL=enum.js.map
/***/ }),
/***/ 82275:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const limitNumber_1 = __nccwpck_require__(80092);
const multipleOf_1 = __nccwpck_require__(16864);
const limitLength_1 = __nccwpck_require__(71337);
const pattern_1 = __nccwpck_require__(81536);
const limitProperties_1 = __nccwpck_require__(51536);
const required_1 = __nccwpck_require__(99648);
const limitItems_1 = __nccwpck_require__(51394);
const uniqueItems_1 = __nccwpck_require__(7474);
const const_1 = __nccwpck_require__(61260);
const enum_1 = __nccwpck_require__(98221);
const validation = [
// number
limitNumber_1.default,
multipleOf_1.default,
// string
limitLength_1.default,
pattern_1.default,
// object
limitProperties_1.default,
required_1.default,
// array
limitItems_1.default,
uniqueItems_1.default,
// any
{ keyword: "type", schemaType: ["string", "array"] },
{ keyword: "nullable", schemaType: "boolean" },
const_1.default,
enum_1.default,
];
exports["default"] = validation;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 51394:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxItems" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxItems", "minItems"],
type: "array",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitItems.js.map
/***/ }),
/***/ 71337:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const ucs2length_1 = __nccwpck_require__(56966);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxLength" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode, it } = cxt;
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitLength.js.map
/***/ }),
/***/ 80092:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const ops = codegen_1.operators;
const KWDs = {
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
keyword: Object.keys(KWDs),
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitNumber.js.map
/***/ }),
/***/ 51536:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxProperties" ? "more" : "fewer";
return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
},
params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
keyword: ["maxProperties", "minProperties"],
type: "object",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
},
};
exports["default"] = def;
//# sourceMappingURL=limitProperties.js.map
/***/ }),
/***/ 16864:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const codegen_1 = __nccwpck_require__(56771);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
keyword: "multipleOf",
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, it } = cxt;
// const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
const prec = it.opts.multipleOfPrecision;
const res = gen.let("res");
const invalid = prec
? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
: (0, codegen_1._) `${res} !== parseInt(${res})`;
cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
},
};
exports["default"] = def;
//# sourceMappingURL=multipleOf.js.map
/***/ }),
/***/ 81536:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(22975);
const codegen_1 = __nccwpck_require__(56771);
const error = {
message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
keyword: "pattern",
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { data, $data, schema, schemaCode, it } = cxt;
// TODO regexp should be wrapped in try/catchs
const u = it.opts.unicodeRegExp ? "u" : "";
const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
},
};
exports["default"] = def;
//# sourceMappingURL=pattern.js.map
/***/ }),
/***/ 99648:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const code_1 = __nccwpck_require__(22975);
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const error = {
message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
keyword: "required",
type: "object",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, schema, schemaCode, data, $data, it } = cxt;
const { opts } = it;
if (!$data && schema.length === 0)
return;
const useLoop = schema.length >= opts.loopRequired;
if (it.allErrors)
allErrorsMode();
else
exitOnErrorMode();
if (opts.strictRequired) {
const props = cxt.parentSchema.properties;
const { definedProperties } = cxt.it;
for (const requiredKey of schema) {
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
}
}
}
function allErrorsMode() {
if (useLoop || $data) {
cxt.block$data(codegen_1.nil, loopAllRequired);
}
else {
for (const prop of schema) {
(0, code_1.checkReportMissingProp)(cxt, prop);
}
}
}
function exitOnErrorMode() {
const missing = gen.let("missing");
if (useLoop || $data) {
const valid = gen.let("valid", true);
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
cxt.ok(valid);
}
else {
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
function loopAllRequired() {
gen.forOf("prop", schemaCode, (prop) => {
cxt.setParams({ missingProperty: prop });
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
});
}
function loopUntilMissing(missing, valid) {
cxt.setParams({ missingProperty: missing });
gen.forOf(missing, schemaCode, () => {
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
gen.if((0, codegen_1.not)(valid), () => {
cxt.error();
gen.break();
});
}, codegen_1.nil);
}
},
};
exports["default"] = def;
//# sourceMappingURL=required.js.map
/***/ }),
/***/ 7474:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const dataType_1 = __nccwpck_require__(79954);
const codegen_1 = __nccwpck_require__(56771);
const util_1 = __nccwpck_require__(28311);
const equal_1 = __nccwpck_require__(73938);
const error = {
message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
keyword: "uniqueItems",
type: "array",
schemaType: "boolean",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
if (!$data && !schema)
return;
const valid = gen.let("valid");
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
cxt.ok(valid);
function validateUniqueItems() {
const i = gen.let("i", (0, codegen_1._) `${data}.length`);
const j = gen.let("j");
cxt.setParams({ i, j });
gen.assign(valid, true);
gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
}
function canOptimize() {
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
}
function loopN(i, j) {
const item = gen.name("item");
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
const indices = gen.const("indices", (0, codegen_1._) `{}`);
gen.for((0, codegen_1._) `;${i}--;`, () => {
gen.let(item, (0, codegen_1._) `${data}[${i}]`);
gen.if(wrongType, (0, codegen_1._) `continue`);
if (itemTypes.length > 1)
gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
gen
.if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
cxt.error();
gen.assign(valid, false).break();
})
.code((0, codegen_1._) `${indices}[${item}] = ${i}`);
});
}
function loopN2(i, j) {
const eql = (0, util_1.useFunc)(gen, equal_1.default);
const outer = gen.name("outer");
gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
cxt.error();
gen.assign(valid, false).break(outer);
})));
}
},
};
exports["default"] = def;
//# sourceMappingURL=uniqueItems.js.map
/***/ }),
/***/ 67786:
/***/ ((module) => {
"use strict";
var traverse = module.exports = function (schema, opts, cb) {
// Legacy support for v0.3.1 and earlier.
if (typeof opts == 'function') {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
var post = cb.post || function() {};
_traverse(opts, pre, post, schema, '', schema);
};
traverse.keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
if: true,
then: true,
else: true
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
$defs: true,
definitions: true,
properties: true,
patternProperties: true,
dependencies: true
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
maximum: true,
minimum: true,
exclusiveMaximum: true,
exclusiveMinimum: true,
multipleOf: true,
maxLength: true,
minLength: true,
pattern: true,
format: true,
maxItems: true,
minItems: true,
uniqueItems: true,
maxProperties: true,
minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i=0; i<sch.length; i++)
_traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == 'object') {
for (var prop in sch)
_traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
_traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
function escapeJsonPtr(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
/***/ }),
/***/ 35224:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const parse = __nccwpck_require__(95882);
const stringify = __nccwpck_require__(84815);
const fastQuerystring = {
parse,
stringify,
};
/**
* Enable TS and JS support
*
* - `const qs = require('fast-querystring')`
* - `import qs from 'fast-querystring'`
*/
module.exports = fastQuerystring;
module.exports["default"] = fastQuerystring;
module.exports.parse = parse;
module.exports.stringify = stringify;
/***/ }),
/***/ 96749:
/***/ ((module) => {
// This file is taken from Node.js project.
// Full implementation can be found from https://github.com/nodejs/node/blob/main/lib/internal/querystring.js
const hexTable = Array.from(
{ length: 256 },
(_, i) => "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(),
);
// These characters do not need escaping when generating query strings:
// ! - . _ ~
// ' ( ) *
// digits
// alpha (uppercase)
// alpha (lowercase)
// rome-ignore format: the array should not be formatted
const noEscape = new Int8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 80 - 95
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, // 112 - 127
]);
/**
* @param {string} str
* @returns {string}
*/
function encodeString(str) {
const len = str.length;
if (len === 0) return "";
let out = "";
let lastPos = 0;
let i = 0;
outer: for (; i < len; i++) {
let c = str.charCodeAt(i);
// ASCII
while (c < 0x80) {
if (noEscape[c] !== 1) {
if (lastPos < i) out += str.slice(lastPos, i);
lastPos = i + 1;
out += hexTable[c];
}
if (++i === len) break outer;
c = str.charCodeAt(i);
}
if (lastPos < i) out += str.slice(lastPos, i);
// Multi-byte characters ...
if (c < 0x800) {
lastPos = i + 1;
out += hexTable[0xc0 | (c >> 6)] + hexTable[0x80 | (c & 0x3f)];
continue;
}
if (c < 0xd800 || c >= 0xe000) {
lastPos = i + 1;
out +=
hexTable[0xe0 | (c >> 12)] +
hexTable[0x80 | ((c >> 6) & 0x3f)] +
hexTable[0x80 | (c & 0x3f)];
continue;
}
// Surrogate pair
++i;
// This branch should never happen because all URLSearchParams entries
// should already be converted to USVString. But, included for
// completion's sake anyway.
if (i >= len) {
throw new Error("URI malformed");
}
const c2 = str.charCodeAt(i) & 0x3ff;
lastPos = i + 1;
c = 0x10000 + (((c & 0x3ff) << 10) | c2);
out +=
hexTable[0xf0 | (c >> 18)] +
hexTable[0x80 | ((c >> 12) & 0x3f)] +
hexTable[0x80 | ((c >> 6) & 0x3f)] +
hexTable[0x80 | (c & 0x3f)];
}
if (lastPos === 0) return str;
if (lastPos < len) return out + str.slice(lastPos);
return out;
}
module.exports = { encodeString };
/***/ }),
/***/ 95882:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastDecode = __nccwpck_require__(1960);
const plusRegex = /\+/g;
const Empty = function () {};
Empty.prototype = Object.create(null);
/**
* @callback parse
* @param {string} input
*/
function parse(input) {
// Optimization: Use new Empty() instead of Object.create(null) for performance
// v8 has a better optimization for initializing functions compared to Object
const result = new Empty();
if (typeof input !== "string") {
return result;
}
let inputLength = input.length;
let key = "";
let value = "";
let startingIndex = -1;
let equalityIndex = -1;
let shouldDecodeKey = false;
let shouldDecodeValue = false;
let keyHasPlus = false;
let valueHasPlus = false;
let hasBothKeyValuePair = false;
let c = 0;
// Have a boundary of input.length + 1 to access last pair inside the loop.
for (let i = 0; i < inputLength + 1; i++) {
c = i !== inputLength ? input.charCodeAt(i) : 38;
// Handle '&' and end of line to pass the current values to result
if (c === 38) {
hasBothKeyValuePair = equalityIndex > startingIndex;
// Optimization: Reuse equality index to store the end of key
if (!hasBothKeyValuePair) {
equalityIndex = i;
}
key = input.slice(startingIndex + 1, equalityIndex);
// Add key/value pair only if the range size is greater than 1; a.k.a. contains at least "="
if (hasBothKeyValuePair || key.length > 0) {
// Optimization: Replace '+' with space
if (keyHasPlus) {
key = key.replace(plusRegex, " ");
}
// Optimization: Do not decode if it's not necessary.
if (shouldDecodeKey) {
key = fastDecode(key) || key;
}
if (hasBothKeyValuePair) {
value = input.slice(equalityIndex + 1, i);
if (valueHasPlus) {
value = value.replace(plusRegex, " ");
}
if (shouldDecodeValue) {
value = fastDecode(value) || value;
}
}
const currentValue = result[key];
if (currentValue === undefined) {
result[key] = value;
} else {
// Optimization: value.pop is faster than Array.isArray(value)
if (currentValue.pop) {
currentValue.push(value);
} else {
result[key] = [currentValue, value];
}
}
}
// Reset reading key value pairs
value = "";
startingIndex = i;
equalityIndex = i;
shouldDecodeKey = false;
shouldDecodeValue = false;
keyHasPlus = false;
valueHasPlus = false;
}
// Check '='
else if (c === 61) {
if (equalityIndex <= startingIndex) {
equalityIndex = i;
}
// If '=' character occurs again, we should decode the input.
else {
shouldDecodeValue = true;
}
}
// Check '+', and remember to replace it with empty space.
else if (c === 43) {
if (equalityIndex > startingIndex) {
valueHasPlus = true;
} else {
keyHasPlus = true;
}
}
// Check '%' character for encoding
else if (c === 37) {
if (equalityIndex > startingIndex) {
shouldDecodeValue = true;
} else {
shouldDecodeKey = true;
}
}
}
return result;
}
module.exports = parse;
/***/ }),
/***/ 84815:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { encodeString } = __nccwpck_require__(96749);
function getAsPrimitive(value) {
const type = typeof value;
if (type === "string") {
// Length check is handled inside encodeString function
return encodeString(value);
} else if (type === "bigint") {
return value.toString();
} else if (type === "boolean") {
return value ? "true" : "false";
} else if (type === "number" && Number.isFinite(value)) {
return value < 1e21 ? "" + value : encodeString("" + value);
}
return "";
}
/**
* @param {Record<string, string | number | boolean
* | ReadonlyArray<string | number | boolean> | null>} input
* @returns {string}
*/
function stringify(input) {
let result = "";
if (input === null || typeof input !== "object") {
return result;
}
const separator = "&";
const keys = Object.keys(input);
const keyLength = keys.length;
let valueLength = 0;
for (let i = 0; i < keyLength; i++) {
const key = keys[i];
const value = input[key];
const encodedKey = encodeString(key) + "=";
if (i) {
result += separator;
}
if (Array.isArray(value)) {
valueLength = value.length;
for (let j = 0; j < valueLength; j++) {
if (j) {
result += separator;
}
// Optimization: Dividing into multiple lines improves the performance.
// Since v8 does not need to care about the '+' character if it was one-liner.
result += encodedKey;
result += getAsPrimitive(value[j]);
}
} else {
result += encodedKey;
result += getAsPrimitive(value);
}
}
return result;
}
module.exports = stringify;
/***/ }),
/***/ 24826:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const validator = __nccwpck_require__(74174)
const parse = __nccwpck_require__(96214)
const redactor = __nccwpck_require__(17333)
const restorer = __nccwpck_require__(98806)
const { groupRedact, nestedRedact } = __nccwpck_require__(54865)
const state = __nccwpck_require__(41012)
const rx = __nccwpck_require__(9158)
const validate = validator()
const noop = (o) => o
noop.restore = noop
const DEFAULT_CENSOR = '[REDACTED]'
fastRedact.rx = rx
fastRedact.validator = validator
module.exports = fastRedact
function fastRedact (opts = {}) {
const paths = Array.from(new Set(opts.paths || []))
const serialize = 'serialize' in opts ? (
opts.serialize === false ? opts.serialize
: (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)
) : JSON.stringify
const remove = opts.remove
if (remove === true && serialize !== JSON.stringify) {
throw Error('fast-redact remove option may only be set when serializer is JSON.stringify')
}
const censor = remove === true
? undefined
: 'censor' in opts ? opts.censor : DEFAULT_CENSOR
const isCensorFct = typeof censor === 'function'
const censorFctTakesPath = isCensorFct && censor.length > 1
if (paths.length === 0) return serialize || noop
validate({ paths, serialize, censor })
const { wildcards, wcLen, secret } = parse({ paths, censor })
const compileRestore = restorer()
const strict = 'strict' in opts ? opts.strict : true
return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({
secret,
censor,
compileRestore,
serialize,
groupRedact,
nestedRedact,
wildcards,
wcLen
}))
}
/***/ }),
/***/ 54865:
/***/ ((module) => {
"use strict";
module.exports = {
groupRedact,
groupRestore,
nestedRedact,
nestedRestore
}
function groupRestore ({ keys, values, target }) {
if (target == null || typeof target === 'string') return
const length = keys.length
for (var i = 0; i < length; i++) {
const k = keys[i]
target[k] = values[i]
}
}
function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {
const target = get(o, path)
if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }
const keys = Object.keys(target)
const keysLength = keys.length
const pathLength = path.length
const pathWithKey = censorFctTakesPath ? [...path] : undefined
const values = new Array(keysLength)
for (var i = 0; i < keysLength; i++) {
const key = keys[i]
values[i] = target[key]
if (censorFctTakesPath) {
pathWithKey[pathLength] = key
target[key] = censor(target[key], pathWithKey)
} else if (isCensorFct) {
target[key] = censor(target[key])
} else {
target[key] = censor
}
}
return { keys, values, target, flat: true }
}
/**
* @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects
*/
function nestedRestore (instructions) {
for (let i = 0; i < instructions.length; i++) {
const { target, path, value } = instructions[i]
let current = target
for (let i = path.length - 1; i > 0; i--) {
current = current[path[i]]
}
current[path[0]] = value
}
}
function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {
const target = get(o, path)
if (target == null) return
const keys = Object.keys(target)
const keysLength = keys.length
for (var i = 0; i < keysLength; i++) {
const key = keys[i]
specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)
}
return store
}
function has (obj, prop) {
return obj !== undefined && obj !== null
? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))
: false
}
function specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {
const afterPathLen = afterPath.length
const lastPathIndex = afterPathLen - 1
const originalKey = k
var i = -1
var n
var nv
var ov
var oov = null
var wc = null
var kIsWc
var wcov
var consecutive = false
var level = 0
// need to track depth of the `redactPath` tree
var depth = 0
var redactPathCurrent = tree()
ov = n = o[k]
if (typeof n !== 'object') return
while (n != null && ++i < afterPathLen) {
depth += 1
k = afterPath[i]
oov = ov
if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {
break
}
if (k === '*') {
if (wc === '*') {
consecutive = true
}
wc = k
if (i !== lastPathIndex) {
continue
}
}
if (wc) {
const wcKeys = Object.keys(n)
for (var j = 0; j < wcKeys.length; j++) {
const wck = wcKeys[j]
wcov = n[wck]
kIsWc = k === '*'
if (consecutive) {
redactPathCurrent = node(redactPathCurrent, wck, depth)
level = i
ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)
} else {
if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {
if (kIsWc) {
ov = wcov
} else {
ov = wcov[k]
}
nv = (i !== lastPathIndex)
? ov
: (isCensorFct
? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))
: censor)
if (kIsWc) {
const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])
store.push(rv)
n[wck] = nv
} else {
if (wcov[k] === nv) {
// pass
} else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {
redactPathCurrent = node(redactPathCurrent, wck, depth)
} else {
redactPathCurrent = node(redactPathCurrent, wck, depth)
const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])
store.push(rv)
wcov[k] = nv
}
}
}
}
}
wc = null
} else {
ov = n[k]
redactPathCurrent = node(redactPathCurrent, k, depth)
nv = (i !== lastPathIndex)
? ov
: (isCensorFct
? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))
: censor)
if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {
// pass
} else {
const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])
store.push(rv)
n[k] = nv
}
n = n[k]
}
if (typeof n !== 'object') break
// prevent circular structure, see https://github.com/pinojs/pino/issues/1513
if (ov === oov || typeof ov === 'undefined') {
// pass
}
}
}
function get (o, p) {
var i = -1
var l = p.length
var n = o
while (n != null && ++i < l) {
n = n[p[i]]
}
return n
}
function iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {
if (level === 0) {
if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {
if (kIsWc) {
ov = wcov
} else {
ov = wcov[k]
}
nv = (i !== lastPathIndex)
? ov
: (isCensorFct
? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))
: censor)
if (kIsWc) {
const rv = restoreInstr(redactPathCurrent, ov, parent)
store.push(rv)
n[wck] = nv
} else {
if (wcov[k] === nv) {
// pass
} else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {
// pass
} else {
const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)
store.push(rv)
wcov[k] = nv
}
}
}
}
for (const key in wcov) {
if (typeof wcov[key] === 'object') {
redactPathCurrent = node(redactPathCurrent, key, depth)
iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)
}
}
}
/**
* @typedef {object} TreeNode
* @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent
* @prop {string} key the key that this node represents (key here being part of the path being redacted
* @prop {TreeNode[]} children the child nodes of this node
* @prop {number} depth the depth of this node in the tree
*/
/**
* instantiate a new, empty tree
* @returns {TreeNode}
*/
function tree () {
return { parent: null, key: null, children: [], depth: 0 }
}
/**
* creates a new node in the tree, attaching it as a child of the provided parent node
* if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead
* @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this
* @param {string} key the key that the new node represents (key here being part of the path being redacted)
* @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node
* @returns {TreeNode} a reference to the newly created node in the tree
*/
function node (parent, key, depth) {
if (parent.depth === depth) {
return node(parent.parent, key, depth)
}
var child = {
parent,
key,
depth,
children: []
}
parent.children.push(child)
return child
}
/**
* @typedef {object} RestoreInstruction
* @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object
* @prop {*} value the value to restore
* @prop {object} target the object to restore the `value` in
*/
/**
* create a restore instruction for the given redactPath node
* generates a path in reverse order by walking up the redactPath tree
* @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore
* @param {*} value the value to restore
* @param {object} target a reference to the parent object to apply the restore instruction to
* @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object
*/
function restoreInstr (node, value, target) {
let current = node
const path = []
do {
path.push(current.key)
current = current.parent
} while (current.parent != null)
return { path, value, target }
}
/***/ }),
/***/ 96214:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const rx = __nccwpck_require__(9158)
module.exports = parse
function parse ({ paths }) {
const wildcards = []
var wcLen = 0
const secret = paths.reduce(function (o, strPath, ix) {
var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, ''))
const leadingBracket = strPath[0] === '['
path = path.map((p) => {
if (p[0] === '[') return p.substr(1, p.length - 2)
else return p
})
const star = path.indexOf('*')
if (star > -1) {
const before = path.slice(0, star)
const beforeStr = before.join('.')
const after = path.slice(star + 1, path.length)
const nested = after.length > 0
wcLen++
wildcards.push({
before,
beforeStr,
after,
nested
})
} else {
o[strPath] = {
path: path,
val: undefined,
precensored: false,
circle: '',
escPath: JSON.stringify(strPath),
leadingBracket: leadingBracket
}
}
return o
}, {})
return { wildcards, wcLen, secret }
}
/***/ }),
/***/ 17333:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const rx = __nccwpck_require__(9158)
module.exports = redactor
function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {
/* eslint-disable-next-line */
const redact = Function('o', `
if (typeof o !== 'object' || o == null) {
${strictImpl(strict, serialize)}
}
const { censor, secret } = this
const originalSecret = {}
const secretKeys = Object.keys(secret)
for (var i = 0; i < secretKeys.length; i++) {
originalSecret[secretKeys[i]] = secret[secretKeys[i]]
}
${redactTmpl(secret, isCensorFct, censorFctTakesPath)}
this.compileRestore()
${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}
this.secret = originalSecret
${resultTmpl(serialize)}
`).bind(state)
redact.state = state
if (serialize === false) {
redact.restore = (o) => state.restore(o)
}
return redact
}
function redactTmpl (secret, isCensorFct, censorFctTakesPath) {
return Object.keys(secret).map((path) => {
const { escPath, leadingBracket, path: arrPath } = secret[path]
const skip = leadingBracket ? 1 : 0
const delim = leadingBracket ? '' : '.'
const hops = []
var match
while ((match = rx.exec(path)) !== null) {
const [ , ix ] = match
const { index, input } = match
if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))
}
var existence = hops.map((p) => `o${delim}${p}`).join(' && ')
if (existence.length === 0) existence += `o${delim}${path} != null`
else existence += ` && o${delim}${path} != null`
const circularDetection = `
switch (true) {
${hops.reverse().map((p) => `
case o${delim}${p} === censor:
secret[${escPath}].circle = ${JSON.stringify(p)}
break
`).join('\n')}
}
`
const censorArgs = censorFctTakesPath
? `val, ${JSON.stringify(arrPath)}`
: `val`
return `
if (${existence}) {
const val = o${delim}${path}
if (val === censor) {
secret[${escPath}].precensored = true
} else {
secret[${escPath}].val = val
o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}
${circularDetection}
}
}
`
}).join('\n')
}
function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {
return hasWildcards === true ? `
{
const { wildcards, wcLen, groupRedact, nestedRedact } = this
for (var i = 0; i < wcLen; i++) {
const { before, beforeStr, after, nested } = wildcards[i]
if (nested === true) {
secret[beforeStr] = secret[beforeStr] || []
nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})
} else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})
}
}
` : ''
}
function resultTmpl (serialize) {
return serialize === false ? `return o` : `
var s = this.serialize(o)
this.restore(o)
return s
`
}
function strictImpl (strict, serialize) {
return strict === true
? `throw Error('fast-redact: primitives cannot be redacted')`
: serialize === false ? `return o` : `return this.serialize(o)`
}
/***/ }),
/***/ 98806:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { groupRestore, nestedRestore } = __nccwpck_require__(54865)
module.exports = restorer
function restorer () {
return function compileRestore () {
if (this.restore) {
this.restore.state.secret = this.secret
return
}
const { secret, wcLen } = this
const paths = Object.keys(secret)
const resetters = resetTmpl(secret, paths)
const hasWildcards = wcLen > 0
const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }
/* eslint-disable-next-line */
this.restore = Function(
'o',
restoreTmpl(resetters, paths, hasWildcards)
).bind(state)
this.restore.state = state
}
}
/**
* Mutates the original object to be censored by restoring its original values
* prior to censoring.
*
* @param {object} secret Compiled object describing which target fields should
* be censored and the field states.
* @param {string[]} paths The list of paths to censor as provided at
* initialization time.
*
* @returns {string} String of JavaScript to be used by `Function()`. The
* string compiles to the function that does the work in the description.
*/
function resetTmpl (secret, paths) {
return paths.map((path) => {
const { circle, escPath, leadingBracket } = secret[path]
const delim = leadingBracket ? '' : '.'
const reset = circle
? `o.${circle} = secret[${escPath}].val`
: `o${delim}${path} = secret[${escPath}].val`
const clear = `secret[${escPath}].val = undefined`
return `
if (secret[${escPath}].val !== undefined) {
try { ${reset} } catch (e) {}
${clear}
}
`
}).join('')
}
/**
* Creates the body of the restore function
*
* Restoration of the redacted object happens
* backwards, in reverse order of redactions,
* so that repeated redactions on the same object
* property can be eventually rolled back to the
* original value.
*
* This way dynamic redactions are restored first,
* starting from the last one working backwards and
* followed by the static ones.
*
* @returns {string} the body of the restore function
*/
function restoreTmpl (resetters, paths, hasWildcards) {
const dynamicReset = hasWildcards === true ? `
const keys = Object.keys(secret)
const len = keys.length
for (var i = len - 1; i >= ${paths.length}; i--) {
const k = keys[i]
const o = secret[k]
if (o) {
if (o.flat === true) this.groupRestore(o)
else this.nestedRestore(o)
secret[k] = null
}
}
` : ''
return `
const secret = this.secret
${dynamicReset}
${resetters}
return o
`
}
/***/ }),
/***/ 9158:
/***/ ((module) => {
"use strict";
module.exports = /[^.[\]]+|\[((?:.)*?)\]/g
/*
Regular expression explanation:
Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.)
opening square bracket ([) or closing square bracket (])
Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture
group (which will be capture group $1) that matches anything
within square brackets. Expansion is lazy so it will
stop matching as soon as the first closing bracket is met `]`
(rather than continuing to match until the final closing bracket).
*/
/***/ }),
/***/ 41012:
/***/ ((module) => {
"use strict";
module.exports = state
function state (o) {
const {
secret,
censor,
compileRestore,
serialize,
groupRedact,
nestedRedact,
wildcards,
wcLen
} = o
const builder = [{ secret, censor, compileRestore }]
if (serialize !== false) builder.push({ serialize })
if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })
return Object.assign(...builder)
}
/***/ }),
/***/ 74174:
/***/ ((module) => {
"use strict";
module.exports = validator
function validator (opts = {}) {
const {
ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',
ERR_INVALID_PATH = (s) => `fast-redact Invalid path (${s})`
} = opts
return function validate ({ paths }) {
paths.forEach((s) => {
if (typeof s !== 'string') {
throw Error(ERR_PATHS_MUST_BE_STRINGS())
}
try {
if (//.test(s)) throw Error()
const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '').replace(/\.\*/g, '.').replace(/\[\*\]/g, '[]')
if (/\n|\r|;/.test(expr)) throw Error()
if (/\/\*/.test(expr)) throw Error()
/* eslint-disable-next-line */
Function(`
'use strict'
const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });
const = null;
o${expr}
if ([o${expr}].length !== 1) throw Error()`)()
} catch (e) {
throw Error(ERR_INVALID_PATH(s))
}
})
}
}
/***/ }),
/***/ 7340:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint-disable no-var */
var reusify = __nccwpck_require__(32113)
function fastqueue (context, worker, _concurrency) {
if (typeof context === 'function') {
_concurrency = worker
worker = context
context = null
}
if (!(_concurrency >= 1)) {
throw new Error('fastqueue concurrency must be equal to or greater than 1')
}
var cache = reusify(Task)
var queueHead = null
var queueTail = null
var _running = 0
var errorHandler = null
var self = {
push: push,
drain: noop,
saturated: noop,
pause: pause,
paused: false,
get concurrency () {
return _concurrency
},
set concurrency (value) {
if (!(value >= 1)) {
throw new Error('fastqueue concurrency must be equal to or greater than 1')
}
_concurrency = value
if (self.paused) return
for (; queueHead && _running < _concurrency;) {
_running++
release()
}
},
running: running,
resume: resume,
idle: idle,
length: length,
getQueue: getQueue,
unshift: unshift,
empty: noop,
kill: kill,
killAndDrain: killAndDrain,
error: error
}
return self
function running () {
return _running
}
function pause () {
self.paused = true
}
function length () {
var current = queueHead
var counter = 0
while (current) {
current = current.next
counter++
}
return counter
}
function getQueue () {
var current = queueHead
var tasks = []
while (current) {
tasks.push(current.value)
current = current.next
}
return tasks
}
function resume () {
if (!self.paused) return
self.paused = false
if (queueHead === null) {
_running++
release()
return
}
for (; queueHead && _running < _concurrency;) {
_running++
release()
}
}
function idle () {
return _running === 0 && self.length() === 0
}
function push (value, done) {
var current = cache.get()
current.context = context
current.release = release
current.value = value
current.callback = done || noop
current.errorHandler = errorHandler
if (_running >= _concurrency || self.paused) {
if (queueTail) {
queueTail.next = current
queueTail = current
} else {
queueHead = current
queueTail = current
self.saturated()
}
} else {
_running++
worker.call(context, current.value, current.worked)
}
}
function unshift (value, done) {
var current = cache.get()
current.context = context
current.release = release
current.value = value
current.callback = done || noop
current.errorHandler = errorHandler
if (_running >= _concurrency || self.paused) {
if (queueHead) {
current.next = queueHead
queueHead = current
} else {
queueHead = current
queueTail = current
self.saturated()
}
} else {
_running++
worker.call(context, current.value, current.worked)
}
}
function release (holder) {
if (holder) {
cache.release(holder)
}
var next = queueHead
if (next && _running <= _concurrency) {
if (!self.paused) {
if (queueTail === queueHead) {
queueTail = null
}
queueHead = next.next
next.next = null
worker.call(context, next.value, next.worked)
if (queueTail === null) {
self.empty()
}
} else {
_running--
}
} else if (--_running === 0) {
self.drain()
}
}
function kill () {
queueHead = null
queueTail = null
self.drain = noop
}
function killAndDrain () {
queueHead = null
queueTail = null
self.drain()
self.drain = noop
}
function error (handler) {
errorHandler = handler
}
}
function noop () {}
function Task () {
this.value = null
this.callback = noop
this.next = null
this.release = noop
this.context = null
this.errorHandler = null
var self = this
this.worked = function worked (err, result) {
var callback = self.callback
var errorHandler = self.errorHandler
var val = self.value
self.value = null
self.callback = noop
if (self.errorHandler) {
errorHandler(err, val)
}
callback.call(self.context, err, result)
self.release(self)
}
}
function queueAsPromised (context, worker, _concurrency) {
if (typeof context === 'function') {
_concurrency = worker
worker = context
context = null
}
function asyncWrapper (arg, cb) {
worker.call(this, arg)
.then(function (res) {
cb(null, res)
}, cb)
}
var queue = fastqueue(context, asyncWrapper, _concurrency)
var pushCb = queue.push
var unshiftCb = queue.unshift
queue.push = push
queue.unshift = unshift
queue.drained = drained
return queue
function push (value) {
var p = new Promise(function (resolve, reject) {
pushCb(value, function (err, result) {
if (err) {
reject(err)
return
}
resolve(result)
})
})
// Let's fork the promise chain to
// make the error bubble up to the user but
// not lead to a unhandledRejection
p.catch(noop)
return p
}
function unshift (value) {
var p = new Promise(function (resolve, reject) {
unshiftCb(value, function (err, result) {
if (err) {
reject(err)
return
}
resolve(result)
})
})
// Let's fork the promise chain to
// make the error bubble up to the user but
// not lead to a unhandledRejection
p.catch(noop)
return p
}
function drained () {
if (queue.idle()) {
return new Promise(function (resolve) {
resolve()
})
}
var previousDrain = queue.drain
var p = new Promise(function (resolve) {
queue.drain = function () {
previousDrain()
resolve()
}
})
return p
}
}
module.exports = fastqueue
module.exports.promise = queueAsPromised
/***/ }),
/***/ 72026:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/*
Char codes:
'!': 33 - !
'#': 35 - %23
'$': 36 - %24
'%': 37 - %25
'&': 38 - %26
''': 39 - '
'(': 40 - (
')': 41 - )
'*': 42 - *
'+': 43 - %2B
',': 44 - %2C
'-': 45 - -
'.': 46 - .
'/': 47 - %2F
':': 58 - %3A
';': 59 - %3B
'=': 61 - %3D
'?': 63 - %3F
'@': 64 - %40
'_': 95 - _
'~': 126 - ~
*/
const assert = __nccwpck_require__(98061)
const querystring = __nccwpck_require__(35224)
const isRegexSafe = __nccwpck_require__(4905)
const deepEqual = __nccwpck_require__(28206)
const { prettyPrintTree } = __nccwpck_require__(62569)
const { StaticNode, NODE_TYPES } = __nccwpck_require__(60609)
const Constrainer = __nccwpck_require__(76791)
const httpMethods = __nccwpck_require__(2916)
const httpMethodStrategy = __nccwpck_require__(24116)
const { safeDecodeURI, safeDecodeURIComponent } = __nccwpck_require__(43436)
const FULL_PATH_REGEXP = /^https?:\/\/.*?\//
const OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/
if (!isRegexSafe(FULL_PATH_REGEXP)) {
throw new Error('the FULL_PATH_REGEXP is not safe, update this module')
}
if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) {
throw new Error('the OPTIONAL_PARAM_REGEXP is not safe, update this module')
}
function Router (opts) {
if (!(this instanceof Router)) {
return new Router(opts)
}
opts = opts || {}
this._opts = opts
if (opts.defaultRoute) {
assert(typeof opts.defaultRoute === 'function', 'The default route must be a function')
this.defaultRoute = opts.defaultRoute
} else {
this.defaultRoute = null
}
if (opts.onBadUrl) {
assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function')
this.onBadUrl = opts.onBadUrl
} else {
this.onBadUrl = null
}
if (opts.buildPrettyMeta) {
assert(typeof opts.buildPrettyMeta === 'function', 'buildPrettyMeta must be a function')
this.buildPrettyMeta = opts.buildPrettyMeta
} else {
this.buildPrettyMeta = defaultBuildPrettyMeta
}
if (opts.querystringParser) {
assert(typeof opts.querystringParser === 'function', 'querystringParser must be a function')
this.querystringParser = opts.querystringParser
} else {
this.querystringParser = (query) => query === '' ? {} : querystring.parse(query)
}
this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive
this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false
this.ignoreDuplicateSlashes = opts.ignoreDuplicateSlashes || false
this.maxParamLength = opts.maxParamLength || 100
this.allowUnsafeRegex = opts.allowUnsafeRegex || false
this.constrainer = new Constrainer(opts.constraints)
this.useSemicolonDelimiter = opts.useSemicolonDelimiter || false
this.routes = []
this.trees = {}
}
Router.prototype.on = function on (method, path, opts, handler, store) {
if (typeof opts === 'function') {
if (handler !== undefined) {
store = handler
}
handler = opts
opts = {}
}
// path validation
assert(typeof path === 'string', 'Path should be a string')
assert(path.length > 0, 'The path could not be empty')
assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`')
// handler validation
assert(typeof handler === 'function', 'Handler should be a function')
// path ends with optional parameter
const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP)
if (optionalParamMatch) {
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')
const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2') || '/'
this.on(method, pathFull, opts, handler, store)
this.on(method, pathOptional, opts, handler, store)
return
}
const route = path
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const methods = Array.isArray(method) ? method : [method]
for (const method of methods) {
assert(typeof method === 'string', 'Method should be a string')
assert(httpMethods.includes(method), `Method '${method}' is not an http method.`)
this._on(method, path, opts, handler, store, route)
}
}
Router.prototype._on = function _on (method, path, opts, handler, store) {
let constraints = {}
if (opts.constraints !== undefined) {
assert(typeof opts.constraints === 'object' && opts.constraints !== null, 'Constraints should be an object')
if (Object.keys(opts.constraints).length !== 0) {
constraints = opts.constraints
}
}
this.constrainer.validateConstraints(constraints)
// Let the constrainer know if any constraints are being used now
this.constrainer.noteUsage(constraints)
// Boot the tree for this method if it doesn't exist yet
if (this.trees[method] === undefined) {
this.trees[method] = new StaticNode('/')
}
let pattern = path
if (pattern === '*' && this.trees[method].prefix.length !== 0) {
const currentRoot = this.trees[method]
this.trees[method] = new StaticNode('')
this.trees[method].staticChildren['/'] = currentRoot
}
let currentNode = this.trees[method]
let parentNodePathIndex = currentNode.prefix.length
const params = []
for (let i = 0; i <= pattern.length; i++) {
if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {
// It's a double colon
i++
continue
}
const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58
const isWildcardNode = pattern.charCodeAt(i) === 42
if (isParametricNode || isWildcardNode || (i === pattern.length && i !== parentNodePathIndex)) {
let staticNodePath = pattern.slice(parentNodePathIndex, i)
if (!this.caseSensitive) {
staticNodePath = staticNodePath.toLowerCase()
}
staticNodePath = staticNodePath.split('::').join(':')
staticNodePath = staticNodePath.split('%').join('%25')
// add the static part of the route to the tree
currentNode = currentNode.createStaticChild(staticNodePath)
}
if (isParametricNode) {
let isRegexNode = false
const regexps = []
let lastParamStartIndex = i + 1
for (let j = lastParamStartIndex; ; j++) {
const charCode = pattern.charCodeAt(j)
const isRegexParam = charCode === 40
const isStaticPart = charCode === 45 || charCode === 46
const isEndOfNode = charCode === 47 || j === pattern.length
if (isRegexParam || isStaticPart || isEndOfNode) {
const paramName = pattern.slice(lastParamStartIndex, j)
params.push(paramName)
isRegexNode = isRegexNode || isRegexParam || isStaticPart
if (isRegexParam) {
const endOfRegexIndex = getClosingParenthensePosition(pattern, j)
const regexString = pattern.slice(j, endOfRegexIndex + 1)
if (!this.allowUnsafeRegex) {
assert(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`)
}
regexps.push(trimRegExpStartAndEnd(regexString))
j = endOfRegexIndex + 1
} else {
regexps.push('(.*?)')
}
const staticPartStartIndex = j
for (; j < pattern.length; j++) {
const charCode = pattern.charCodeAt(j)
if (charCode === 47) break
if (charCode === 58) {
const nextCharCode = pattern.charCodeAt(j + 1)
if (nextCharCode === 58) j++
else break
}
}
let staticPart = pattern.slice(staticPartStartIndex, j)
if (staticPart) {
staticPart = staticPart.split('::').join(':')
staticPart = staticPart.split('%').join('%25')
regexps.push(escapeRegExp(staticPart))
}
lastParamStartIndex = j + 1
if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {
const nodePattern = isRegexNode ? '()' + staticPart : staticPart
const nodePath = pattern.slice(i, j)
pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j)
i += nodePattern.length
const regex = isRegexNode ? new RegExp('^' + regexps.join('') + '$') : null
currentNode = currentNode.createParametricChild(regex, staticPart || null, nodePath)
parentNodePathIndex = i + 1
break
}
}
}
} else if (isWildcardNode) {
// add the wildcard parameter
params.push('*')
currentNode = currentNode.createWildcardChild()
parentNodePathIndex = i + 1
if (i !== pattern.length - 1) {
throw new Error('Wildcard must be the last character in the route')
}
}
}
if (!this.caseSensitive) {
pattern = pattern.toLowerCase()
}
if (pattern === '*') {
pattern = '/*'
}
for (const existRoute of this.routes) {
const routeConstraints = existRoute.opts.constraints || {}
if (
existRoute.method === method &&
existRoute.pattern === pattern &&
deepEqual(routeConstraints, constraints)
) {
throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`)
}
}
const route = { method, path, pattern, params, opts, handler, store }
this.routes.push(route)
currentNode.addRoute(route, this.constrainer)
}
Router.prototype.hasRoute = function hasRoute (method, path, constraints) {
const route = this.findRoute(method, path, constraints)
return route !== null
}
Router.prototype.findRoute = function findNode (method, path, constraints = {}) {
if (this.trees[method] === undefined) {
return null
}
let pattern = path
let currentNode = this.trees[method]
let parentNodePathIndex = currentNode.prefix.length
const params = []
for (let i = 0; i <= pattern.length; i++) {
if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {
// It's a double colon
i++
continue
}
const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58
const isWildcardNode = pattern.charCodeAt(i) === 42
if (isParametricNode || isWildcardNode || (i === pattern.length && i !== parentNodePathIndex)) {
let staticNodePath = pattern.slice(parentNodePathIndex, i)
if (!this.caseSensitive) {
staticNodePath = staticNodePath.toLowerCase()
}
staticNodePath = staticNodePath.split('::').join(':')
staticNodePath = staticNodePath.split('%').join('%25')
// add the static part of the route to the tree
currentNode = currentNode.getStaticChild(staticNodePath)
if (currentNode === null) {
return null
}
}
if (isParametricNode) {
let isRegexNode = false
const regexps = []
let lastParamStartIndex = i + 1
for (let j = lastParamStartIndex; ; j++) {
const charCode = pattern.charCodeAt(j)
const isRegexParam = charCode === 40
const isStaticPart = charCode === 45 || charCode === 46
const isEndOfNode = charCode === 47 || j === pattern.length
if (isRegexParam || isStaticPart || isEndOfNode) {
const paramName = pattern.slice(lastParamStartIndex, j)
params.push(paramName)
isRegexNode = isRegexNode || isRegexParam || isStaticPart
if (isRegexParam) {
const endOfRegexIndex = getClosingParenthensePosition(pattern, j)
const regexString = pattern.slice(j, endOfRegexIndex + 1)
if (!this.allowUnsafeRegex) {
assert(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`)
}
regexps.push(trimRegExpStartAndEnd(regexString))
j = endOfRegexIndex + 1
} else {
regexps.push('(.*?)')
}
const staticPartStartIndex = j
for (; j < pattern.length; j++) {
const charCode = pattern.charCodeAt(j)
if (charCode === 47) break
if (charCode === 58) {
const nextCharCode = pattern.charCodeAt(j + 1)
if (nextCharCode === 58) j++
else break
}
}
let staticPart = pattern.slice(staticPartStartIndex, j)
if (staticPart) {
staticPart = staticPart.split('::').join(':')
staticPart = staticPart.split('%').join('%25')
regexps.push(escapeRegExp(staticPart))
}
lastParamStartIndex = j + 1
if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {
const nodePattern = isRegexNode ? '()' + staticPart : staticPart
const nodePath = pattern.slice(i, j)
pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j)
i += nodePattern.length
const regex = isRegexNode ? new RegExp('^' + regexps.join('') + '$') : null
currentNode = currentNode.getParametricChild(regex, staticPart || null, nodePath)
if (currentNode === null) {
return null
}
parentNodePathIndex = i + 1
break
}
}
}
} else if (isWildcardNode) {
// add the wildcard parameter
params.push('*')
currentNode = currentNode.getWildcardChild()
parentNodePathIndex = i + 1
if (i !== pattern.length - 1) {
throw new Error('Wildcard must be the last character in the route')
}
}
}
if (!this.caseSensitive) {
pattern = pattern.toLowerCase()
}
for (const existRoute of this.routes) {
const routeConstraints = existRoute.opts.constraints || {}
if (
existRoute.method === method &&
existRoute.pattern === pattern &&
deepEqual(routeConstraints, constraints)
) {
return {
handler: existRoute.handler,
store: existRoute.store,
params: existRoute.params
}
}
}
return null
}
Router.prototype.hasConstraintStrategy = function (strategyName) {
return this.constrainer.hasConstraintStrategy(strategyName)
}
Router.prototype.addConstraintStrategy = function (constraints) {
this.constrainer.addConstraintStrategy(constraints)
this._rebuild(this.routes)
}
Router.prototype.reset = function reset () {
this.trees = {}
this.routes = []
}
Router.prototype.off = function off (method, path, constraints) {
// path validation
assert(typeof path === 'string', 'Path should be a string')
assert(path.length > 0, 'The path could not be empty')
assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`')
// options validation
assert(
typeof constraints === 'undefined' ||
(typeof constraints === 'object' && !Array.isArray(constraints) && constraints !== null),
'Constraints should be an object or undefined.')
// path ends with optional parameter
const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP)
if (optionalParamMatch) {
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')
const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2')
this.off(method, pathFull, constraints)
this.off(method, pathOptional, constraints)
return
}
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const methods = Array.isArray(method) ? method : [method]
for (const method of methods) {
this._off(method, path, constraints)
}
}
Router.prototype._off = function _off (method, path, constraints) {
// method validation
assert(typeof method === 'string', 'Method should be a string')
assert(httpMethods.includes(method), `Method '${method}' is not an http method.`)
function matcherWithoutConstraints (route) {
return method !== route.method || path !== route.path
}
function matcherWithConstraints (route) {
return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {})
}
const predicate = constraints ? matcherWithConstraints : matcherWithoutConstraints
// Rebuild tree without the specific route
const newRoutes = this.routes.filter(predicate)
this._rebuild(newRoutes)
}
Router.prototype.lookup = function lookup (req, res, ctx, done) {
if (typeof ctx === 'function') {
done = ctx
ctx = undefined
}
if (done === undefined) {
const constraints = this.constrainer.deriveConstraints(req, ctx)
const handle = this.find(req.method, req.url, constraints)
return this.callHandler(handle, req, res, ctx)
}
this.constrainer.deriveConstraints(req, ctx, (err, constraints) => {
if (err !== null) {
done(err)
return
}
try {
const handle = this.find(req.method, req.url, constraints)
const result = this.callHandler(handle, req, res, ctx)
done(null, result)
} catch (err) {
done(err)
}
})
}
Router.prototype.callHandler = function callHandler (handle, req, res, ctx) {
if (handle === null) return this._defaultRoute(req, res, ctx)
return ctx === undefined
? handle.handler(req, res, handle.params, handle.store, handle.searchParams)
: handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams)
}
Router.prototype.find = function find (method, path, derivedConstraints) {
let currentNode = this.trees[method]
if (currentNode === undefined) return null
if (path.charCodeAt(0) !== 47) { // 47 is '/'
path = path.replace(FULL_PATH_REGEXP, '/')
}
// This must be run before sanitizeUrl as the resulting function
// .sliceParameter must be constructed with same URL string used
// throughout the rest of this function.
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
let sanitizedUrl
let querystring
let shouldDecodeParam
try {
sanitizedUrl = safeDecodeURI(path, this.useSemicolonDelimiter)
path = sanitizedUrl.path
querystring = sanitizedUrl.querystring
shouldDecodeParam = sanitizedUrl.shouldDecodeParam
} catch (error) {
return this._onBadUrl(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const originPath = path
if (this.caseSensitive === false) {
path = path.toLowerCase()
}
const maxParamLength = this.maxParamLength
let pathIndex = currentNode.prefix.length
const params = []
const pathLen = path.length
const brothersNodesStack = []
while (true) {
if (pathIndex === pathLen && currentNode.isLeafNode) {
const handle = currentNode.handlerStorage.getMatchingHandler(derivedConstraints)
if (handle !== null) {
return {
handler: handle.handler,
store: handle.store,
params: handle._createParamsObject(params),
searchParams: this.querystringParser(querystring)
}
}
}
let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length)
if (node === null) {
if (brothersNodesStack.length === 0) {
return null
}
const brotherNodeState = brothersNodesStack.pop()
pathIndex = brotherNodeState.brotherPathIndex
params.splice(brotherNodeState.paramsCount)
node = brotherNodeState.brotherNode
}
currentNode = node
// static route
if (currentNode.kind === NODE_TYPES.STATIC) {
pathIndex += currentNode.prefix.length
continue
}
if (currentNode.kind === NODE_TYPES.WILDCARD) {
let param = originPath.slice(pathIndex)
if (shouldDecodeParam) {
param = safeDecodeURIComponent(param)
}
params.push(param)
pathIndex = pathLen
continue
}
// parametric node
let paramEndIndex = originPath.indexOf('/', pathIndex)
if (paramEndIndex === -1) {
paramEndIndex = pathLen
}
let param = originPath.slice(pathIndex, paramEndIndex)
if (shouldDecodeParam) {
param = safeDecodeURIComponent(param)
}
if (currentNode.isRegex) {
const matchedParameters = currentNode.regex.exec(param)
if (matchedParameters === null) continue
for (let i = 1; i < matchedParameters.length; i++) {
const matchedParam = matchedParameters[i]
if (matchedParam.length > maxParamLength) {
return null
}
params.push(matchedParam)
}
} else {
if (param.length > maxParamLength) {
return null
}
params.push(param)
}
pathIndex = paramEndIndex
}
}
Router.prototype._rebuild = function (routes) {
this.reset()
for (const route of routes) {
const { method, path, opts, handler, store } = route
this._on(method, path, opts, handler, store)
}
}
Router.prototype._defaultRoute = function (req, res, ctx) {
if (this.defaultRoute !== null) {
return ctx === undefined
? this.defaultRoute(req, res)
: this.defaultRoute.call(ctx, req, res)
} else {
res.statusCode = 404
res.end()
}
}
Router.prototype._onBadUrl = function (path) {
if (this.onBadUrl === null) {
return null
}
const onBadUrl = this.onBadUrl
return {
handler: (req, res, ctx) => onBadUrl(path, req, res),
params: {},
store: null
}
}
Router.prototype.prettyPrint = function (options = {}) {
const method = options.method
options.buildPrettyMeta = this.buildPrettyMeta.bind(this)
let tree = null
if (method === undefined) {
const { version, host, ...constraints } = this.constrainer.strategies
constraints[httpMethodStrategy.name] = httpMethodStrategy
const mergedRouter = new Router({ ...this._opts, constraints })
const mergedRoutes = this.routes.map(route => {
const constraints = {
...route.opts.constraints,
[httpMethodStrategy.name]: route.method
}
return { ...route, method: 'MERGED', opts: { constraints } }
})
mergedRouter._rebuild(mergedRoutes)
tree = mergedRouter.trees.MERGED
} else {
tree = this.trees[method]
}
if (tree == null) return '(empty tree)'
return prettyPrintTree(tree, options)
}
for (const i in httpMethods) {
/* eslint no-prototype-builtins: "off" */
if (!httpMethods.hasOwnProperty(i)) continue
const m = httpMethods[i]
const methodName = m.toLowerCase()
Router.prototype[methodName] = function (path, handler, store) {
return this.on(m, path, handler, store)
}
}
Router.prototype.all = function (path, handler, store) {
this.on(httpMethods, path, handler, store)
}
module.exports = Router
function escapeRegExp (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function removeDuplicateSlashes (path) {
return path.replace(/\/\/+/g, '/')
}
function trimLastSlash (path) {
if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) {
return path.slice(0, -1)
}
return path
}
function trimRegExpStartAndEnd (regexString) {
// removes chars that marks start "^" and end "$" of regexp
if (regexString.charCodeAt(1) === 94) {
regexString = regexString.slice(0, 1) + regexString.slice(2)
}
if (regexString.charCodeAt(regexString.length - 2) === 36) {
regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1)
}
return regexString
}
function getClosingParenthensePosition (path, idx) {
// `path.indexOf()` will always return the first position of the closing parenthese,
// but it's inefficient for grouped or wrong regexp expressions.
// see issues #62 and #63 for more info
let parentheses = 1
while (idx < path.length) {
idx++
// ignore skipped chars
if (path[idx] === '\\') {
idx++
continue
}
if (path[idx] === ')') {
parentheses--
} else if (path[idx] === '(') {
parentheses++
}
if (!parentheses) return idx
}
throw new TypeError('Invalid regexp expression in "' + path + '"')
}
function defaultBuildPrettyMeta (route) {
// buildPrettyMeta function must return an object, which will be parsed into key/value pairs for display
if (!route) return {}
if (!route.store) return {}
return Object.assign({}, route.store)
}
/***/ }),
/***/ 76791:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const acceptVersionStrategy = __nccwpck_require__(30517)
const acceptHostStrategy = __nccwpck_require__(46739)
const assert = __nccwpck_require__(98061)
class Constrainer {
constructor (customStrategies) {
this.strategies = {
version: acceptVersionStrategy,
host: acceptHostStrategy
}
this.strategiesInUse = new Set()
this.asyncStrategiesInUse = new Set()
// validate and optimize prototypes of given custom strategies
if (customStrategies) {
for (const strategy of Object.values(customStrategies)) {
this.addConstraintStrategy(strategy)
}
}
}
isStrategyUsed (strategyName) {
return this.strategiesInUse.has(strategyName) ||
this.asyncStrategiesInUse.has(strategyName)
}
hasConstraintStrategy (strategyName) {
const customConstraintStrategy = this.strategies[strategyName]
if (customConstraintStrategy !== undefined) {
return customConstraintStrategy.isCustom ||
this.isStrategyUsed(strategyName)
}
return false
}
addConstraintStrategy (strategy) {
assert(typeof strategy.name === 'string' && strategy.name !== '', 'strategy.name is required.')
assert(strategy.storage && typeof strategy.storage === 'function', 'strategy.storage function is required.')
assert(strategy.deriveConstraint && typeof strategy.deriveConstraint === 'function', 'strategy.deriveConstraint function is required.')
if (this.strategies[strategy.name] && this.strategies[strategy.name].isCustom) {
throw new Error(`There already exists a custom constraint with the name ${strategy.name}.`)
}
if (this.isStrategyUsed(strategy.name)) {
throw new Error(`There already exists a route with ${strategy.name} constraint.`)
}
strategy.isCustom = true
strategy.isAsync = strategy.deriveConstraint.length === 3
this.strategies[strategy.name] = strategy
if (strategy.mustMatchWhenDerived) {
this.noteUsage({ [strategy.name]: strategy })
}
}
deriveConstraints (req, ctx, done) {
const constraints = this.deriveSyncConstraints(req, ctx)
if (done === undefined) {
return constraints
}
this.deriveAsyncConstraints(constraints, req, ctx, done)
}
deriveSyncConstraints (req, ctx) {
return undefined
}
// When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used.
noteUsage (constraints) {
if (constraints) {
const beforeSize = this.strategiesInUse.size
for (const key in constraints) {
const strategy = this.strategies[key]
if (strategy.isAsync) {
this.asyncStrategiesInUse.add(key)
} else {
this.strategiesInUse.add(key)
}
}
if (beforeSize !== this.strategiesInUse.size) {
this._buildDeriveConstraints()
}
}
}
newStoreForConstraint (constraint) {
if (!this.strategies[constraint]) {
throw new Error(`No strategy registered for constraint key ${constraint}`)
}
return this.strategies[constraint].storage()
}
validateConstraints (constraints) {
for (const key in constraints) {
const value = constraints[key]
if (typeof value === 'undefined') {
throw new Error('Can\'t pass an undefined constraint value, must pass null or no key at all')
}
const strategy = this.strategies[key]
if (!strategy) {
throw new Error(`No strategy registered for constraint key ${key}`)
}
if (strategy.validate) {
strategy.validate(value)
}
}
}
deriveAsyncConstraints (constraints, req, ctx, done) {
let asyncConstraintsCount = this.asyncStrategiesInUse.size
if (asyncConstraintsCount === 0) {
done(null, constraints)
return
}
constraints = constraints || {}
for (const key of this.asyncStrategiesInUse) {
const strategy = this.strategies[key]
strategy.deriveConstraint(req, ctx, (err, constraintValue) => {
if (err !== null) {
done(err)
return
}
constraints[key] = constraintValue
if (--asyncConstraintsCount === 0) {
done(null, constraints)
}
})
}
}
// Optimization: build a fast function for deriving the constraints for all the strategies at once. We inline the definitions of the version constraint and the host constraint for performance.
// If no constraining strategies are in use (no routes constrain on host, or version, or any custom strategies) then we don't need to derive constraints for each route match, so don't do anything special, and just return undefined
// This allows us to not allocate an object to hold constraint values if no constraints are defined.
_buildDeriveConstraints () {
if (this.strategiesInUse.size === 0) return
const lines = ['return {']
for (const key of this.strategiesInUse) {
const strategy = this.strategies[key]
// Optimization: inline the derivation for the common built in constraints
if (!strategy.isCustom) {
if (key === 'version') {
lines.push(' version: req.headers[\'accept-version\'],')
} else {
lines.push(' host: req.headers.host || req.headers[\':authority\'],')
}
} else {
lines.push(` ${strategy.name}: this.strategies.${key}.deriveConstraint(req, ctx),`)
}
}
lines.push('}')
this.deriveSyncConstraints = new Function('req', 'ctx', lines.join('\n')).bind(this) // eslint-disable-line
}
}
module.exports = Constrainer
/***/ }),
/***/ 33094:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const httpMethodStrategy = __nccwpck_require__(24116)
class HandlerStorage {
constructor () {
this.unconstrainedHandler = null // optimized reference to the handler that will match most of the time
this.constraints = []
this.handlers = [] // unoptimized list of handler objects for which the fast matcher function will be compiled
this.constrainedHandlerStores = null
}
// This is the hot path for node handler finding -- change with care!
getMatchingHandler (derivedConstraints) {
if (derivedConstraints === undefined) {
return this.unconstrainedHandler
}
return this._getHandlerMatchingConstraints(derivedConstraints)
}
addHandler (constrainer, route) {
const params = route.params
const constraints = route.opts.constraints || {}
const handlerObject = {
params,
constraints,
handler: route.handler,
store: route.store || null,
_createParamsObject: this._compileCreateParamsObject(params)
}
const constraintsNames = Object.keys(constraints)
if (constraintsNames.length === 0) {
this.unconstrainedHandler = handlerObject
}
for (const constraint of constraintsNames) {
if (!this.constraints.includes(constraint)) {
if (constraint === 'version') {
// always check the version constraint first as it is the most selective
this.constraints.unshift(constraint)
} else {
this.constraints.push(constraint)
}
}
}
const isMergedTree = constraintsNames.includes(httpMethodStrategy.name)
if (!isMergedTree && this.handlers.length >= 31) {
throw new Error('find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached')
}
this.handlers.push(handlerObject)
// Sort the most constrained handlers to the front of the list of handlers so they are tested first.
this.handlers.sort((a, b) => Object.keys(a.constraints).length - Object.keys(b.constraints).length)
if (!isMergedTree) {
this._compileGetHandlerMatchingConstraints(constrainer, constraints)
}
}
_compileCreateParamsObject (params) {
const lines = []
for (let i = 0; i < params.length; i++) {
lines.push(`'${params[i]}': paramsArray[${i}]`)
}
return new Function('paramsArray', `return {${lines.join(',')}}`) // eslint-disable-line
}
_getHandlerMatchingConstraints () {
return null
}
// Builds a store object that maps from constraint values to a bitmap of handler indexes which pass the constraint for a value
// So for a host constraint, this might look like { "fastify.io": 0b0010, "google.ca": 0b0101 }, meaning the 3rd handler is constrainted to fastify.io, and the 2nd and 4th handlers are constrained to google.ca.
// The store's implementation comes from the strategies provided to the Router.
_buildConstraintStore (store, constraint) {
for (let i = 0; i < this.handlers.length; i++) {
const handler = this.handlers[i]
const constraintValue = handler.constraints[constraint]
if (constraintValue !== undefined) {
let indexes = store.get(constraintValue) || 0
indexes |= 1 << i // set the i-th bit for the mask because this handler is constrained by this value https://stackoverflow.com/questions/1436438/how-do-you-set-clear-and-toggle-a-single-bit-in-javascrip
store.set(constraintValue, indexes)
}
}
}
// Builds a bitmask for a given constraint that has a bit for each handler index that is 0 when that handler *is* constrained and 1 when the handler *isnt* constrainted. This is opposite to what might be obvious, but is just for convienience when doing the bitwise operations.
_constrainedIndexBitmask (constraint) {
let mask = 0
for (let i = 0; i < this.handlers.length; i++) {
const handler = this.handlers[i]
const constraintValue = handler.constraints[constraint]
if (constraintValue !== undefined) {
mask |= 1 << i
}
}
return ~mask
}
// Compile a fast function to match the handlers for this node
// The function implements a general case multi-constraint matching algorithm.
// The general idea is this: we have a bunch of handlers, each with a potentially different set of constraints, and sometimes none at all. We're given a list of constraint values and we have to use the constraint-value-comparison strategies to see which handlers match the constraint values passed in.
// We do this by asking each constraint store which handler indexes match the given constraint value for each store. Trickily, the handlers that a store says match are the handlers constrained by that store, but handlers that aren't constrained at all by that store could still match just fine. So, each constraint store can only describe matches for it, and it won't have any bearing on the handlers it doesn't care about. For this reason, we have to ask each stores which handlers match and track which have been matched (or not cared about) by all of them.
// We use bitmaps to represent these lists of matches so we can use bitwise operations to implement this efficiently. Bitmaps are cheap to allocate, let us implement this masking behaviour in one CPU instruction, and are quite compact in memory. We start with a bitmap set to all 1s representing every handler that is a match candidate, and then for each constraint, see which handlers match using the store, and then mask the result by the mask of handlers that that store applies to, and bitwise AND with the candidate list. Phew.
// We consider all this compiling function complexity to be worth it, because the naive implementation that just loops over the handlers asking which stores match is quite a bit slower.
_compileGetHandlerMatchingConstraints (constrainer) {
this.constrainedHandlerStores = {}
for (const constraint of this.constraints) {
const store = constrainer.newStoreForConstraint(constraint)
this.constrainedHandlerStores[constraint] = store
this._buildConstraintStore(store, constraint)
}
const lines = []
lines.push(`
let candidates = ${(1 << this.handlers.length) - 1}
let mask, matches
`)
for (const constraint of this.constraints) {
// Setup the mask for indexes this constraint applies to. The mask bits are set to 1 for each position if the constraint applies.
lines.push(`
mask = ${this._constrainedIndexBitmask(constraint)}
value = derivedConstraints.${constraint}
`)
// If there's no constraint value, none of the handlers constrained by this constraint can match. Remove them from the candidates.
// If there is a constraint value, get the matching indexes bitmap from the store, and mask it down to only the indexes this constraint applies to, and then bitwise and with the candidates list to leave only matching candidates left.
const strategy = constrainer.strategies[constraint]
const matchMask = strategy.mustMatchWhenDerived ? 'matches' : '(matches | mask)'
lines.push(`
if (value === undefined) {
candidates &= mask
} else {
matches = this.constrainedHandlerStores.${constraint}.get(value) || 0
candidates &= ${matchMask}
}
if (candidates === 0) return null;
`)
}
// There are some constraints that can be derived and marked as "must match", where if they are derived, they only match routes that actually have a constraint on the value, like the SemVer version constraint.
// An example: a request comes in for version 1.x, and this node has a handler that matches the path, but there's no version constraint. For SemVer, the find-my-way semantics do not match this handler to that request.
// This function is used by Nodes with handlers to match when they don't have any constrained routes to exclude request that do have must match derived constraints present.
for (const constraint in constrainer.strategies) {
const strategy = constrainer.strategies[constraint]
if (strategy.mustMatchWhenDerived && !this.constraints.includes(constraint)) {
lines.push(`if (derivedConstraints.${constraint} !== undefined) return null`)
}
}
// Return the first handler who's bit is set in the candidates https://stackoverflow.com/questions/18134985/how-to-find-index-of-first-set-bit
lines.push('return this.handlers[Math.floor(Math.log2(candidates))]')
this._getHandlerMatchingConstraints = new Function('derivedConstraints', lines.join('\n')) // eslint-disable-line
}
}
module.exports = HandlerStorage
/***/ }),
/***/ 2916:
/***/ ((module) => {
"use strict";
// defined by Node.js http module, a snapshot from Node.js 18.12.0
const httpMethods = [
'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE',
'GET', 'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE',
'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS',
'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT',
'REBIND', 'REPORT', 'SEARCH', 'SOURCE', 'SUBSCRIBE', 'TRACE',
'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE'
]
module.exports = httpMethods
/***/ }),
/***/ 60609:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const HandlerStorage = __nccwpck_require__(33094)
const NODE_TYPES = {
STATIC: 0,
PARAMETRIC: 1,
WILDCARD: 2
}
class Node {
constructor () {
this.isLeafNode = false
this.routes = null
this.handlerStorage = null
}
addRoute (route, constrainer) {
if (this.routes === null) {
this.routes = []
}
if (this.handlerStorage === null) {
this.handlerStorage = new HandlerStorage()
}
this.isLeafNode = true
this.routes.push(route)
this.handlerStorage.addHandler(constrainer, route)
}
}
class ParentNode extends Node {
constructor () {
super()
this.staticChildren = {}
}
findStaticMatchingChild (path, pathIndex) {
const staticChild = this.staticChildren[path.charAt(pathIndex)]
if (staticChild === undefined || !staticChild.matchPrefix(path, pathIndex)) {
return null
}
return staticChild
}
getStaticChild (path, pathIndex = 0) {
if (path.length === pathIndex) {
return this
}
const staticChild = this.findStaticMatchingChild(path, pathIndex)
if (staticChild) {
return staticChild.getStaticChild(path, pathIndex + staticChild.prefix.length)
}
return null
}
createStaticChild (path) {
if (path.length === 0) {
return this
}
let staticChild = this.staticChildren[path.charAt(0)]
if (staticChild) {
let i = 1
for (; i < staticChild.prefix.length; i++) {
if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
staticChild = staticChild.split(this, i)
break
}
}
return staticChild.createStaticChild(path.slice(i))
}
const label = path.charAt(0)
this.staticChildren[label] = new StaticNode(path)
return this.staticChildren[label]
}
}
class StaticNode extends ParentNode {
constructor (prefix) {
super()
this.prefix = prefix
this.wildcardChild = null
this.parametricChildren = []
this.kind = NODE_TYPES.STATIC
this._compilePrefixMatch()
}
getParametricChild (regex) {
const regexpSource = regex && regex.source
const parametricChild = this.parametricChildren.find(child => {
const childRegexSource = child.regex && child.regex.source
return childRegexSource === regexpSource
})
if (parametricChild) {
return parametricChild
}
return null
}
createParametricChild (regex, staticSuffix, nodePath) {
let parametricChild = this.getParametricChild(regex)
if (parametricChild) {
parametricChild.nodePaths.add(nodePath)
return parametricChild
}
parametricChild = new ParametricNode(regex, staticSuffix, nodePath)
this.parametricChildren.push(parametricChild)
this.parametricChildren.sort((child1, child2) => {
if (!child1.isRegex) return 1
if (!child2.isRegex) return -1
if (child1.staticSuffix === null) return 1
if (child2.staticSuffix === null) return -1
if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1
if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1
return 0
})
return parametricChild
}
getWildcardChild () {
return this.wildcardChild
}
createWildcardChild () {
this.wildcardChild = this.getWildcardChild() || new WildcardNode()
return this.wildcardChild
}
split (parentNode, length) {
const parentPrefix = this.prefix.slice(0, length)
const childPrefix = this.prefix.slice(length)
this.prefix = childPrefix
this._compilePrefixMatch()
const staticNode = new StaticNode(parentPrefix)
staticNode.staticChildren[childPrefix.charAt(0)] = this
parentNode.staticChildren[parentPrefix.charAt(0)] = staticNode
return staticNode
}
getNextNode (path, pathIndex, nodeStack, paramsCount) {
let node = this.findStaticMatchingChild(path, pathIndex)
let parametricBrotherNodeIndex = 0
if (node === null) {
if (this.parametricChildren.length === 0) {
return this.wildcardChild
}
node = this.parametricChildren[0]
parametricBrotherNodeIndex = 1
}
if (this.wildcardChild !== null) {
nodeStack.push({
paramsCount,
brotherPathIndex: pathIndex,
brotherNode: this.wildcardChild
})
}
for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) {
nodeStack.push({
paramsCount,
brotherPathIndex: pathIndex,
brotherNode: this.parametricChildren[i]
})
}
return node
}
_compilePrefixMatch () {
if (this.prefix.length === 1) {
this.matchPrefix = () => true
return
}
const lines = []
for (let i = 1; i < this.prefix.length; i++) {
const charCode = this.prefix.charCodeAt(i)
lines.push(`path.charCodeAt(i + ${i}) === ${charCode}`)
}
this.matchPrefix = new Function('path', 'i', `return ${lines.join(' && ')}`) // eslint-disable-line
}
}
class ParametricNode extends ParentNode {
constructor (regex, staticSuffix, nodePath) {
super()
this.isRegex = !!regex
this.regex = regex || null
this.staticSuffix = staticSuffix || null
this.kind = NODE_TYPES.PARAMETRIC
this.nodePaths = new Set([nodePath])
}
getNextNode (path, pathIndex) {
return this.findStaticMatchingChild(path, pathIndex)
}
}
class WildcardNode extends Node {
constructor () {
super()
this.kind = NODE_TYPES.WILDCARD
}
getNextNode () {
return null
}
}
module.exports = { StaticNode, ParametricNode, WildcardNode, NODE_TYPES }
/***/ }),
/***/ 62569:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const deepEqual = __nccwpck_require__(28206)
const httpMethodStrategy = __nccwpck_require__(24116)
const treeDataSymbol = Symbol('treeData')
function printObjectTree (obj, parentPrefix = '') {
let tree = ''
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const value = obj[key]
const isLast = i === keys.length - 1
const nodePrefix = isLast ? '└── ' : '├── '
const childPrefix = isLast ? ' ' : '│ '
const nodeData = value[treeDataSymbol] || ''
const prefixedNodeData = nodeData.split('\n').join('\n' + parentPrefix + childPrefix)
tree += parentPrefix + nodePrefix + key + prefixedNodeData + '\n'
tree += printObjectTree(value, parentPrefix + childPrefix)
}
return tree
}
function parseFunctionName (fn) {
let fName = fn.name || ''
fName = fName.replace('bound', '').trim()
fName = (fName || 'anonymous') + '()'
return fName
}
function parseMeta (meta) {
if (Array.isArray(meta)) return meta.map(m => parseMeta(m))
if (typeof meta === 'symbol') return meta.toString()
if (typeof meta === 'function') return parseFunctionName(meta)
return meta
}
function getRouteMetaData (route, options) {
if (!options.includeMeta) return {}
const metaDataObject = options.buildPrettyMeta(route)
const filteredMetaData = {}
let includeMetaKeys = options.includeMeta
if (!Array.isArray(includeMetaKeys)) {
includeMetaKeys = Reflect.ownKeys(metaDataObject)
}
for (const metaKey of includeMetaKeys) {
if (!Object.prototype.hasOwnProperty.call(metaDataObject, metaKey)) continue
const serializedKey = metaKey.toString()
const metaValue = metaDataObject[metaKey]
if (metaValue !== undefined && metaValue !== null) {
const serializedValue = JSON.stringify(parseMeta(metaValue))
filteredMetaData[serializedKey] = serializedValue
}
}
return filteredMetaData
}
function serializeMetaData (metaData) {
let serializedMetaData = ''
for (const [key, value] of Object.entries(metaData)) {
serializedMetaData += `\n• (${key}) ${value}`
}
return serializedMetaData
}
// get original merged tree node route
function normalizeRoute (route) {
const constraints = { ...route.opts.constraints }
const method = constraints[httpMethodStrategy.name]
delete constraints[httpMethodStrategy.name]
return { ...route, method, opts: { constraints } }
}
function serializeRoute (route) {
let serializedRoute = ` (${route.method})`
const constraints = route.opts.constraints || {}
if (Object.keys(constraints).length !== 0) {
serializedRoute += ' ' + JSON.stringify(constraints)
}
serializedRoute += serializeMetaData(route.metaData)
return serializedRoute
}
function mergeSimilarRoutes (routes) {
return routes.reduce((mergedRoutes, route) => {
for (const nodeRoute of mergedRoutes) {
if (
deepEqual(route.opts.constraints, nodeRoute.opts.constraints) &&
deepEqual(route.metaData, nodeRoute.metaData)
) {
nodeRoute.method += ', ' + route.method
return mergedRoutes
}
}
mergedRoutes.push(route)
return mergedRoutes
}, [])
}
function serializeNode (node, prefix, options) {
let routes = node.routes
if (options.method === undefined) {
routes = routes.map(normalizeRoute)
}
routes = routes.map(route => {
route.metaData = getRouteMetaData(route, options)
return route
})
if (options.method === undefined) {
routes = mergeSimilarRoutes(routes)
}
return routes.map(serializeRoute).join(`\n${prefix}`)
}
function buildObjectTree (node, tree, prefix, options) {
if (node.isLeafNode || options.commonPrefix !== false) {
prefix = prefix || '(empty root node)'
tree = tree[prefix] = {}
if (node.isLeafNode) {
tree[treeDataSymbol] = serializeNode(node, prefix, options)
}
prefix = ''
}
if (node.staticChildren) {
for (const child of Object.values(node.staticChildren)) {
buildObjectTree(child, tree, prefix + child.prefix, options)
}
}
if (node.parametricChildren) {
for (const child of Object.values(node.parametricChildren)) {
const childPrefix = Array.from(child.nodePaths).join('|')
buildObjectTree(child, tree, prefix + childPrefix, options)
}
}
if (node.wildcardChild) {
buildObjectTree(node.wildcardChild, tree, '*', options)
}
}
function prettyPrintTree (root, options) {
const objectTree = {}
buildObjectTree(root, objectTree, root.prefix, options)
return printObjectTree(objectTree)
}
module.exports = { prettyPrintTree }
/***/ }),
/***/ 46739:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(98061)
function HostStorage () {
const hosts = {}
const regexHosts = []
return {
get: (host) => {
const exact = hosts[host]
if (exact) {
return exact
}
for (const regex of regexHosts) {
if (regex.host.test(host)) {
return regex.value
}
}
},
set: (host, value) => {
if (host instanceof RegExp) {
regexHosts.push({ host, value })
} else {
hosts[host] = value
}
}
}
}
module.exports = {
name: 'host',
mustMatchWhenDerived: false,
storage: HostStorage,
validate (value) {
assert(typeof value === 'string' || Object.prototype.toString.call(value) === '[object RegExp]', 'Host should be a string or a RegExp')
}
}
/***/ }),
/***/ 30517:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(98061)
function SemVerStore () {
if (!(this instanceof SemVerStore)) {
return new SemVerStore()
}
this.store = {}
this.maxMajor = 0
this.maxMinors = {}
this.maxPatches = {}
}
SemVerStore.prototype.set = function (version, store) {
if (typeof version !== 'string') {
throw new TypeError('Version should be a string')
}
let [major, minor, patch] = version.split('.')
if (isNaN(major)) {
throw new TypeError('Major version must be a numeric value')
}
major = Number(major)
minor = Number(minor) || 0
patch = Number(patch) || 0
if (major >= this.maxMajor) {
this.maxMajor = major
this.store.x = store
this.store['*'] = store
this.store['x.x'] = store
this.store['x.x.x'] = store
}
if (minor >= (this.maxMinors[major] || 0)) {
this.maxMinors[major] = minor
this.store[`${major}.x`] = store
this.store[`${major}.x.x`] = store
}
if (patch >= (this.maxPatches[`${major}.${minor}`] || 0)) {
this.maxPatches[`${major}.${minor}`] = patch
this.store[`${major}.${minor}.x`] = store
}
this.store[`${major}.${minor}.${patch}`] = store
return this
}
SemVerStore.prototype.get = function (version) {
return this.store[version]
}
module.exports = {
name: 'version',
mustMatchWhenDerived: true,
storage: SemVerStore,
validate (value) {
assert(typeof value === 'string', 'Version should be a string')
}
}
/***/ }),
/***/ 24116:
/***/ ((module) => {
"use strict";
module.exports = {
name: '__fmw_internal_strategy_merged_tree_http_method__',
storage: function () {
const handlers = {}
return {
get: (type) => { return handlers[type] || null },
set: (type, store) => { handlers[type] = store }
}
},
deriveConstraint: /* istanbul ignore next */ (req) => req.method,
mustMatchWhenDerived: true
}
/***/ }),
/***/ 43436:
/***/ ((module) => {
"use strict";
// It must spot all the chars where decodeURIComponent(x) !== decodeURI(x)
// The chars are: # $ & + , / : ; = ? @
function decodeComponentChar (highCharCode, lowCharCode) {
if (highCharCode === 50) {
if (lowCharCode === 53) return '%'
if (lowCharCode === 51) return '#'
if (lowCharCode === 52) return '$'
if (lowCharCode === 54) return '&'
if (lowCharCode === 66) return '+'
if (lowCharCode === 98) return '+'
if (lowCharCode === 67) return ','
if (lowCharCode === 99) return ','
if (lowCharCode === 70) return '/'
if (lowCharCode === 102) return '/'
return null
}
if (highCharCode === 51) {
if (lowCharCode === 65) return ':'
if (lowCharCode === 97) return ':'
if (lowCharCode === 66) return ';'
if (lowCharCode === 98) return ';'
if (lowCharCode === 68) return '='
if (lowCharCode === 100) return '='
if (lowCharCode === 70) return '?'
if (lowCharCode === 102) return '?'
return null
}
if (highCharCode === 52 && lowCharCode === 48) {
return '@'
}
return null
}
function safeDecodeURI (path, useSemicolonDelimiter) {
let shouldDecode = false
let shouldDecodeParam = false
let querystring = ''
for (let i = 1; i < path.length; i++) {
const charCode = path.charCodeAt(i)
if (charCode === 37) {
const highCharCode = path.charCodeAt(i + 1)
const lowCharCode = path.charCodeAt(i + 2)
if (decodeComponentChar(highCharCode, lowCharCode) === null) {
shouldDecode = true
} else {
shouldDecodeParam = true
// %25 - encoded % char. We need to encode one more time to prevent double decoding
if (highCharCode === 50 && lowCharCode === 53) {
shouldDecode = true
path = path.slice(0, i + 1) + '25' + path.slice(i + 1)
i += 2
}
i += 2
}
// Some systems do not follow RFC and separate the path and query
// string with a `;` character (code 59), e.g. `/foo;jsessionid=123456`.
// Thus, we need to split on `;` as well as `?` and `#` if the useSemicolonDelimiter option is enabled.
} else if (charCode === 63 || charCode === 35 || (charCode === 59 && useSemicolonDelimiter)) {
querystring = path.slice(i + 1)
path = path.slice(0, i)
break
}
}
const decodedPath = shouldDecode ? decodeURI(path) : path
return { path: decodedPath, querystring, shouldDecodeParam }
}
function safeDecodeURIComponent (uriComponent) {
const startIndex = uriComponent.indexOf('%')
if (startIndex === -1) return uriComponent
let decoded = ''
let lastIndex = startIndex
for (let i = startIndex; i < uriComponent.length; i++) {
if (uriComponent.charCodeAt(i) === 37) {
const highCharCode = uriComponent.charCodeAt(i + 1)
const lowCharCode = uriComponent.charCodeAt(i + 2)
const decodedChar = decodeComponentChar(highCharCode, lowCharCode)
decoded += uriComponent.slice(lastIndex, i) + decodedChar
lastIndex = i + 3
}
}
return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex)
}
module.exports = { safeDecodeURI, safeDecodeURIComponent }
/***/ }),
/***/ 31133:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var debug;
module.exports = function () {
if (!debug) {
try {
/* eslint global-require: off */
debug = __nccwpck_require__(38237)("follow-redirects");
}
catch (error) { /* */ }
if (typeof debug !== "function") {
debug = function () { /* */ };
}
}
debug.apply(null, arguments);
};
/***/ }),
/***/ 67707:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var url = __nccwpck_require__(57310);
var URL = url.URL;
var http = __nccwpck_require__(13685);
var https = __nccwpck_require__(95687);
var Writable = (__nccwpck_require__(12781).Writable);
var assert = __nccwpck_require__(39491);
var debug = __nccwpck_require__(31133);
// Whether to use the native URL object or the legacy url module
var useNativeURL = false;
try {
assert(new URL());
}
catch (error) {
useNativeURL = error.code === "ERR_INVALID_URL";
}
// URL fields to preserve in copy operations
var preservedUrlFields = [
"auth",
"host",
"hostname",
"href",
"path",
"pathname",
"port",
"protocol",
"query",
"search",
"hash",
];
// 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);
};
});
// Error types with codes
var InvalidUrlError = createErrorType(
"ERR_INVALID_URL",
"Invalid URL",
TypeError
);
var RedirectionError = createErrorType(
"ERR_FR_REDIRECTION_FAILURE",
"Redirected request failed"
);
var TooManyRedirectsError = createErrorType(
"ERR_FR_TOO_MANY_REDIRECTS",
"Maximum number of redirects exceeded",
RedirectionError
);
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"
);
// istanbul ignore next
var destroy = Writable.prototype.destroy || noop;
// 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 = [];
// Attach a callback if passed
if (responseCallback) {
this.on("response", responseCallback);
}
// React to responses of native requests
var self = this;
this._onNativeResponse = function (response) {
try {
self._processResponse(response);
}
catch (cause) {
self.emit("error", cause instanceof RedirectionError ?
cause : new RedirectionError({ cause: cause }));
}
};
// Perform the first request
this._performRequest();
}
RedirectableRequest.prototype = Object.create(Writable.prototype);
RedirectableRequest.prototype.abort = function () {
destroyRequest(this._currentRequest);
this._currentRequest.abort();
this.emit("abort");
};
RedirectableRequest.prototype.destroy = function (error) {
destroyRequest(this._currentRequest, error);
destroy.call(this, error);
return this;
};
// 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 (!isString(data) && !isBuffer(data)) {
throw new TypeError("data should be a string, Buffer or Uint8Array");
}
if (isFunction(encoding)) {
callback = encoding;
encoding = null;
}
// 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();
}
};
// Ends the current native request
RedirectableRequest.prototype.end = function (data, encoding, callback) {
// Shift parameters if necessary
if (isFunction(data)) {
callback = data;
data = encoding = null;
}
else if (isFunction(encoding)) {
callback = encoding;
encoding = null;
}
// 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;
}
};
// 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);
};
// Global timeout for all underlying requests
RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
var self = this;
// Destroys the socket on timeout
function destroyOnTimeout(socket) {
socket.setTimeout(msecs);
socket.removeListener("timeout", socket.destroy);
socket.addListener("timeout", socket.destroy);
}
// 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);
}
// Stops a timeout from triggering
function clearTimer() {
// Clear the timeout
if (self._timeout) {
clearTimeout(self._timeout);
self._timeout = null;
}
// Clean up all attached listeners
self.removeListener("abort", clearTimer);
self.removeListener("error", clearTimer);
self.removeListener("response", clearTimer);
self.removeListener("close", clearTimer);
if (callback) {
self.removeListener("timeout", callback);
}
if (!self.socket) {
self._currentRequest.removeListener("socket", startTimer);
}
}
// Attach callback if passed
if (callback) {
this.on("timeout", callback);
}
// Start the timer if or when the socket is opened
if (this.socket) {
startTimer(this.socket);
}
else {
this._currentRequest.once("socket", startTimer);
}
// Clean up on events
this.on("socket", destroyOnTimeout);
this.on("abort", clearTimer);
this.on("error", clearTimer);
this.on("response", clearTimer);
this.on("close", clearTimer);
return this;
};
// 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);
};
});
// 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 = {};
}
// 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);
}
}
};
// 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) {
throw new TypeError("Unsupported protocol " + protocol);
}
// If specified, use the agent corresponding to the protocol
// (HTTP and HTTPS use different types of agents)
if (this._options.agents) {
var scheme = protocol.slice(0, -1);
this._options.agent = this._options.agents[scheme];
}
// Create the native request and set up its event handlers
var request = this._currentRequest =
nativeProtocol.request(this._options, this._onNativeResponse);
request._redirectable = this;
for (var event of events) {
request.on(event, eventHandlers[event]);
}
// RFC7230§5.3.1: When making a request directly to an origin server, […]
// a client MUST send only the absolute path […] as the request-target.
this._currentUrl = /^\//.test(this._options.path) ?
url.format(this._options) :
// When making a request to a proxy, […]
// a client MUST send the target URI in absolute-form […].
this._options.path;
// 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();
}
}
}());
}
};
// 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,
});
}
// 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.
// If the response is not a redirect; return it as-is
var location = response.headers.location;
if (!location || this._options.followRedirects === false ||
statusCode < 300 || statusCode >= 400) {
response.responseUrl = this._currentUrl;
response.redirects = this._redirects;
this.emit("response", response);
// Clean up
this._requestBodyBuffers = [];
return;
}
// The response is a redirect, so abort the current request
destroyRequest(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) {
throw new TooManyRedirectsError();
}
// Store the request headers if applicable
var requestHeaders;
var beforeRedirect = this._options.beforeRedirect;
if (beforeRedirect) {
requestHeaders = Object.assign({
// The Host header was set by nativeProtocol.request
Host: response.req.getHeader("host"),
}, this._options.headers);
}
// RFC7231§6.4: Automatic redirection needs to done with
// care for methods not known to be safe, […]
// RFC7231§6.4.23: For historical reasons, a user agent MAY change
// the request method from POST to GET for the subsequent request.
var method = this._options.method;
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 currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
// If the redirect is relative, carry over the host of the last request
var currentUrlParts = parseUrl(this._currentUrl);
var currentHost = currentHostHeader || currentUrlParts.host;
var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
url.format(Object.assign(currentUrlParts, { host: currentHost }));
// Create the redirected request
var redirectUrl = resolveUrl(location, currentUrl);
debug("redirecting to", redirectUrl.href);
this._isRedirect = true;
spreadUrlObject(redirectUrl, this._options);
// Drop confidential headers when redirecting to a less secure protocol
// or to a different domain that is not a superdomain
if (redirectUrl.protocol !== currentUrlParts.protocol &&
redirectUrl.protocol !== "https:" ||
redirectUrl.host !== currentHost &&
!isSubdomain(redirectUrl.host, currentHost)) {
removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
}
// Evaluate the beforeRedirect callback
if (isFunction(beforeRedirect)) {
var responseDetails = {
headers: response.headers,
statusCode: statusCode,
};
var requestDetails = {
url: currentUrl,
method: method,
headers: requestHeaders,
};
beforeRedirect(this._options, responseDetails, requestDetails);
this._sanitizeOptions(this._options);
}
// Perform the redirected request
this._performRequest();
};
// 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);
// Executes a request, following redirects
function request(input, options, callback) {
// Parse parameters, ensuring that input is an object
if (isURL(input)) {
input = spreadUrlObject(input);
}
else if (isString(input)) {
input = spreadUrlObject(parseUrl(input));
}
else {
callback = options;
options = validateUrl(input);
input = { protocol: protocol };
}
if (isFunction(options)) {
callback = options;
options = null;
}
// Set defaults
options = Object.assign({
maxRedirects: exports.maxRedirects,
maxBodyLength: exports.maxBodyLength,
}, input, options);
options.nativeProtocols = nativeProtocols;
if (!isString(options.host) && !isString(options.hostname)) {
options.hostname = "::1";
}
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;
}
// 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;
}
function noop() { /* empty */ }
function parseUrl(input) {
var parsed;
/* istanbul ignore else */
if (useNativeURL) {
parsed = new URL(input);
}
else {
// Ensure the URL is valid and absolute
parsed = validateUrl(url.parse(input));
if (!isString(parsed.protocol)) {
throw new InvalidUrlError({ input });
}
}
return parsed;
}
function resolveUrl(relative, base) {
/* istanbul ignore next */
return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative));
}
function validateUrl(input) {
if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
throw new InvalidUrlError({ input: input.href || input });
}
if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
throw new InvalidUrlError({ input: input.href || input });
}
return input;
}
function spreadUrlObject(urlObject, target) {
var spread = target || {};
for (var key of preservedUrlFields) {
spread[key] = urlObject[key];
}
// Fix IPv6 hostname
if (spread.hostname.startsWith("[")) {
spread.hostname = spread.hostname.slice(1, -1);
}
// Ensure port is a number
if (spread.port !== "") {
spread.port = Number(spread.port);
}
// Concatenate path
spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
return spread;
}
function removeMatchingHeaders(regex, headers) {
var lastValue;
for (var header in headers) {
if (regex.test(header)) {
lastValue = headers[header];
delete headers[header];
}
}
return (lastValue === null || typeof lastValue === "undefined") ?
undefined : String(lastValue).trim();
}
function createErrorType(code, message, baseClass) {
// Create constructor
function CustomError(properties) {
Error.captureStackTrace(this, this.constructor);
Object.assign(this, properties || {});
this.code = code;
this.message = this.cause ? message + ": " + this.cause.message : message;
}
// Attach constructor and set default properties
CustomError.prototype = new (baseClass || Error)();
Object.defineProperties(CustomError.prototype, {
constructor: {
value: CustomError,
enumerable: false,
},
name: {
value: "Error [" + code + "]",
enumerable: false,
},
});
return CustomError;
}
function destroyRequest(request, error) {
for (var event of events) {
request.removeListener(event, eventHandlers[event]);
}
request.on("error", noop);
request.destroy(error);
}
function isSubdomain(subdomain, domain) {
assert(isString(subdomain) && isString(domain));
var dot = subdomain.length - domain.length - 1;
return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
}
function isString(value) {
return typeof value === "string" || value instanceof String;
}
function isFunction(value) {
return typeof value === "function";
}
function isBuffer(value) {
return typeof value === "object" && ("length" in value);
}
function isURL(value) {
return URL && value instanceof URL;
}
// Exports
module.exports = wrap({ http: http, https: https });
module.exports.wrap = wrap;
/***/ }),
/***/ 64334:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var CombinedStream = __nccwpck_require__(85443);
var util = __nccwpck_require__(73837);
var path = __nccwpck_require__(71017);
var http = __nccwpck_require__(13685);
var https = __nccwpck_require__(95687);
var parseUrl = (__nccwpck_require__(57310).parse);
var fs = __nccwpck_require__(57147);
var Stream = (__nccwpck_require__(12781).Stream);
var mime = __nccwpck_require__(43583);
var asynckit = __nccwpck_require__(14812);
var populate = __nccwpck_require__(17142);
// Public API
module.exports = FormData;
// make it a Stream
util.inherits(FormData, CombinedStream);
/**
* 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(options);
}
this._overheadLength = 0;
this._valueLength = 0;
this._valuesToMeasure = [];
CombinedStream.call(this);
options = options || {};
for (var option in options) {
this[option] = options[option];
}
}
FormData.LINE_BREAK = '\r\n';
FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
FormData.prototype.append = function(field, value, options) {
options = options || {};
// allow filename as single option
if (typeof options == 'string') {
options = {filename: options};
}
var append = CombinedStream.prototype.append.bind(this);
// all that streamy business can't handle numbers
if (typeof value == 'number') {
value = '' + value;
}
// 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;
}
var header = this._multiPartHeader(field, value, options);
var footer = this._multiPartFooter();
append(header);
append(value);
append(footer);
// pass along options.knownLength
this._trackLength(header, value, options);
};
FormData.prototype._trackLength = function(header, value, options) {
var valueLength = 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);
}
this._valueLength += valueLength;
// @check why add CRLF? does this account for custom/multiple CRLFs?
this._overheadLength +=
Buffer.byteLength(header) +
FormData.LINE_BREAK.length;
// empty or either doesn't have path or not an http response or not a stream
if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) {
return;
}
// no need to bother with the length
if (!options.knownLength) {
this._valuesToMeasure.push(value);
}
};
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) {
// when end specified
// no need to calculate range
// inclusive, starts with 0
callback(null, value.end + 1 - (value.start ? value.start : 0));
// not that fast snoopy
} else {
// still need to fetch file size from fs
fs.stat(value.path, function(err, stat) {
var fileSize;
if (err) {
callback(err);
return;
}
// update final size based on the range options
fileSize = stat.size - (value.start ? value.start : 0);
callback(null, fileSize);
});
}
// or http response
} else if (value.hasOwnProperty('httpVersion')) {
callback(null, +value.headers['content-length']);
// 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();
// 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;
}
var contentDisposition = this._getContentDisposition(value, options);
var contentType = this._getContentType(value, options);
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 || [])
};
// allow custom headers.
if (typeof options.header == 'object') {
populate(headers, options.header);
}
var header;
for (var prop in headers) {
if (!headers.hasOwnProperty(prop)) continue;
header = headers[prop];
// skip nullish headers.
if (header == null) {
continue;
}
// convert all headers to arrays.
if (!Array.isArray(header)) {
header = [header];
}
// add non-empty headers.
if (header.length) {
contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
}
}
return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
};
FormData.prototype._getContentDisposition = function(value, options) {
var filename
, contentDisposition
;
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 || '');
}
if (filename) {
contentDisposition = 'filename="' + filename + '"';
}
return contentDisposition;
};
FormData.prototype._getContentType = function(value, options) {
// use custom content-type above all
var contentType = options.contentType;
// or try `name` from formidable, browser
if (!contentType && value.name) {
contentType = mime.lookup(value.name);
}
// or try `path` from fs-, request- streams
if (!contentType && value.path) {
contentType = mime.lookup(value.path);
}
// or if it's http-reponse
if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
contentType = value.headers['content-type'];
}
// or guess it from the filepath or filename
if (!contentType && (options.filepath || options.filename)) {
contentType = mime.lookup(options.filepath || options.filename);
}
// 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;
var lastPart = (this._streams.length === 0);
if (lastPart) {
footer += this._lastBoundary();
}
next(footer);
}.bind(this);
};
FormData.prototype._lastBoundary = function() {
return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
};
FormData.prototype.getHeaders = function(userHeaders) {
var header;
var formHeaders = {
'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
};
for (header in userHeaders) {
if (userHeaders.hasOwnProperty(header)) {
formHeaders[header.toLowerCase()] = userHeaders[header];
}
}
return formHeaders;
};
FormData.prototype.setBoundary = function(boundary) {
this._boundary = boundary;
};
FormData.prototype.getBoundary = function() {
if (!this._boundary) {
this._generateBoundary();
}
return this._boundary;
};
FormData.prototype.getBuffer = function() {
var dataBuffer = new Buffer.alloc( 0 );
var boundary = this.getBoundary();
// Create the form content. Add Line breaks to the end of data.
for (var i = 0, len = this._streams.length; i < len; i++) {
if (typeof this._streams[i] !== 'function') {
// Add content to the buffer.
if(Buffer.isBuffer(this._streams[i])) {
dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
}else {
dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
}
// Add break after content.
if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
}
}
}
// Add the footer and return the Buffer object.
return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
};
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;
};
// 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;
}
// 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.'));
}
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;
if (this._valuesToMeasure.length) {
hasKnownLength = false;
}
return hasKnownLength;
};
FormData.prototype.getLength = function(cb) {
var knownLength = this._overheadLength + this._valueLength;
if (this._streams.length) {
knownLength += this._lastBoundary().length;
}
if (!this._valuesToMeasure.length) {
process.nextTick(cb.bind(this, null, knownLength));
return;
}
asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
if (err) {
cb(err);
return;
}
values.forEach(function(length) {
knownLength += length;
});
cb(null, knownLength);
});
};
FormData.prototype.submit = function(params, cb) {
var request
, options
, defaults = {method: 'post'}
;
// parse provided url if it's string
// or treat it as options object
if (typeof params == 'string') {
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;
}
}
// 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 && err !== 'Unknown stream') {
this._error(err);
return;
}
// add content length
if (length) {
request.setHeader('Content-Length', length);
}
this.pipe(request);
if (cb) {
var onResponse;
var callback = function (error, responce) {
request.removeListener('error', callback);
request.removeListener('response', onResponse);
return cb.call(this, error, responce);
};
onResponse = callback.bind(this, null);
request.on('error', callback);
request.on('response', onResponse);
}
}.bind(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]';
};
/***/ }),
/***/ 17142:
/***/ ((module) => {
// populates missing values
module.exports = function(dst, src) {
Object.keys(src).forEach(function(prop)
{
dst[prop] = dst[prop] || src[prop];
});
return dst;
};
/***/ }),
/***/ 46868:
/***/ ((module) => {
"use strict";
/*!
* forwarded
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
* @public
*/
module.exports = forwarded
/**
* Get all addresses in the request, using the `X-Forwarded-For` header.
*
* @param {object} req
* @return {array}
* @public
*/
function forwarded (req) {
if (!req) {
throw new TypeError('argument req is required')
}
// simple header parsing
var proxyAddrs = parse(req.headers['x-forwarded-for'] || '')
var socketAddr = getSocketAddr(req)
var addrs = [socketAddr].concat(proxyAddrs)
// return all addresses
return addrs
}
/**
* Get the socket address for a request.
*
* @param {object} req
* @return {string}
* @private
*/
function getSocketAddr (req) {
return req.socket
? req.socket.remoteAddress
: req.connection.remoteAddress
}
/**
* Parse the X-Forwarded-For header.
*
* @param {string} header
* @private
*/
function parse (header) {
var end = header.length
var list = []
var start = header.length
// gather addresses, backwards
for (var i = header.length - 1; i >= 0; i--) {
switch (header.charCodeAt(i)) {
case 0x20: /* */
if (start === end) {
start = end = i
}
break
case 0x2c: /* , */
if (start !== end) {
list.push(header.substring(start, end))
}
start = end = i
break
default:
start = i
break
}
}
// final address
if (start !== end) {
list.push(header.substring(start, end))
}
return list
}
/***/ }),
/***/ 31621:
/***/ ((module) => {
"use strict";
module.exports = (flag, argv = process.argv) => {
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
/***/ }),
/***/ 37263:
/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {
/* module decorator */ module = __nccwpck_require__.nmd(module);
(function() {
var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
ipaddr = {};
root = this;
if (( true && module !== null) && module.exports) {
module.exports = ipaddr;
} else {
root['ipaddr'] = ipaddr;
}
matchCIDR = function(first, second, partSize, cidrBits) {
var part, shift;
if (first.length !== second.length) {
throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
}
part = 0;
while (cidrBits > 0) {
shift = partSize - cidrBits;
if (shift < 0) {
shift = 0;
}
if (first[part] >> shift !== second[part] >> shift) {
return false;
}
cidrBits -= partSize;
part += 1;
}
return true;
};
ipaddr.subnetMatch = function(address, rangeList, defaultName) {
var k, len, rangeName, rangeSubnets, subnet;
if (defaultName == null) {
defaultName = 'unicast';
}
for (rangeName in rangeList) {
rangeSubnets = rangeList[rangeName];
if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
rangeSubnets = [rangeSubnets];
}
for (k = 0, len = rangeSubnets.length; k < len; k++) {
subnet = rangeSubnets[k];
if (address.kind() === subnet[0].kind()) {
if (address.match.apply(address, subnet)) {
return rangeName;
}
}
}
}
return defaultName;
};
ipaddr.IPv4 = (function() {
function IPv4(octets) {
var k, len, octet;
if (octets.length !== 4) {
throw new Error("ipaddr: ipv4 octet count should be 4");
}
for (k = 0, len = octets.length; k < len; k++) {
octet = octets[k];
if (!((0 <= octet && octet <= 255))) {
throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
}
}
this.octets = octets;
}
IPv4.prototype.kind = function() {
return 'ipv4';
};
IPv4.prototype.toString = function() {
return this.octets.join(".");
};
IPv4.prototype.toNormalizedString = function() {
return this.toString();
};
IPv4.prototype.toByteArray = function() {
return this.octets.slice(0);
};
IPv4.prototype.match = function(other, cidrRange) {
var ref;
if (cidrRange === void 0) {
ref = other, other = ref[0], cidrRange = ref[1];
}
if (other.kind() !== 'ipv4') {
throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
}
return matchCIDR(this.octets, other.octets, 8, cidrRange);
};
IPv4.prototype.SpecialRanges = {
unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
multicast: [[new IPv4([224, 0, 0, 0]), 4]],
linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
loopback: [[new IPv4([127, 0, 0, 0]), 8]],
carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
"private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
};
IPv4.prototype.range = function() {
return ipaddr.subnetMatch(this, this.SpecialRanges);
};
IPv4.prototype.toIPv4MappedAddress = function() {
return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
};
IPv4.prototype.prefixLengthFromSubnetMask = function() {
var cidr, i, k, octet, stop, zeros, zerotable;
zerotable = {
0: 8,
128: 7,
192: 6,
224: 5,
240: 4,
248: 3,
252: 2,
254: 1,
255: 0
};
cidr = 0;
stop = false;
for (i = k = 3; k >= 0; i = k += -1) {
octet = this.octets[i];
if (octet in zerotable) {
zeros = zerotable[octet];
if (stop && zeros !== 0) {
return null;
}
if (zeros !== 8) {
stop = true;
}
cidr += zeros;
} else {
return null;
}
}
return 32 - cidr;
};
return IPv4;
})();
ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
ipv4Regexes = {
fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
longValue: new RegExp("^" + ipv4Part + "$", 'i')
};
ipaddr.IPv4.parser = function(string) {
var match, parseIntAuto, part, shift, value;
parseIntAuto = function(string) {
if (string[0] === "0" && string[1] !== "x") {
return parseInt(string, 8);
} else {
return parseInt(string);
}
};
if (match = string.match(ipv4Regexes.fourOctet)) {
return (function() {
var k, len, ref, results;
ref = match.slice(1, 6);
results = [];
for (k = 0, len = ref.length; k < len; k++) {
part = ref[k];
results.push(parseIntAuto(part));
}
return results;
})();
} else if (match = string.match(ipv4Regexes.longValue)) {
value = parseIntAuto(match[1]);
if (value > 0xffffffff || value < 0) {
throw new Error("ipaddr: address outside defined range");
}
return ((function() {
var k, results;
results = [];
for (shift = k = 0; k <= 24; shift = k += 8) {
results.push((value >> shift) & 0xff);
}
return results;
})()).reverse();
} else {
return null;
}
};
ipaddr.IPv6 = (function() {
function IPv6(parts, zoneId) {
var i, k, l, len, part, ref;
if (parts.length === 16) {
this.parts = [];
for (i = k = 0; k <= 14; i = k += 2) {
this.parts.push((parts[i] << 8) | parts[i + 1]);
}
} else if (parts.length === 8) {
this.parts = parts;
} else {
throw new Error("ipaddr: ipv6 part count should be 8 or 16");
}
ref = this.parts;
for (l = 0, len = ref.length; l < len; l++) {
part = ref[l];
if (!((0 <= part && part <= 0xffff))) {
throw new Error("ipaddr: ipv6 part should fit in 16 bits");
}
}
if (zoneId) {
this.zoneId = zoneId;
}
}
IPv6.prototype.kind = function() {
return 'ipv6';
};
IPv6.prototype.toString = function() {
return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');
};
IPv6.prototype.toRFC5952String = function() {
var bestMatchIndex, bestMatchLength, match, regex, string;
regex = /((^|:)(0(:|$)){2,})/g;
string = this.toNormalizedString();
bestMatchIndex = 0;
bestMatchLength = -1;
while ((match = regex.exec(string))) {
if (match[0].length > bestMatchLength) {
bestMatchIndex = match.index;
bestMatchLength = match[0].length;
}
}
if (bestMatchLength < 0) {
return string;
}
return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength);
};
IPv6.prototype.toByteArray = function() {
var bytes, k, len, part, ref;
bytes = [];
ref = this.parts;
for (k = 0, len = ref.length; k < len; k++) {
part = ref[k];
bytes.push(part >> 8);
bytes.push(part & 0xff);
}
return bytes;
};
IPv6.prototype.toNormalizedString = function() {
var addr, part, suffix;
addr = ((function() {
var k, len, ref, results;
ref = this.parts;
results = [];
for (k = 0, len = ref.length; k < len; k++) {
part = ref[k];
results.push(part.toString(16));
}
return results;
}).call(this)).join(":");
suffix = '';
if (this.zoneId) {
suffix = '%' + this.zoneId;
}
return addr + suffix;
};
IPv6.prototype.toFixedLengthString = function() {
var addr, part, suffix;
addr = ((function() {
var k, len, ref, results;
ref = this.parts;
results = [];
for (k = 0, len = ref.length; k < len; k++) {
part = ref[k];
results.push(part.toString(16).padStart(4, '0'));
}
return results;
}).call(this)).join(":");
suffix = '';
if (this.zoneId) {
suffix = '%' + this.zoneId;
}
return addr + suffix;
};
IPv6.prototype.match = function(other, cidrRange) {
var ref;
if (cidrRange === void 0) {
ref = other, other = ref[0], cidrRange = ref[1];
}
if (other.kind() !== 'ipv6') {
throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
}
return matchCIDR(this.parts, other.parts, 16, cidrRange);
};
IPv6.prototype.SpecialRanges = {
unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
'6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
};
IPv6.prototype.range = function() {
return ipaddr.subnetMatch(this, this.SpecialRanges);
};
IPv6.prototype.isIPv4MappedAddress = function() {
return this.range() === 'ipv4Mapped';
};
IPv6.prototype.toIPv4Address = function() {
var high, low, ref;
if (!this.isIPv4MappedAddress()) {
throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
}
ref = this.parts.slice(-2), high = ref[0], low = ref[1];
return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
};
IPv6.prototype.prefixLengthFromSubnetMask = function() {
var cidr, i, k, part, stop, zeros, zerotable;
zerotable = {
0: 16,
32768: 15,
49152: 14,
57344: 13,
61440: 12,
63488: 11,
64512: 10,
65024: 9,
65280: 8,
65408: 7,
65472: 6,
65504: 5,
65520: 4,
65528: 3,
65532: 2,
65534: 1,
65535: 0
};
cidr = 0;
stop = false;
for (i = k = 7; k >= 0; i = k += -1) {
part = this.parts[i];
if (part in zerotable) {
zeros = zerotable[part];
if (stop && zeros !== 0) {
return null;
}
if (zeros !== 16) {
stop = true;
}
cidr += zeros;
} else {
return null;
}
}
return 128 - cidr;
};
return IPv6;
})();
ipv6Part = "(?:[0-9a-f]+::?)+";
zoneIndex = "%[0-9a-z]{1,}";
ipv6Regexes = {
zoneIndex: new RegExp(zoneIndex, 'i'),
"native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'),
transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i')
};
expandIPv6 = function(string, parts) {
var colonCount, lastColon, part, replacement, replacementCount, zoneId;
if (string.indexOf('::') !== string.lastIndexOf('::')) {
return null;
}
zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0];
if (zoneId) {
zoneId = zoneId.substring(1);
string = string.replace(/%.+$/, '');
}
colonCount = 0;
lastColon = -1;
while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
colonCount++;
}
if (string.substr(0, 2) === '::') {
colonCount--;
}
if (string.substr(-2, 2) === '::') {
colonCount--;
}
if (colonCount > parts) {
return null;
}
replacementCount = parts - colonCount;
replacement = ':';
while (replacementCount--) {
replacement += '0:';
}
string = string.replace('::', replacement);
if (string[0] === ':') {
string = string.slice(1);
}
if (string[string.length - 1] === ':') {
string = string.slice(0, -1);
}
parts = (function() {
var k, len, ref, results;
ref = string.split(":");
results = [];
for (k = 0, len = ref.length; k < len; k++) {
part = ref[k];
results.push(parseInt(part, 16));
}
return results;
})();
return {
parts: parts,
zoneId: zoneId
};
};
ipaddr.IPv6.parser = function(string) {
var addr, k, len, match, octet, octets, zoneId;
if (ipv6Regexes['native'].test(string)) {
return expandIPv6(string, 8);
} else if (match = string.match(ipv6Regexes['transitional'])) {
zoneId = match[6] || '';
addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
if (addr.parts) {
octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
for (k = 0, len = octets.length; k < len; k++) {
octet = octets[k];
if (!((0 <= octet && octet <= 255))) {
return null;
}
}
addr.parts.push(octets[0] << 8 | octets[1]);
addr.parts.push(octets[2] << 8 | octets[3]);
return {
parts: addr.parts,
zoneId: addr.zoneId
};
}
}
return null;
};
ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
return this.parser(string) !== null;
};
ipaddr.IPv4.isValid = function(string) {
var e;
try {
new this(this.parser(string));
return true;
} catch (error1) {
e = error1;
return false;
}
};
ipaddr.IPv4.isValidFourPartDecimal = function(string) {
if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
return true;
} else {
return false;
}
};
ipaddr.IPv6.isValid = function(string) {
var addr, e;
if (typeof string === "string" && string.indexOf(":") === -1) {
return false;
}
try {
addr = this.parser(string);
new this(addr.parts, addr.zoneId);
return true;
} catch (error1) {
e = error1;
return false;
}
};
ipaddr.IPv4.parse = function(string) {
var parts;
parts = this.parser(string);
if (parts === null) {
throw new Error("ipaddr: string is not formatted like ip address");
}
return new this(parts);
};
ipaddr.IPv6.parse = function(string) {
var addr;
addr = this.parser(string);
if (addr.parts === null) {
throw new Error("ipaddr: string is not formatted like ip address");
}
return new this(addr.parts, addr.zoneId);
};
ipaddr.IPv4.parseCIDR = function(string) {
var maskLength, match, parsed;
if (match = string.match(/^(.+)\/(\d+)$/)) {
maskLength = parseInt(match[2]);
if (maskLength >= 0 && maskLength <= 32) {
parsed = [this.parse(match[1]), maskLength];
Object.defineProperty(parsed, 'toString', {
value: function() {
return this.join('/');
}
});
return parsed;
}
}
throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
};
ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
var filledOctetCount, j, octets;
prefix = parseInt(prefix);
if (prefix < 0 || prefix > 32) {
throw new Error('ipaddr: invalid IPv4 prefix length');
}
octets = [0, 0, 0, 0];
j = 0;
filledOctetCount = Math.floor(prefix / 8);
while (j < filledOctetCount) {
octets[j] = 255;
j++;
}
if (filledOctetCount < 4) {
octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
}
return new this(octets);
};
ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
try {
cidr = this.parseCIDR(string);
ipInterfaceOctets = cidr[0].toByteArray();
subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
octets = [];
i = 0;
while (i < 4) {
octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
i++;
}
return new this(octets);
} catch (error1) {
error = error1;
throw new Error('ipaddr: the address does not have IPv4 CIDR format');
}
};
ipaddr.IPv4.networkAddressFromCIDR = function(string) {
var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
try {
cidr = this.parseCIDR(string);
ipInterfaceOctets = cidr[0].toByteArray();
subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
octets = [];
i = 0;
while (i < 4) {
octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
i++;
}
return new this(octets);
} catch (error1) {
error = error1;
throw new Error('ipaddr: the address does not have IPv4 CIDR format');
}
};
ipaddr.IPv6.parseCIDR = function(string) {
var maskLength, match, parsed;
if (match = string.match(/^(.+)\/(\d+)$/)) {
maskLength = parseInt(match[2]);
if (maskLength >= 0 && maskLength <= 128) {
parsed = [this.parse(match[1]), maskLength];
Object.defineProperty(parsed, 'toString', {
value: function() {
return this.join('/');
}
});
return parsed;
}
}
throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
};
ipaddr.isValid = function(string) {
return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
};
ipaddr.parse = function(string) {
if (ipaddr.IPv6.isValid(string)) {
return ipaddr.IPv6.parse(string);
} else if (ipaddr.IPv4.isValid(string)) {
return ipaddr.IPv4.parse(string);
} else {
throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
}
};
ipaddr.parseCIDR = function(string) {
var e;
try {
return ipaddr.IPv6.parseCIDR(string);
} catch (error1) {
e = error1;
try {
return ipaddr.IPv4.parseCIDR(string);
} catch (error1) {
e = error1;
throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
}
}
};
ipaddr.fromByteArray = function(bytes) {
var length;
length = bytes.length;
if (length === 4) {
return new ipaddr.IPv4(bytes);
} else if (length === 16) {
return new ipaddr.IPv6(bytes);
} else {
throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
}
};
ipaddr.process = function(string) {
var addr;
addr = this.parse(string);
if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
return addr.toIPv4Address();
} else {
return addr;
}
};
}).call(this);
/***/ }),
/***/ 46014:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Clone = __nccwpck_require__(85578);
const Common = __nccwpck_require__(72448);
const internals = {
annotations: Symbol('annotations')
};
exports.error = function (stripColorCodes) {
if (!this._original ||
typeof this._original !== 'object') {
return this.details[0].message;
}
const redFgEscape = stripColorCodes ? '' : '\u001b[31m';
const redBgEscape = stripColorCodes ? '' : '\u001b[41m';
const endColor = stripColorCodes ? '' : '\u001b[0m';
const obj = Clone(this._original);
for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first
const pos = i + 1;
const error = this.details[i];
const path = error.path;
let node = obj;
for (let j = 0; ; ++j) {
const seg = path[j];
if (Common.isSchema(node)) {
node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step
}
if (j + 1 < path.length &&
typeof node[seg] !== 'string') {
node = node[seg];
}
else {
const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} };
node[internals.annotations] = refAnnotations;
const cacheKey = seg || error.context.key;
if (node[seg] !== undefined) {
refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || [];
refAnnotations.errors[cacheKey].push(pos);
}
else {
refAnnotations.missing[cacheKey] = pos;
}
break;
}
}
}
const replacers = {
key: /_\$key\$_([, \d]+)_\$end\$_"/g,
missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g,
arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g,
specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g
};
let message = internals.safeStringify(obj, 2)
.replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`)
.replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`)
.replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`)
.replace(replacers.specials, ($0, $1) => $1);
message = `${message}\n${redFgEscape}`;
for (let i = 0; i < this.details.length; ++i) {
const pos = i + 1;
message = `${message}\n[${pos}] ${this.details[i].message}`;
}
message = message + endColor;
return message;
};
// Inspired by json-stringify-safe
internals.safeStringify = function (obj, spaces) {
return JSON.stringify(obj, internals.serializer(), spaces);
};
internals.serializer = function () {
const keys = [];
const stack = [];
const cycleReplacer = (key, value) => {
if (stack[0] === value) {
return '[Circular ~]';
}
return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
};
return function (key, value) {
if (stack.length > 0) {
const thisPos = stack.indexOf(this);
if (~thisPos) {
stack.length = thisPos + 1;
keys.length = thisPos + 1;
keys[thisPos] = key;
}
else {
stack.push(this);
keys.push(key);
}
if (~stack.indexOf(value)) {
value = cycleReplacer.call(this, key, value);
}
}
else {
stack.push(value);
}
if (value) {
const annotations = value[internals.annotations];
if (annotations) {
if (Array.isArray(value)) {
const annotated = [];
for (let i = 0; i < value.length; ++i) {
if (annotations.errors[i]) {
annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`);
}
annotated.push(value[i]);
}
value = annotated;
}
else {
for (const errorKey in annotations.errors) {
value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey];
value[errorKey] = undefined;
}
for (const missingKey in annotations.missing) {
value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__';
}
}
return value;
}
}
if (value === Infinity ||
value === -Infinity ||
Number.isNaN(value) ||
typeof value === 'function' ||
typeof value === 'symbol') {
return '[' + value.toString() + ']';
}
return value;
};
};
/***/ }),
/***/ 95184:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const DeepEqual = __nccwpck_require__(55801);
const Merge = __nccwpck_require__(60445);
const Cache = __nccwpck_require__(63355);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const Errors = __nccwpck_require__(69490);
const Extend = __nccwpck_require__(86680);
const Manifest = __nccwpck_require__(87997);
const Messages = __nccwpck_require__(86103);
const Modify = __nccwpck_require__(81290);
const Ref = __nccwpck_require__(73838);
const Trace = __nccwpck_require__(43171);
const Validator = __nccwpck_require__(91804);
const Values = __nccwpck_require__(71944);
const internals = {};
internals.Base = class {
constructor(type) {
// Naming: public, _private, $_extension, $_mutate{action}
this.type = type;
this.$_root = null;
this._definition = {};
this._reset();
}
_reset() {
this._ids = new Modify.Ids();
this._preferences = null;
this._refs = new Ref.Manager();
this._cache = null;
this._valids = null;
this._invalids = null;
this._flags = {};
this._rules = [];
this._singleRules = new Map(); // The rule options passed for non-multi rules
this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types)
this.$_temp = { // Runtime state (not cloned)
ruleset: null, // null: use last, false: error, number: start position
whens: {} // Runtime cache of generated whens
};
}
// Manifest
describe() {
Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled');
return Manifest.describe(this);
}
// Rules
allow(...values) {
Common.verifyFlat(values, 'allow');
return this._values(values, '_valids');
}
alter(targets) {
Assert(targets && typeof targets === 'object' && !Array.isArray(targets), 'Invalid targets argument');
Assert(!this._inRuleset(), 'Cannot set alterations inside a ruleset');
const obj = this.clone();
obj.$_terms.alterations = obj.$_terms.alterations || [];
for (const target in targets) {
const adjuster = targets[target];
Assert(typeof adjuster === 'function', 'Alteration adjuster for', target, 'must be a function');
obj.$_terms.alterations.push({ target, adjuster });
}
obj.$_temp.ruleset = false;
return obj;
}
artifact(id) {
Assert(id !== undefined, 'Artifact cannot be undefined');
Assert(!this._cache, 'Cannot set an artifact with a rule cache');
return this.$_setFlag('artifact', id);
}
cast(to) {
Assert(to === false || typeof to === 'string', 'Invalid to value');
Assert(to === false || this._definition.cast[to], 'Type', this.type, 'does not support casting to', to);
return this.$_setFlag('cast', to === false ? undefined : to);
}
default(value, options) {
return this._default('default', value, options);
}
description(desc) {
Assert(desc && typeof desc === 'string', 'Description must be a non-empty string');
return this.$_setFlag('description', desc);
}
empty(schema) {
const obj = this.clone();
if (schema !== undefined) {
schema = obj.$_compile(schema, { override: false });
}
return obj.$_setFlag('empty', schema, { clone: false });
}
error(err) {
Assert(err, 'Missing error');
Assert(err instanceof Error || typeof err === 'function', 'Must provide a valid Error object or a function');
return this.$_setFlag('error', err);
}
example(example, options = {}) {
Assert(example !== undefined, 'Missing example');
Common.assertOptions(options, ['override']);
return this._inner('examples', example, { single: true, override: options.override });
}
external(method, description) {
if (typeof method === 'object') {
Assert(!description, 'Cannot combine options with description');
description = method.description;
method = method.method;
}
Assert(typeof method === 'function', 'Method must be a function');
Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string');
return this._inner('externals', { method, description }, { single: true });
}
failover(value, options) {
return this._default('failover', value, options);
}
forbidden() {
return this.presence('forbidden');
}
id(id) {
if (!id) {
return this.$_setFlag('id', undefined);
}
Assert(typeof id === 'string', 'id must be a non-empty string');
Assert(/^[^\.]+$/.test(id), 'id cannot contain period character');
return this.$_setFlag('id', id);
}
invalid(...values) {
return this._values(values, '_invalids');
}
label(name) {
Assert(name && typeof name === 'string', 'Label name must be a non-empty string');
return this.$_setFlag('label', name);
}
meta(meta) {
Assert(meta !== undefined, 'Meta cannot be undefined');
return this._inner('metas', meta, { single: true });
}
note(...notes) {
Assert(notes.length, 'Missing notes');
for (const note of notes) {
Assert(note && typeof note === 'string', 'Notes must be non-empty strings');
}
return this._inner('notes', notes);
}
only(mode = true) {
Assert(typeof mode === 'boolean', 'Invalid mode:', mode);
return this.$_setFlag('only', mode);
}
optional() {
return this.presence('optional');
}
prefs(prefs) {
Assert(prefs, 'Missing preferences');
Assert(prefs.context === undefined, 'Cannot override context');
Assert(prefs.externals === undefined, 'Cannot override externals');
Assert(prefs.warnings === undefined, 'Cannot override warnings');
Assert(prefs.debug === undefined, 'Cannot override debug');
Common.checkPreferences(prefs);
const obj = this.clone();
obj._preferences = Common.preferences(obj._preferences, prefs);
return obj;
}
presence(mode) {
Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode);
return this.$_setFlag('presence', mode);
}
raw(enabled = true) {
return this.$_setFlag('result', enabled ? 'raw' : undefined);
}
result(mode) {
Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode);
return this.$_setFlag('result', mode);
}
required() {
return this.presence('required');
}
strict(enabled) {
const obj = this.clone();
const convert = enabled === undefined ? false : !enabled;
obj._preferences = Common.preferences(obj._preferences, { convert });
return obj;
}
strip(enabled = true) {
return this.$_setFlag('result', enabled ? 'strip' : undefined);
}
tag(...tags) {
Assert(tags.length, 'Missing tags');
for (const tag of tags) {
Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings');
}
return this._inner('tags', tags);
}
unit(name) {
Assert(name && typeof name === 'string', 'Unit name must be a non-empty string');
return this.$_setFlag('unit', name);
}
valid(...values) {
Common.verifyFlat(values, 'valid');
const obj = this.allow(...values);
obj.$_setFlag('only', !!obj._valids, { clone: false });
return obj;
}
when(condition, options) {
const obj = this.clone();
if (!obj.$_terms.whens) {
obj.$_terms.whens = [];
}
const when = Compile.when(obj, condition, options);
if (!['any', 'link'].includes(obj.type)) {
const conditions = when.is ? [when] : when.switch;
for (const item of conditions) {
Assert(!item.then || item.then.type === 'any' || item.then.type === obj.type, 'Cannot combine', obj.type, 'with', item.then && item.then.type);
Assert(!item.otherwise || item.otherwise.type === 'any' || item.otherwise.type === obj.type, 'Cannot combine', obj.type, 'with', item.otherwise && item.otherwise.type);
}
}
obj.$_terms.whens.push(when);
return obj.$_mutateRebuild();
}
// Helpers
cache(cache) {
Assert(!this._inRuleset(), 'Cannot set caching inside a ruleset');
Assert(!this._cache, 'Cannot override schema cache');
Assert(this._flags.artifact === undefined, 'Cannot cache a rule with an artifact');
const obj = this.clone();
obj._cache = cache || Cache.provider.provision();
obj.$_temp.ruleset = false;
return obj;
}
clone() {
const obj = Object.create(Object.getPrototypeOf(this));
return this._assign(obj);
}
concat(source) {
Assert(Common.isSchema(source), 'Invalid schema object');
Assert(this.type === 'any' || source.type === 'any' || source.type === this.type, 'Cannot merge type', this.type, 'with another type:', source.type);
Assert(!this._inRuleset(), 'Cannot concatenate onto a schema with open ruleset');
Assert(!source._inRuleset(), 'Cannot concatenate a schema with open ruleset');
let obj = this.clone();
if (this.type === 'any' &&
source.type !== 'any') {
// Change obj to match source type
const tmpObj = source.clone();
for (const key of Object.keys(obj)) {
if (key !== 'type') {
tmpObj[key] = obj[key];
}
}
obj = tmpObj;
}
obj._ids.concat(source._ids);
obj._refs.register(source, Ref.toSibling);
obj._preferences = obj._preferences ? Common.preferences(obj._preferences, source._preferences) : source._preferences;
obj._valids = Values.merge(obj._valids, source._valids, source._invalids);
obj._invalids = Values.merge(obj._invalids, source._invalids, source._valids);
// Remove unique rules present in source
for (const name of source._singleRules.keys()) {
if (obj._singleRules.has(name)) {
obj._rules = obj._rules.filter((target) => target.keep || target.name !== name);
obj._singleRules.delete(name);
}
}
// Rules
for (const test of source._rules) {
if (!source._definition.rules[test.method].multi) {
obj._singleRules.set(test.name, test);
}
obj._rules.push(test);
}
// Flags
if (obj._flags.empty &&
source._flags.empty) {
obj._flags.empty = obj._flags.empty.concat(source._flags.empty);
const flags = Object.assign({}, source._flags);
delete flags.empty;
Merge(obj._flags, flags);
}
else if (source._flags.empty) {
obj._flags.empty = source._flags.empty;
const flags = Object.assign({}, source._flags);
delete flags.empty;
Merge(obj._flags, flags);
}
else {
Merge(obj._flags, source._flags);
}
// Terms
for (const key in source.$_terms) {
const terms = source.$_terms[key];
if (!terms) {
if (!obj.$_terms[key]) {
obj.$_terms[key] = terms;
}
continue;
}
if (!obj.$_terms[key]) {
obj.$_terms[key] = terms.slice();
continue;
}
obj.$_terms[key] = obj.$_terms[key].concat(terms);
}
// Tracing
if (this.$_root._tracer) {
this.$_root._tracer._combine(obj, [this, source]);
}
// Rebuild
return obj.$_mutateRebuild();
}
extend(options) {
Assert(!options.base, 'Cannot extend type with another base');
return Extend.type(this, options);
}
extract(path) {
path = Array.isArray(path) ? path : path.split('.');
return this._ids.reach(path);
}
fork(paths, adjuster) {
Assert(!this._inRuleset(), 'Cannot fork inside a ruleset');
let obj = this; // eslint-disable-line consistent-this
for (let path of [].concat(paths)) {
path = Array.isArray(path) ? path : path.split('.');
obj = obj._ids.fork(path, adjuster, obj);
}
obj.$_temp.ruleset = false;
return obj;
}
rule(options) {
const def = this._definition;
Common.assertOptions(options, Object.keys(def.modifiers));
Assert(this.$_temp.ruleset !== false, 'Cannot apply rules to empty ruleset or the last rule added does not support rule properties');
const start = this.$_temp.ruleset === null ? this._rules.length - 1 : this.$_temp.ruleset;
Assert(start >= 0 && start < this._rules.length, 'Cannot apply rules to empty ruleset');
const obj = this.clone();
for (let i = start; i < obj._rules.length; ++i) {
const original = obj._rules[i];
const rule = Clone(original);
for (const name in options) {
def.modifiers[name](rule, options[name]);
Assert(rule.name === original.name, 'Cannot change rule name');
}
obj._rules[i] = rule;
if (obj._singleRules.get(rule.name) === original) {
obj._singleRules.set(rule.name, rule);
}
}
obj.$_temp.ruleset = false;
return obj.$_mutateRebuild();
}
get ruleset() {
Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one');
const obj = this.clone();
obj.$_temp.ruleset = obj._rules.length;
return obj;
}
get $() {
return this.ruleset;
}
tailor(targets) {
targets = [].concat(targets);
Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset');
let obj = this; // eslint-disable-line consistent-this
if (this.$_terms.alterations) {
for (const { target, adjuster } of this.$_terms.alterations) {
if (targets.includes(target)) {
obj = adjuster(obj);
Assert(Common.isSchema(obj), 'Alteration adjuster for', target, 'failed to return a schema object');
}
}
}
obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false });
obj.$_temp.ruleset = false;
return obj.$_mutateRebuild();
}
tracer() {
return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$
}
validate(value, options) {
return Validator.entry(value, this, options);
}
validateAsync(value, options) {
return Validator.entryAsync(value, this, options);
}
// Extensions
$_addRule(options) {
// Normalize rule
if (typeof options === 'string') {
options = { name: options };
}
Assert(options && typeof options === 'object', 'Invalid options');
Assert(options.name && typeof options.name === 'string', 'Invalid rule name');
for (const key in options) {
Assert(key[0] !== '_', 'Cannot set private rule properties');
}
const rule = Object.assign({}, options); // Shallow cloned
rule._resolve = [];
rule.method = rule.method || rule.name;
const definition = this._definition.rules[rule.method];
const args = rule.args;
Assert(definition, 'Unknown rule', rule.method);
// Args
const obj = this.clone();
if (args) {
Assert(Object.keys(args).length === 1 || Object.keys(args).length === this._definition.rules[rule.name].args.length, 'Invalid rule definition for', this.type, rule.name);
for (const key in args) {
let arg = args[key];
if (definition.argsByName) {
const resolver = definition.argsByName.get(key);
if (resolver.ref &&
Common.isResolvable(arg)) {
rule._resolve.push(key);
obj.$_mutateRegister(arg);
}
else {
if (resolver.normalize) {
arg = resolver.normalize(arg);
args[key] = arg;
}
if (resolver.assert) {
const error = Common.validateArg(arg, key, resolver);
Assert(!error, error, 'or reference');
}
}
}
if (arg === undefined) {
delete args[key];
continue;
}
args[key] = arg;
}
}
// Unique rules
if (!definition.multi) {
obj._ruleRemove(rule.name, { clone: false });
obj._singleRules.set(rule.name, rule);
}
if (obj.$_temp.ruleset === false) {
obj.$_temp.ruleset = null;
}
if (definition.priority) {
obj._rules.unshift(rule);
}
else {
obj._rules.push(rule);
}
return obj;
}
$_compile(schema, options) {
return Compile.schema(this.$_root, schema, options);
}
$_createError(code, value, local, state, prefs, options = {}) {
const flags = options.flags !== false ? this._flags : {};
const messages = options.messages ? Messages.merge(this._definition.messages, options.messages) : this._definition.messages;
return new Errors.Report(code, value, local, flags, messages, state, prefs);
}
$_getFlag(name) {
return this._flags[name];
}
$_getRule(name) {
return this._singleRules.get(name);
}
$_mapLabels(path) {
path = Array.isArray(path) ? path : path.split('.');
return this._ids.labels(path);
}
$_match(value, state, prefs, overrides) {
prefs = Object.assign({}, prefs); // Shallow cloned
prefs.abortEarly = true;
prefs._externals = false;
state.snapshot();
const result = !Validator.validate(value, this, state, prefs, overrides).errors;
state.restore();
return result;
}
$_modify(options) {
Common.assertOptions(options, ['each', 'once', 'ref', 'schema']);
return Modify.schema(this, options) || this;
}
$_mutateRebuild() {
Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset');
this._refs.reset();
this._ids.reset();
const each = (item, { source, name, path, key }) => {
const family = this._definition[source][name] && this._definition[source][name].register;
if (family !== false) {
this.$_mutateRegister(item, { family, key });
}
};
this.$_modify({ each });
if (this._definition.rebuild) {
this._definition.rebuild(this);
}
this.$_temp.ruleset = false;
return this;
}
$_mutateRegister(schema, { family, key } = {}) {
this._refs.register(schema, family);
this._ids.register(schema, { key });
}
$_property(name) {
return this._definition.properties[name];
}
$_reach(path) {
return this._ids.reach(path);
}
$_rootReferences() {
return this._refs.roots();
}
$_setFlag(name, value, options = {}) {
Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset');
const flag = this._definition.flags[name] || {};
if (DeepEqual(value, flag.default)) {
value = undefined;
}
if (DeepEqual(value, this._flags[name])) {
return this;
}
const obj = options.clone !== false ? this.clone() : this;
if (value !== undefined) {
obj._flags[name] = value;
obj.$_mutateRegister(value);
}
else {
delete obj._flags[name];
}
if (name[0] !== '_') {
obj.$_temp.ruleset = false;
}
return obj;
}
$_parent(method, ...args) {
return this[method][Common.symbols.parent].call(this, ...args);
}
$_validate(value, state, prefs) {
return Validator.validate(value, this, state, prefs);
}
// Internals
_assign(target) {
target.type = this.type;
target.$_root = this.$_root;
target.$_temp = Object.assign({}, this.$_temp);
target.$_temp.whens = {};
target._ids = this._ids.clone();
target._preferences = this._preferences;
target._valids = this._valids && this._valids.clone();
target._invalids = this._invalids && this._invalids.clone();
target._rules = this._rules.slice();
target._singleRules = Clone(this._singleRules, { shallow: true });
target._refs = this._refs.clone();
target._flags = Object.assign({}, this._flags);
target._cache = null;
target.$_terms = {};
for (const key in this.$_terms) {
target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null;
}
// Backwards compatibility
target.$_super = {};
for (const override in this.$_super) {
target.$_super[override] = this._super[override].bind(target);
}
return target;
}
_bare() {
const obj = this.clone();
obj._reset();
const terms = obj._definition.terms;
for (const name in terms) {
const term = terms[name];
obj.$_terms[name] = term.init;
}
return obj.$_mutateRebuild();
}
_default(flag, value, options = {}) {
Common.assertOptions(options, 'literal');
Assert(value !== undefined, 'Missing', flag, 'value');
Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option');
if (typeof value === 'function' &&
options.literal) {
value = {
[Common.symbols.literal]: true,
literal: value
};
}
const obj = this.$_setFlag(flag, value);
return obj;
}
_generate(value, state, prefs) {
if (!this.$_terms.whens) {
return { schema: this };
}
// Collect matching whens
const whens = [];
const ids = [];
for (let i = 0; i < this.$_terms.whens.length; ++i) {
const when = this.$_terms.whens[i];
if (when.concat) {
whens.push(when.concat);
ids.push(`${i}.concat`);
continue;
}
const input = when.ref ? when.ref.resolve(value, state, prefs) : value;
const tests = when.is ? [when] : when.switch;
const before = ids.length;
for (let j = 0; j < tests.length; ++j) {
const { is, then, otherwise } = tests[j];
const baseId = `${i}${when.switch ? '.' + j : ''}`;
if (is.$_match(input, state.nest(is, `${baseId}.is`), prefs)) {
if (then) {
const localState = state.localize([...state.path, `${baseId}.then`], state.ancestors, state.schemas);
const { schema: generated, id } = then._generate(value, localState, prefs);
whens.push(generated);
ids.push(`${baseId}.then${id ? `(${id})` : ''}`);
break;
}
}
else if (otherwise) {
const localState = state.localize([...state.path, `${baseId}.otherwise`], state.ancestors, state.schemas);
const { schema: generated, id } = otherwise._generate(value, localState, prefs);
whens.push(generated);
ids.push(`${baseId}.otherwise${id ? `(${id})` : ''}`);
break;
}
}
if (when.break &&
ids.length > before) { // Something matched
break;
}
}
// Check cache
const id = ids.join(', ');
state.mainstay.tracer.debug(state, 'rule', 'when', id);
if (!id) {
return { schema: this };
}
if (!state.mainstay.tracer.active &&
this.$_temp.whens[id]) {
return { schema: this.$_temp.whens[id], id };
}
// Generate dynamic schema
let obj = this; // eslint-disable-line consistent-this
if (this._definition.generate) {
obj = this._definition.generate(this, value, state, prefs);
}
// Apply whens
for (const when of whens) {
obj = obj.concat(when);
}
// Tracing
if (this.$_root._tracer) {
this.$_root._tracer._combine(obj, [this, ...whens]);
}
// Cache result
this.$_temp.whens[id] = obj;
return { schema: obj, id };
}
_inner(type, values, options = {}) {
Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`);
const obj = this.clone();
if (!obj.$_terms[type] ||
options.override) {
obj.$_terms[type] = [];
}
if (options.single) {
obj.$_terms[type].push(values);
}
else {
obj.$_terms[type].push(...values);
}
obj.$_temp.ruleset = false;
return obj;
}
_inRuleset() {
return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false;
}
_ruleRemove(name, options = {}) {
if (!this._singleRules.has(name)) {
return this;
}
const obj = options.clone !== false ? this.clone() : this;
obj._singleRules.delete(name);
const filtered = [];
for (let i = 0; i < obj._rules.length; ++i) {
const test = obj._rules[i];
if (test.name === name &&
!test.keep) {
if (obj._inRuleset() &&
i < obj.$_temp.ruleset) {
--obj.$_temp.ruleset;
}
continue;
}
filtered.push(test);
}
obj._rules = filtered;
return obj;
}
_values(values, key) {
Common.verifyFlat(values, key.slice(1, -1));
const obj = this.clone();
const override = values[0] === Common.symbols.override;
if (override) {
values = values.slice(1);
}
if (!obj[key] &&
values.length) {
obj[key] = new Values();
}
else if (override) {
obj[key] = values.length ? new Values() : null;
obj.$_mutateRebuild();
}
if (!obj[key]) {
return obj;
}
if (override) {
obj[key].override();
}
for (const value of values) {
Assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined');
Assert(value !== Common.symbols.override, 'Override must be the first value');
const other = key === '_invalids' ? '_valids' : '_invalids';
if (obj[other]) {
obj[other].remove(value);
if (!obj[other].length) {
Assert(key === '_valids' || !obj._flags.only, 'Setting invalid value', value, 'leaves schema rejecting all values due to previous valid rule');
obj[other] = null;
}
}
obj[key].add(value, obj._refs);
}
return obj;
}
};
internals.Base.prototype[Common.symbols.any] = {
version: Common.version,
compile: Compile.compile,
root: '$_root'
};
internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype)
// Aliases
internals.Base.prototype.deny = internals.Base.prototype.invalid;
internals.Base.prototype.disallow = internals.Base.prototype.invalid;
internals.Base.prototype.equal = internals.Base.prototype.valid;
internals.Base.prototype.exist = internals.Base.prototype.required;
internals.Base.prototype.not = internals.Base.prototype.invalid;
internals.Base.prototype.options = internals.Base.prototype.prefs;
internals.Base.prototype.preferences = internals.Base.prototype.prefs;
module.exports = new internals.Base();
/***/ }),
/***/ 63355:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Common = __nccwpck_require__(72448);
const internals = {
max: 1000,
supported: new Set(['undefined', 'boolean', 'number', 'string'])
};
exports.provider = {
provision(options) {
return new internals.Cache(options);
}
};
// Least Recently Used (LRU) Cache
internals.Cache = class {
constructor(options = {}) {
Common.assertOptions(options, ['max']);
Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size');
this._max = options.max || internals.max;
this._map = new Map(); // Map of nodes by key
this._list = new internals.List(); // List of nodes (most recently used in head)
}
get length() {
return this._map.size;
}
set(key, value) {
if (key !== null &&
!internals.supported.has(typeof key)) {
return;
}
let node = this._map.get(key);
if (node) {
node.value = value;
this._list.first(node);
return;
}
node = this._list.unshift({ key, value });
this._map.set(key, node);
this._compact();
}
get(key) {
const node = this._map.get(key);
if (node) {
this._list.first(node);
return Clone(node.value);
}
}
_compact() {
if (this._map.size > this._max) {
const node = this._list.pop();
this._map.delete(node.key);
}
}
};
internals.List = class {
constructor() {
this.tail = null;
this.head = null;
}
unshift(node) {
node.next = null;
node.prev = this.head;
if (this.head) {
this.head.next = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
return node;
}
first(node) {
if (node === this.head) {
return;
}
this._remove(node);
this.unshift(node);
}
pop() {
return this._remove(this.tail);
}
_remove(node) {
const { next, prev } = node;
next.prev = prev;
if (prev) {
prev.next = next;
}
if (node === this.tail) {
this.tail = next;
}
node.prev = null;
node.next = null;
return node;
}
};
/***/ }),
/***/ 72448:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const AssertError = __nccwpck_require__(35563);
const Pkg = __nccwpck_require__(77045);
let Messages;
let Schemas;
const internals = {
isoDate: /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/
};
exports.version = Pkg.version;
exports.defaults = {
abortEarly: true,
allowUnknown: false,
artifacts: false,
cache: true,
context: null,
convert: true,
dateFormat: 'iso',
errors: {
escapeHtml: false,
label: 'path',
language: null,
render: true,
stack: false,
wrap: {
label: '"',
array: '[]'
}
},
externals: true,
messages: {},
nonEnumerables: false,
noDefaults: false,
presence: 'optional',
skipFunctions: false,
stripUnknown: false,
warnings: false
};
exports.symbols = {
any: Symbol.for('@hapi/joi/schema'), // Used to internally identify any-based types (shared with other joi versions)
arraySingle: Symbol('arraySingle'),
deepDefault: Symbol('deepDefault'),
errors: Symbol('errors'),
literal: Symbol('literal'),
override: Symbol('override'),
parent: Symbol('parent'),
prefs: Symbol('prefs'),
ref: Symbol('ref'),
template: Symbol('template'),
values: Symbol('values')
};
exports.assertOptions = function (options, keys, name = 'Options') {
Assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be of type object');
const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k));
Assert(unknownKeys.length === 0, `${name} contain unknown keys: ${unknownKeys}`);
};
exports.checkPreferences = function (prefs) {
Schemas = Schemas || __nccwpck_require__(85614);
const result = Schemas.preferences.validate(prefs);
if (result.error) {
throw new AssertError([result.error.details[0].message]);
}
};
exports.compare = function (a, b, operator) {
switch (operator) {
case '=': return a === b;
case '>': return a > b;
case '<': return a < b;
case '>=': return a >= b;
case '<=': return a <= b;
}
};
exports["default"] = function (value, defaultValue) {
return value === undefined ? defaultValue : value;
};
exports.isIsoDate = function (date) {
return internals.isoDate.test(date);
};
exports.isNumber = function (value) {
return typeof value === 'number' && !isNaN(value);
};
exports.isResolvable = function (obj) {
if (!obj) {
return false;
}
return obj[exports.symbols.ref] || obj[exports.symbols.template];
};
exports.isSchema = function (schema, options = {}) {
const any = schema && schema[exports.symbols.any];
if (!any) {
return false;
}
Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas');
return true;
};
exports.isValues = function (obj) {
return obj[exports.symbols.values];
};
exports.limit = function (value) {
return Number.isSafeInteger(value) && value >= 0;
};
exports.preferences = function (target, source) {
Messages = Messages || __nccwpck_require__(86103);
target = target || {};
source = source || {};
const merged = Object.assign({}, target, source);
if (source.errors &&
target.errors) {
merged.errors = Object.assign({}, target.errors, source.errors);
merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap);
}
if (source.messages) {
merged.messages = Messages.compile(source.messages, target.messages);
}
delete merged[exports.symbols.prefs];
return merged;
};
exports.tryWithPath = function (fn, key, options = {}) {
try {
return fn();
}
catch (err) {
if (err.path !== undefined) {
err.path = key + '.' + err.path;
}
else {
err.path = key;
}
if (options.append) {
err.message = `${err.message} (${err.path})`;
}
throw err;
}
};
exports.validateArg = function (value, label, { assert, message }) {
if (exports.isSchema(assert)) {
const result = assert.validate(value);
if (!result.error) {
return;
}
return result.error.message;
}
else if (!assert(value)) {
return label ? `${label} ${message}` : message;
}
};
exports.verifyFlat = function (args, method) {
for (const arg of args) {
Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method);
}
};
/***/ }),
/***/ 3038:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Common = __nccwpck_require__(72448);
const Ref = __nccwpck_require__(73838);
const internals = {};
exports.schema = function (Joi, config, options = {}) {
Common.assertOptions(options, ['appendPath', 'override']);
try {
return internals.schema(Joi, config, options);
}
catch (err) {
if (options.appendPath &&
err.path !== undefined) {
err.message = `${err.message} (${err.path})`;
}
throw err;
}
};
internals.schema = function (Joi, config, options) {
Assert(config !== undefined, 'Invalid undefined schema');
if (Array.isArray(config)) {
Assert(config.length, 'Invalid empty array schema');
if (config.length === 1) {
config = config[0];
}
}
const valid = (base, ...values) => {
if (options.override !== false) {
return base.valid(Joi.override, ...values);
}
return base.valid(...values);
};
if (internals.simple(config)) {
return valid(Joi, config);
}
if (typeof config === 'function') {
return Joi.custom(config);
}
Assert(typeof config === 'object', 'Invalid schema content:', typeof config);
if (Common.isResolvable(config)) {
return valid(Joi, config);
}
if (Common.isSchema(config)) {
return config;
}
if (Array.isArray(config)) {
for (const item of config) {
if (!internals.simple(item)) {
return Joi.alternatives().try(...config);
}
}
return valid(Joi, ...config);
}
if (config instanceof RegExp) {
return Joi.string().regex(config);
}
if (config instanceof Date) {
return valid(Joi.date(), config);
}
Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects');
return Joi.object().keys(config);
};
exports.ref = function (id, options) {
return Ref.isRef(id) ? id : Ref.create(id, options);
};
exports.compile = function (root, schema, options = {}) {
Common.assertOptions(options, ['legacy']);
// Compiled by any supported version
const any = schema && schema[Common.symbols.any];
if (any) {
Assert(options.legacy || any.version === Common.version, 'Cannot mix different versions of joi schemas:', any.version, Common.version);
return schema;
}
// Uncompiled root
if (typeof schema !== 'object' ||
!options.legacy) {
return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions
}
// Scan schema for compiled parts
const compiler = internals.walk(schema);
if (!compiler) {
return exports.schema(root, schema, { appendPath: true });
}
return compiler.compile(compiler.root, schema);
};
internals.walk = function (schema) {
if (typeof schema !== 'object') {
return null;
}
if (Array.isArray(schema)) {
for (const item of schema) {
const compiler = internals.walk(item);
if (compiler) {
return compiler;
}
}
return null;
}
const any = schema[Common.symbols.any];
if (any) {
return { root: schema[any.root], compile: any.compile };
}
Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects');
for (const key in schema) {
const compiler = internals.walk(schema[key]);
if (compiler) {
return compiler;
}
}
return null;
};
internals.simple = function (value) {
return value === null || ['boolean', 'string', 'number'].includes(typeof value);
};
exports.when = function (schema, condition, options) {
if (options === undefined) {
Assert(condition && typeof condition === 'object', 'Missing options');
options = condition;
condition = Ref.create('.');
}
if (Array.isArray(options)) {
options = { switch: options };
}
Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']);
// Schema condition
if (Common.isSchema(condition)) {
Assert(options.is === undefined, '"is" can not be used with a schema condition');
Assert(options.not === undefined, '"not" can not be used with a schema condition');
Assert(options.switch === undefined, '"switch" can not be used with a schema condition');
return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break });
}
// Single condition
Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition);
Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"');
if (options.switch === undefined) {
let rule = options;
if (options.not !== undefined) {
rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break };
}
let is = rule.is !== undefined ? schema.$_compile(rule.is) : schema.$_root.invalid(null, false, 0, '').required();
Assert(rule.then !== undefined || rule.otherwise !== undefined, 'options must have at least one of "then", "otherwise", or "switch"');
Assert(rule.break === undefined || rule.then === undefined || rule.otherwise === undefined, 'Cannot specify then, otherwise, and break all together');
if (options.is !== undefined &&
!Ref.isRef(options.is) &&
!Common.isSchema(options.is)) {
is = is.required(); // Only apply required if this wasn't already a schema or a ref
}
return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break });
}
// Switch statement
Assert(Array.isArray(options.switch), '"switch" must be an array');
Assert(options.is === undefined, 'Cannot combine "switch" with "is"');
Assert(options.not === undefined, 'Cannot combine "switch" with "not"');
Assert(options.then === undefined, 'Cannot combine "switch" with "then"');
const rule = {
ref: exports.ref(condition),
switch: [],
break: options.break
};
for (let i = 0; i < options.switch.length; ++i) {
const test = options.switch[i];
const last = i === options.switch.length - 1;
Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']);
Assert(test.is !== undefined, 'Switch statement missing "is"');
Assert(test.then !== undefined, 'Switch statement missing "then"');
const item = {
is: schema.$_compile(test.is),
then: schema.$_compile(test.then)
};
if (!Ref.isRef(test.is) &&
!Common.isSchema(test.is)) {
item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref
}
if (last) {
Assert(options.otherwise === undefined || test.otherwise === undefined, 'Cannot specify "otherwise" inside and outside a "switch"');
const otherwise = options.otherwise !== undefined ? options.otherwise : test.otherwise;
if (otherwise !== undefined) {
Assert(rule.break === undefined, 'Cannot specify both otherwise and break');
item.otherwise = schema.$_compile(otherwise);
}
}
rule.switch.push(item);
}
return rule;
};
internals.condition = function (schema, condition) {
for (const key of ['then', 'otherwise']) {
if (condition[key] === undefined) {
delete condition[key];
}
else {
condition[key] = schema.$_compile(condition[key]);
}
}
return condition;
};
/***/ }),
/***/ 69490:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Annotate = __nccwpck_require__(46014);
const Common = __nccwpck_require__(72448);
const Template = __nccwpck_require__(51396);
const internals = {};
exports.Report = class {
constructor(code, value, local, flags, messages, state, prefs) {
this.code = code;
this.flags = flags;
this.messages = messages;
this.path = state.path;
this.prefs = prefs;
this.state = state;
this.value = value;
this.message = null;
this.template = null;
this.local = local || {};
this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages);
if (this.value !== undefined &&
!this.local.hasOwnProperty('value')) {
this.local.value = this.value;
}
if (this.path.length) {
const key = this.path[this.path.length - 1];
if (typeof key !== 'object') {
this.local.key = key;
}
}
}
_setTemplate(template) {
this.template = template;
if (!this.flags.label &&
this.path.length === 0) {
const localized = this._template(this.template, 'root');
if (localized) {
this.local.label = localized;
}
}
}
toString() {
if (this.message) {
return this.message;
}
const code = this.code;
if (!this.prefs.errors.render) {
return this.code;
}
const template = this._template(this.template) ||
this._template(this.prefs.messages) ||
this._template(this.messages);
if (template === undefined) {
return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`;
}
// Render and cache result
this.message = template.render(this.value, this.state, this.prefs, this.local, { errors: this.prefs.errors, messages: [this.prefs.messages, this.messages] });
if (!this.prefs.errors.label) {
this.message = this.message.replace(/^"" /, '').trim();
}
return this.message;
}
_template(messages, code) {
return exports.template(this.value, messages, code || this.code, this.state, this.prefs);
}
};
exports.path = function (path) {
let label = '';
for (const segment of path) {
if (typeof segment === 'object') { // Exclude array single path segment
continue;
}
if (typeof segment === 'string') {
if (label) {
label += '.';
}
label += segment;
}
else {
label += `[${segment}]`;
}
}
return label;
};
exports.template = function (value, messages, code, state, prefs) {
if (!messages) {
return;
}
if (Template.isTemplate(messages)) {
return code !== 'root' ? messages : null;
}
let lang = prefs.errors.language;
if (Common.isResolvable(lang)) {
lang = lang.resolve(value, state, prefs);
}
if (lang &&
messages[lang]) {
if (messages[lang][code] !== undefined) {
return messages[lang][code];
}
if (messages[lang]['*'] !== undefined) {
return messages[lang]['*'];
}
}
if (!messages[code]) {
return messages['*'];
}
return messages[code];
};
exports.label = function (flags, state, prefs, messages) {
if (!prefs.errors.label) {
return '';
}
if (flags.label) {
return flags.label;
}
let path = state.path;
if (prefs.errors.label === 'key' &&
state.path.length > 1) {
path = state.path.slice(-1);
}
const normalized = exports.path(path);
if (normalized) {
return normalized;
}
return exports.template(null, prefs.messages, 'root', state, prefs) ||
messages && exports.template(null, messages, 'root', state, prefs) ||
'value';
};
exports.process = function (errors, original, prefs) {
if (!errors) {
return null;
}
const { override, message, details } = exports.details(errors);
if (override) {
return override;
}
if (prefs.errors.stack) {
return new exports.ValidationError(message, details, original);
}
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
const validationError = new exports.ValidationError(message, details, original);
Error.stackTraceLimit = limit;
return validationError;
};
exports.details = function (errors, options = {}) {
let messages = [];
const details = [];
for (const item of errors) {
// Override
if (item instanceof Error) {
if (options.override !== false) {
return { override: item };
}
const message = item.toString();
messages.push(message);
details.push({
message,
type: 'override',
context: { error: item }
});
continue;
}
// Report
const message = item.toString();
messages.push(message);
details.push({
message,
path: item.path.filter((v) => typeof v !== 'object'),
type: item.code,
context: item.local
});
}
if (messages.length > 1) {
messages = [...new Set(messages)];
}
return { message: messages.join('. '), details };
};
exports.ValidationError = class extends Error {
constructor(message, details, original) {
super(message);
this._original = original;
this.details = details;
}
static isError(err) {
return err instanceof exports.ValidationError;
}
};
exports.ValidationError.prototype.isJoi = true;
exports.ValidationError.prototype.name = 'ValidationError';
exports.ValidationError.prototype.annotate = Annotate.error;
/***/ }),
/***/ 86680:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Common = __nccwpck_require__(72448);
const Messages = __nccwpck_require__(86103);
const internals = {};
exports.type = function (from, options) {
const base = Object.getPrototypeOf(from);
const prototype = Clone(base);
const schema = from._assign(Object.create(prototype));
const def = Object.assign({}, options); // Shallow cloned
delete def.base;
prototype._definition = def;
const parent = base._definition || {};
def.messages = Messages.merge(parent.messages, def.messages);
def.properties = Object.assign({}, parent.properties, def.properties);
// Type
schema.type = def.type;
// Flags
def.flags = Object.assign({}, parent.flags, def.flags);
// Terms
const terms = Object.assign({}, parent.terms);
if (def.terms) {
for (const name in def.terms) { // Only apply own terms
const term = def.terms[name];
Assert(schema.$_terms[name] === undefined, 'Invalid term override for', def.type, name);
schema.$_terms[name] = term.init;
terms[name] = term;
}
}
def.terms = terms;
// Constructor arguments
if (!def.args) {
def.args = parent.args;
}
// Prepare
def.prepare = internals.prepare(def.prepare, parent.prepare);
// Coerce
if (def.coerce) {
if (typeof def.coerce === 'function') {
def.coerce = { method: def.coerce };
}
if (def.coerce.from &&
!Array.isArray(def.coerce.from)) {
def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) };
}
}
def.coerce = internals.coerce(def.coerce, parent.coerce);
// Validate
def.validate = internals.validate(def.validate, parent.validate);
// Rules
const rules = Object.assign({}, parent.rules);
if (def.rules) {
for (const name in def.rules) {
const rule = def.rules[name];
Assert(typeof rule === 'object', 'Invalid rule definition for', def.type, name);
let method = rule.method;
if (method === undefined) {
method = function () {
return this.$_addRule(name);
};
}
if (method) {
Assert(!prototype[name], 'Rule conflict in', def.type, name);
prototype[name] = method;
}
Assert(!rules[name], 'Rule conflict in', def.type, name);
rules[name] = rule;
if (rule.alias) {
const aliases = [].concat(rule.alias);
for (const alias of aliases) {
prototype[alias] = rule.method;
}
}
if (rule.args) {
rule.argsByName = new Map();
rule.args = rule.args.map((arg) => {
if (typeof arg === 'string') {
arg = { name: arg };
}
Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name);
if (Common.isSchema(arg.assert)) {
arg.assert = arg.assert.strict().label(arg.name);
}
rule.argsByName.set(arg.name, arg);
return arg;
});
}
}
}
def.rules = rules;
// Modifiers
const modifiers = Object.assign({}, parent.modifiers);
if (def.modifiers) {
for (const name in def.modifiers) {
Assert(!prototype[name], 'Rule conflict in', def.type, name);
const modifier = def.modifiers[name];
Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name);
const method = function (arg) {
return this.rule({ [name]: arg });
};
prototype[name] = method;
modifiers[name] = modifier;
}
}
def.modifiers = modifiers;
// Overrides
if (def.overrides) {
prototype._super = base;
schema.$_super = {}; // Backwards compatibility
for (const override in def.overrides) {
Assert(base[override], 'Cannot override missing', override);
def.overrides[override][Common.symbols.parent] = base[override];
schema.$_super[override] = base[override].bind(schema); // Backwards compatibility
}
Object.assign(prototype, def.overrides);
}
// Casts
def.cast = Object.assign({}, parent.cast, def.cast);
// Manifest
const manifest = Object.assign({}, parent.manifest, def.manifest);
manifest.build = internals.build(def.manifest && def.manifest.build, parent.manifest && parent.manifest.build);
def.manifest = manifest;
// Rebuild
def.rebuild = internals.rebuild(def.rebuild, parent.rebuild);
return schema;
};
// Helpers
internals.build = function (child, parent) {
if (!child ||
!parent) {
return child || parent;
}
return function (obj, desc) {
return parent(child(obj, desc), desc);
};
};
internals.coerce = function (child, parent) {
if (!child ||
!parent) {
return child || parent;
}
return {
from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null,
method(value, helpers) {
let coerced;
if (!parent.from ||
parent.from.includes(typeof value)) {
coerced = parent.method(value, helpers);
if (coerced) {
if (coerced.errors ||
coerced.value === undefined) {
return coerced;
}
value = coerced.value;
}
}
if (!child.from ||
child.from.includes(typeof value)) {
const own = child.method(value, helpers);
if (own) {
return own;
}
}
return coerced;
}
};
};
internals.prepare = function (child, parent) {
if (!child ||
!parent) {
return child || parent;
}
return function (value, helpers) {
const prepared = child(value, helpers);
if (prepared) {
if (prepared.errors ||
prepared.value === undefined) {
return prepared;
}
value = prepared.value;
}
return parent(value, helpers) || prepared;
};
};
internals.rebuild = function (child, parent) {
if (!child ||
!parent) {
return child || parent;
}
return function (schema) {
parent(schema);
child(schema);
};
};
internals.validate = function (child, parent) {
if (!child ||
!parent) {
return child || parent;
}
return function (value, helpers) {
const result = parent(value, helpers);
if (result) {
if (result.errors &&
(!Array.isArray(result.errors) || result.errors.length)) {
return result;
}
value = result.value;
}
return child(value, helpers) || result;
};
};
/***/ }),
/***/ 20918:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Cache = __nccwpck_require__(63355);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const Errors = __nccwpck_require__(69490);
const Extend = __nccwpck_require__(86680);
const Manifest = __nccwpck_require__(87997);
const Ref = __nccwpck_require__(73838);
const Template = __nccwpck_require__(51396);
const Trace = __nccwpck_require__(43171);
let Schemas;
const internals = {
types: {
alternatives: __nccwpck_require__(26867),
any: __nccwpck_require__(9512),
array: __nccwpck_require__(20270),
boolean: __nccwpck_require__(47489),
date: __nccwpck_require__(6624),
function: __nccwpck_require__(62269),
link: __nccwpck_require__(69869),
number: __nccwpck_require__(15855),
object: __nccwpck_require__(46878),
string: __nccwpck_require__(72260),
symbol: __nccwpck_require__(40971)
},
aliases: {
alt: 'alternatives',
bool: 'boolean',
func: 'function'
}
};
if (Buffer) { // $lab:coverage:ignore$
internals.types.binary = __nccwpck_require__(34288);
}
internals.root = function () {
const root = {
_types: new Set(Object.keys(internals.types))
};
// Types
for (const type of root._types) {
root[type] = function (...args) {
Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments');
return internals.generate(this, internals.types[type], args);
};
}
// Shortcuts
for (const method of ['allow', 'custom', 'disallow', 'equal', 'exist', 'forbidden', 'invalid', 'not', 'only', 'optional', 'options', 'prefs', 'preferences', 'required', 'strip', 'valid', 'when']) {
root[method] = function (...args) {
return this.any()[method](...args);
};
}
// Methods
Object.assign(root, internals.methods);
// Aliases
for (const alias in internals.aliases) {
const target = internals.aliases[alias];
root[alias] = root[target];
}
root.x = root.expression;
// Trace
if (Trace.setup) { // $lab:coverage:ignore$
Trace.setup(root);
}
return root;
};
internals.methods = {
ValidationError: Errors.ValidationError,
version: Common.version,
cache: Cache.provider,
assert(value, schema, ...args /* [message], [options] */) {
internals.assert(value, schema, true, args);
},
attempt(value, schema, ...args /* [message], [options] */) {
return internals.assert(value, schema, false, args);
},
build(desc) {
Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled');
return Manifest.build(this, desc);
},
checkPreferences(prefs) {
Common.checkPreferences(prefs);
},
compile(schema, options) {
return Compile.compile(this, schema, options);
},
defaults(modifier) {
Assert(typeof modifier === 'function', 'modifier must be a function');
const joi = Object.assign({}, this);
for (const type of joi._types) {
const schema = modifier(joi[type]());
Assert(Common.isSchema(schema), 'modifier must return a valid schema object');
joi[type] = function (...args) {
return internals.generate(this, schema, args);
};
}
return joi;
},
expression(...args) {
return new Template(...args);
},
extend(...extensions) {
Common.verifyFlat(extensions, 'extend');
Schemas = Schemas || __nccwpck_require__(85614);
Assert(extensions.length, 'You need to provide at least one extension');
this.assert(extensions, Schemas.extensions);
const joi = Object.assign({}, this);
joi._types = new Set(joi._types);
for (let extension of extensions) {
if (typeof extension === 'function') {
extension = extension(joi);
}
this.assert(extension, Schemas.extension);
const expanded = internals.expandExtension(extension, joi);
for (const item of expanded) {
Assert(joi[item.type] === undefined || joi._types.has(item.type), 'Cannot override name', item.type);
const base = item.base || this.any();
const schema = Extend.type(base, item);
joi._types.add(item.type);
joi[item.type] = function (...args) {
return internals.generate(this, schema, args);
};
}
}
return joi;
},
isError: Errors.ValidationError.isError,
isExpression: Template.isTemplate,
isRef: Ref.isRef,
isSchema: Common.isSchema,
in(...args) {
return Ref.in(...args);
},
override: Common.symbols.override,
ref(...args) {
return Ref.create(...args);
},
types() {
const types = {};
for (const type of this._types) {
types[type] = this[type]();
}
for (const target in internals.aliases) {
types[target] = this[target]();
}
return types;
}
};
// Helpers
internals.assert = function (value, schema, annotate, args /* [message], [options] */) {
const message = args[0] instanceof Error || typeof args[0] === 'string' ? args[0] : null;
const options = message !== null ? args[1] : args[0];
const result = schema.validate(value, Common.preferences({ errors: { stack: true } }, options || {}));
let error = result.error;
if (!error) {
return result.value;
}
if (message instanceof Error) {
throw message;
}
const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message;
if (error instanceof Errors.ValidationError === false) {
error = Clone(error);
}
error.message = message ? `${message} ${display}` : display;
throw error;
};
internals.generate = function (root, schema, args) {
Assert(root, 'Must be invoked on a Joi instance.');
schema.$_root = root;
if (!schema._definition.args ||
!args.length) {
return schema;
}
return schema._definition.args(schema, ...args);
};
internals.expandExtension = function (extension, joi) {
if (typeof extension.type === 'string') {
return [extension];
}
const extended = [];
for (const type of joi._types) {
if (extension.type.test(type)) {
const item = Object.assign({}, extension);
item.type = type;
item.base = joi[type]();
extended.push(item);
}
}
return extended;
};
module.exports = internals.root();
/***/ }),
/***/ 87997:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Common = __nccwpck_require__(72448);
const Messages = __nccwpck_require__(86103);
const Ref = __nccwpck_require__(73838);
const Template = __nccwpck_require__(51396);
let Schemas;
const internals = {};
exports.describe = function (schema) {
const def = schema._definition;
// Type
const desc = {
type: schema.type,
flags: {},
rules: []
};
// Flags
for (const flag in schema._flags) {
if (flag[0] !== '_') {
desc.flags[flag] = internals.describe(schema._flags[flag]);
}
}
if (!Object.keys(desc.flags).length) {
delete desc.flags;
}
// Preferences
if (schema._preferences) {
desc.preferences = Clone(schema._preferences, { shallow: ['messages'] });
delete desc.preferences[Common.symbols.prefs];
if (desc.preferences.messages) {
desc.preferences.messages = Messages.decompile(desc.preferences.messages);
}
}
// Allow / Invalid
if (schema._valids) {
desc.allow = schema._valids.describe();
}
if (schema._invalids) {
desc.invalid = schema._invalids.describe();
}
// Rules
for (const rule of schema._rules) {
const ruleDef = def.rules[rule.name];
if (ruleDef.manifest === false) { // Defaults to true
continue;
}
const item = { name: rule.name };
for (const custom in def.modifiers) {
if (rule[custom] !== undefined) {
item[custom] = internals.describe(rule[custom]);
}
}
if (rule.args) {
item.args = {};
for (const key in rule.args) {
const arg = rule.args[key];
if (key === 'options' &&
!Object.keys(arg).length) {
continue;
}
item.args[key] = internals.describe(arg, { assign: key });
}
if (!Object.keys(item.args).length) {
delete item.args;
}
}
desc.rules.push(item);
}
if (!desc.rules.length) {
delete desc.rules;
}
// Terms (must be last to verify no name conflicts)
for (const term in schema.$_terms) {
if (term[0] === '_') {
continue;
}
Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term);
const items = schema.$_terms[term];
if (!items) {
continue;
}
if (items instanceof Map) {
if (items.size) {
desc[term] = [...items.entries()];
}
continue;
}
if (Common.isValues(items)) {
desc[term] = items.describe();
continue;
}
Assert(def.terms[term], 'Term', term, 'missing configuration');
const manifest = def.terms[term].manifest;
const mapped = typeof manifest === 'object';
if (!items.length &&
!mapped) {
continue;
}
const normalized = [];
for (const item of items) {
normalized.push(internals.describe(item));
}
// Mapped
if (mapped) {
const { from, to } = manifest.mapped;
desc[term] = {};
for (const item of normalized) {
desc[term][item[to]] = item[from];
}
continue;
}
// Single
if (manifest === 'single') {
Assert(normalized.length === 1, 'Term', term, 'contains more than one item');
desc[term] = normalized[0];
continue;
}
// Array
desc[term] = normalized;
}
internals.validate(schema.$_root, desc);
return desc;
};
internals.describe = function (item, options = {}) {
if (Array.isArray(item)) {
return item.map(internals.describe);
}
if (item === Common.symbols.deepDefault) {
return { special: 'deep' };
}
if (typeof item !== 'object' ||
item === null) {
return item;
}
if (options.assign === 'options') {
return Clone(item);
}
if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$
return { buffer: item.toString('binary') };
}
if (item instanceof Date) {
return item.toISOString();
}
if (item instanceof Error) {
return item;
}
if (item instanceof RegExp) {
if (options.assign === 'regex') {
return item.toString();
}
return { regex: item.toString() };
}
if (item[Common.symbols.literal]) {
return { function: item.literal };
}
if (typeof item.describe === 'function') {
if (options.assign === 'ref') {
return item.describe().ref;
}
return item.describe();
}
const normalized = {};
for (const key in item) {
const value = item[key];
if (value === undefined) {
continue;
}
normalized[key] = internals.describe(value, { assign: key });
}
return normalized;
};
exports.build = function (joi, desc) {
const builder = new internals.Builder(joi);
return builder.parse(desc);
};
internals.Builder = class {
constructor(joi) {
this.joi = joi;
}
parse(desc) {
internals.validate(this.joi, desc);
// Type
let schema = this.joi[desc.type]()._bare();
const def = schema._definition;
// Flags
if (desc.flags) {
for (const flag in desc.flags) {
const setter = def.flags[flag] && def.flags[flag].setter || flag;
Assert(typeof schema[setter] === 'function', 'Invalid flag', flag, 'for type', desc.type);
schema = schema[setter](this.build(desc.flags[flag]));
}
}
// Preferences
if (desc.preferences) {
schema = schema.preferences(this.build(desc.preferences));
}
// Allow / Invalid
if (desc.allow) {
schema = schema.allow(...this.build(desc.allow));
}
if (desc.invalid) {
schema = schema.invalid(...this.build(desc.invalid));
}
// Rules
if (desc.rules) {
for (const rule of desc.rules) {
Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type);
const args = [];
if (rule.args) {
const built = {};
for (const key in rule.args) {
built[key] = this.build(rule.args[key], { assign: key });
}
const keys = Object.keys(built);
const definition = def.rules[rule.name].args;
if (definition) {
Assert(keys.length <= definition.length, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to', definition.length, ', found', keys.length, ')');
for (const { name } of definition) {
args.push(built[name]);
}
}
else {
Assert(keys.length === 1, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to 1, found', keys.length, ')');
args.push(built[keys[0]]);
}
}
// Apply
schema = schema[rule.name](...args);
// Ruleset
const options = {};
for (const custom in def.modifiers) {
if (rule[custom] !== undefined) {
options[custom] = this.build(rule[custom]);
}
}
if (Object.keys(options).length) {
schema = schema.rule(options);
}
}
}
// Terms
const terms = {};
for (const key in desc) {
if (['allow', 'flags', 'invalid', 'whens', 'preferences', 'rules', 'type'].includes(key)) {
continue;
}
Assert(def.terms[key], 'Term', key, 'missing configuration');
const manifest = def.terms[key].manifest;
if (manifest === 'schema') {
terms[key] = desc[key].map((item) => this.parse(item));
continue;
}
if (manifest === 'values') {
terms[key] = desc[key].map((item) => this.build(item));
continue;
}
if (manifest === 'single') {
terms[key] = this.build(desc[key]);
continue;
}
if (typeof manifest === 'object') {
terms[key] = {};
for (const name in desc[key]) {
const value = desc[key][name];
terms[key][name] = this.parse(value);
}
continue;
}
terms[key] = this.build(desc[key]);
}
if (desc.whens) {
terms.whens = desc.whens.map((when) => this.build(when));
}
schema = def.manifest.build(schema, terms);
schema.$_temp.ruleset = false;
return schema;
}
build(desc, options = {}) {
if (desc === null) {
return null;
}
if (Array.isArray(desc)) {
return desc.map((item) => this.build(item));
}
if (desc instanceof Error) {
return desc;
}
if (options.assign === 'options') {
return Clone(desc);
}
if (options.assign === 'regex') {
return internals.regex(desc);
}
if (options.assign === 'ref') {
return Ref.build(desc);
}
if (typeof desc !== 'object') {
return desc;
}
if (Object.keys(desc).length === 1) {
if (desc.buffer) {
Assert(Buffer, 'Buffers are not supported');
return Buffer && Buffer.from(desc.buffer, 'binary'); // $lab:coverage:ignore$
}
if (desc.function) {
return { [Common.symbols.literal]: true, literal: desc.function };
}
if (desc.override) {
return Common.symbols.override;
}
if (desc.ref) {
return Ref.build(desc.ref);
}
if (desc.regex) {
return internals.regex(desc.regex);
}
if (desc.special) {
Assert(['deep'].includes(desc.special), 'Unknown special value', desc.special);
return Common.symbols.deepDefault;
}
if (desc.value) {
return Clone(desc.value);
}
}
if (desc.type) {
return this.parse(desc);
}
if (desc.template) {
return Template.build(desc);
}
const normalized = {};
for (const key in desc) {
normalized[key] = this.build(desc[key], { assign: key });
}
return normalized;
}
};
internals.regex = function (string) {
const end = string.lastIndexOf('/');
const exp = string.slice(1, end);
const flags = string.slice(end + 1);
return new RegExp(exp, flags);
};
internals.validate = function (joi, desc) {
Schemas = Schemas || __nccwpck_require__(85614);
joi.assert(desc, Schemas.description);
};
/***/ }),
/***/ 86103:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Template = __nccwpck_require__(51396);
const internals = {};
exports.compile = function (messages, target) {
// Single value string ('plain error message', 'template {error} message')
if (typeof messages === 'string') {
Assert(!target, 'Cannot set single message string');
return new Template(messages);
}
// Single value template
if (Template.isTemplate(messages)) {
Assert(!target, 'Cannot set single message template');
return messages;
}
// By error code { 'number.min': <string | template> }
Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options');
target = target ? Clone(target) : {};
for (let code in messages) {
const message = messages[code];
if (code === 'root' ||
Template.isTemplate(message)) {
target[code] = message;
continue;
}
if (typeof message === 'string') {
target[code] = new Template(message);
continue;
}
// By language { english: { 'number.min': <string | template> } }
Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code);
const language = code;
target[language] = target[language] || {};
for (code in message) {
const localized = message[code];
if (code === 'root' ||
Template.isTemplate(localized)) {
target[language][code] = localized;
continue;
}
Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language);
target[language][code] = new Template(localized);
}
}
return target;
};
exports.decompile = function (messages) {
// By error code { 'number.min': <string | template> }
const target = {};
for (let code in messages) {
const message = messages[code];
if (code === 'root') {
target.root = message;
continue;
}
if (Template.isTemplate(message)) {
target[code] = message.describe({ compact: true });
continue;
}
// By language { english: { 'number.min': <string | template> } }
const language = code;
target[language] = {};
for (code in message) {
const localized = message[code];
if (code === 'root') {
target[language].root = localized;
continue;
}
target[language][code] = localized.describe({ compact: true });
}
}
return target;
};
exports.merge = function (base, extended) {
if (!base) {
return exports.compile(extended);
}
if (!extended) {
return base;
}
// Single value string
if (typeof extended === 'string') {
return new Template(extended);
}
// Single value template
if (Template.isTemplate(extended)) {
return extended;
}
// By error code { 'number.min': <string | template> }
const target = Clone(base);
for (let code in extended) {
const message = extended[code];
if (code === 'root' ||
Template.isTemplate(message)) {
target[code] = message;
continue;
}
if (typeof message === 'string') {
target[code] = new Template(message);
continue;
}
// By language { english: { 'number.min': <string | template> } }
Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code);
const language = code;
target[language] = target[language] || {};
for (code in message) {
const localized = message[code];
if (code === 'root' ||
Template.isTemplate(localized)) {
target[language][code] = localized;
continue;
}
Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language);
target[language][code] = new Template(localized);
}
}
return target;
};
/***/ }),
/***/ 81290:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Common = __nccwpck_require__(72448);
const Ref = __nccwpck_require__(73838);
const internals = {};
exports.Ids = internals.Ids = class {
constructor() {
this._byId = new Map();
this._byKey = new Map();
this._schemaChain = false;
}
clone() {
const clone = new internals.Ids();
clone._byId = new Map(this._byId);
clone._byKey = new Map(this._byKey);
clone._schemaChain = this._schemaChain;
return clone;
}
concat(source) {
if (source._schemaChain) {
this._schemaChain = true;
}
for (const [id, value] of source._byId.entries()) {
Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id);
this._byId.set(id, value);
}
for (const [key, value] of source._byKey.entries()) {
Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key);
this._byKey.set(key, value);
}
}
fork(path, adjuster, root) {
const chain = this._collect(path);
chain.push({ schema: root });
const tail = chain.shift();
let adjusted = { id: tail.id, schema: adjuster(tail.schema) };
Assert(Common.isSchema(adjusted.schema), 'adjuster function failed to return a joi schema type');
for (const node of chain) {
adjusted = { id: node.id, schema: internals.fork(node.schema, adjusted.id, adjusted.schema) };
}
return adjusted.schema;
}
labels(path, behind = []) {
const current = path[0];
const node = this._get(current);
if (!node) {
return [...behind, ...path].join('.');
}
const forward = path.slice(1);
behind = [...behind, node.schema._flags.label || current];
if (!forward.length) {
return behind.join('.');
}
return node.schema._ids.labels(forward, behind);
}
reach(path, behind = []) {
const current = path[0];
const node = this._get(current);
Assert(node, 'Schema does not contain path', [...behind, ...path].join('.'));
const forward = path.slice(1);
if (!forward.length) {
return node.schema;
}
return node.schema._ids.reach(forward, [...behind, current]);
}
register(schema, { key } = {}) {
if (!schema ||
!Common.isSchema(schema)) {
return;
}
if (schema.$_property('schemaChain') ||
schema._ids._schemaChain) {
this._schemaChain = true;
}
const id = schema._flags.id;
if (id) {
const existing = this._byId.get(id);
Assert(!existing || existing.schema === schema, 'Cannot add different schemas with the same id:', id);
Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id);
this._byId.set(id, { schema, id });
}
if (key) {
Assert(!this._byKey.has(key), 'Schema already contains key:', key);
Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key);
this._byKey.set(key, { schema, id: key });
}
}
reset() {
this._byId = new Map();
this._byKey = new Map();
this._schemaChain = false;
}
_collect(path, behind = [], nodes = []) {
const current = path[0];
const node = this._get(current);
Assert(node, 'Schema does not contain path', [...behind, ...path].join('.'));
nodes = [node, ...nodes];
const forward = path.slice(1);
if (!forward.length) {
return nodes;
}
return node.schema._ids._collect(forward, [...behind, current], nodes);
}
_get(id) {
return this._byId.get(id) || this._byKey.get(id);
}
};
internals.fork = function (schema, id, replacement) {
const each = (item, { key }) => {
if (id === (item._flags.id || key)) {
return replacement;
}
};
const obj = exports.schema(schema, { each, ref: false });
return obj ? obj.$_mutateRebuild() : schema;
};
exports.schema = function (schema, options) {
let obj;
for (const name in schema._flags) {
if (name[0] === '_') {
continue;
}
const result = internals.scan(schema._flags[name], { source: 'flags', name }, options);
if (result !== undefined) {
obj = obj || schema.clone();
obj._flags[name] = result;
}
}
for (let i = 0; i < schema._rules.length; ++i) {
const rule = schema._rules[i];
const result = internals.scan(rule.args, { source: 'rules', name: rule.name }, options);
if (result !== undefined) {
obj = obj || schema.clone();
const clone = Object.assign({}, rule);
clone.args = result;
obj._rules[i] = clone;
const existingUnique = obj._singleRules.get(rule.name);
if (existingUnique === rule) {
obj._singleRules.set(rule.name, clone);
}
}
}
for (const name in schema.$_terms) {
if (name[0] === '_') {
continue;
}
const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options);
if (result !== undefined) {
obj = obj || schema.clone();
obj.$_terms[name] = result;
}
}
return obj;
};
internals.scan = function (item, source, options, _path, _key) {
const path = _path || [];
if (item === null ||
typeof item !== 'object') {
return;
}
let clone;
if (Array.isArray(item)) {
for (let i = 0; i < item.length; ++i) {
const key = source.source === 'terms' && source.name === 'keys' && item[i].key;
const result = internals.scan(item[i], source, options, [i, ...path], key);
if (result !== undefined) {
clone = clone || item.slice();
clone[i] = result;
}
}
return clone;
}
if (options.schema !== false && Common.isSchema(item) ||
options.ref !== false && Ref.isRef(item)) {
const result = options.each(item, { ...source, path, key: _key });
if (result === item) {
return;
}
return result;
}
for (const key in item) {
if (key[0] === '_') {
continue;
}
const result = internals.scan(item[key], source, options, [key, ...path], _key);
if (result !== undefined) {
clone = clone || Object.assign({}, item);
clone[key] = result;
}
}
return clone;
};
/***/ }),
/***/ 73838:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Reach = __nccwpck_require__(18891);
const Common = __nccwpck_require__(72448);
let Template;
const internals = {
symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions)
defaults: {
adjust: null,
in: false,
iterables: null,
map: null,
separator: '.',
type: 'value'
}
};
exports.create = function (key, options = {}) {
Assert(typeof key === 'string', 'Invalid reference key:', key);
Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'render', 'separator']);
Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object');
const ref = Object.assign({}, internals.defaults, options);
delete ref.prefix;
const separator = ref.separator;
const context = internals.context(key, separator, options.prefix);
ref.type = context.type;
key = context.key;
if (ref.type === 'value') {
if (context.root) {
Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix');
ref.ancestor = 'root';
if (!key) {
key = null;
}
}
if (separator &&
separator === key) {
key = null;
ref.ancestor = 0;
}
else {
if (ref.ancestor !== undefined) {
Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option');
}
else {
const [ancestor, slice] = internals.ancestor(key, separator);
if (slice) {
key = key.slice(slice);
if (key === '') {
key = null;
}
}
ref.ancestor = ancestor;
}
}
}
ref.path = separator ? (key === null ? [] : key.split(separator)) : [key];
return new internals.Ref(ref);
};
exports["in"] = function (key, options = {}) {
return exports.create(key, { ...options, in: true });
};
exports.isRef = function (ref) {
return ref ? !!ref[Common.symbols.ref] : false;
};
internals.Ref = class {
constructor(options) {
Assert(typeof options === 'object', 'Invalid reference construction');
Common.assertOptions(options, [
'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'render', 'separator', 'type', // Copied
'depth', 'key', 'root', 'display' // Overridden
]);
Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator');
Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function');
Assert(!options.map || Array.isArray(options.map), 'options.map must be an array');
Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options');
Object.assign(this, internals.defaults, options);
Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors');
if (Array.isArray(this.map)) {
this.map = new Map(this.map);
}
this.depth = this.path.length;
this.key = this.path.length ? this.path.join(this.separator) : null;
this.root = this.path[0];
this.updateDisplay();
}
resolve(value, state, prefs, local, options = {}) {
Assert(!this.in || options.in, 'Invalid in() reference usage');
if (this.type === 'global') {
return this._resolve(prefs.context, state, options);
}
if (this.type === 'local') {
return this._resolve(local, state, options);
}
if (!this.ancestor) {
return this._resolve(value, state, options);
}
if (this.ancestor === 'root') {
return this._resolve(state.ancestors[state.ancestors.length - 1], state, options);
}
Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display);
return this._resolve(state.ancestors[this.ancestor - 1], state, options);
}
_resolve(target, state, options) {
let resolved;
if (this.type === 'value' &&
state.mainstay.shadow &&
options.shadow !== false) {
resolved = state.mainstay.shadow.get(this.absolute(state));
}
if (resolved === undefined) {
resolved = Reach(target, this.path, { iterables: this.iterables, functions: true });
}
if (this.adjust) {
resolved = this.adjust(resolved);
}
if (this.map) {
const mapped = this.map.get(resolved);
if (mapped !== undefined) {
resolved = mapped;
}
}
if (state.mainstay) {
state.mainstay.tracer.resolve(state, this, resolved);
}
return resolved;
}
toString() {
return this.display;
}
absolute(state) {
return [...state.path.slice(0, -this.ancestor), ...this.path];
}
clone() {
return new internals.Ref(this);
}
describe() {
const ref = { path: this.path };
if (this.type !== 'value') {
ref.type = this.type;
}
if (this.separator !== '.') {
ref.separator = this.separator;
}
if (this.type === 'value' &&
this.ancestor !== 1) {
ref.ancestor = this.ancestor;
}
if (this.map) {
ref.map = [...this.map];
}
for (const key of ['adjust', 'iterables', 'render']) {
if (this[key] !== null &&
this[key] !== undefined) {
ref[key] = this[key];
}
}
if (this.in !== false) {
ref.in = true;
}
return { ref };
}
updateDisplay() {
const key = this.key !== null ? this.key : '';
if (this.type !== 'value') {
this.display = `ref:${this.type}:${key}`;
return;
}
if (!this.separator) {
this.display = `ref:${key}`;
return;
}
if (!this.ancestor) {
this.display = `ref:${this.separator}${key}`;
return;
}
if (this.ancestor === 'root') {
this.display = `ref:root:${key}`;
return;
}
if (this.ancestor === 1) {
this.display = `ref:${key || '..'}`;
return;
}
const lead = new Array(this.ancestor + 1).fill(this.separator).join('');
this.display = `ref:${lead}${key || ''}`;
}
};
internals.Ref.prototype[Common.symbols.ref] = true;
exports.build = function (desc) {
desc = Object.assign({}, internals.defaults, desc);
if (desc.type === 'value' &&
desc.ancestor === undefined) {
desc.ancestor = 1;
}
return new internals.Ref(desc);
};
internals.context = function (key, separator, prefix = {}) {
key = key.trim();
if (prefix) {
const globalp = prefix.global === undefined ? '$' : prefix.global;
if (globalp !== separator &&
key.startsWith(globalp)) {
return { key: key.slice(globalp.length), type: 'global' };
}
const local = prefix.local === undefined ? '#' : prefix.local;
if (local !== separator &&
key.startsWith(local)) {
return { key: key.slice(local.length), type: 'local' };
}
const root = prefix.root === undefined ? '/' : prefix.root;
if (root !== separator &&
key.startsWith(root)) {
return { key: key.slice(root.length), type: 'value', root: true };
}
}
return { key, type: 'value' };
};
internals.ancestor = function (key, separator) {
if (!separator) {
return [1, 0]; // 'a_b' -> 1 (parent)
}
if (key[0] !== separator) { // 'a.b' -> 1 (parent)
return [1, 0];
}
if (key[1] !== separator) { // '.a.b' -> 0 (self)
return [0, 1];
}
let i = 2;
while (key[i] === separator) {
++i;
}
return [i - 1, i]; // '...a.b.' -> 2 (grandparent)
};
exports.toSibling = 0;
exports.toParent = 1;
exports.Manager = class {
constructor() {
this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ...
}
register(source, target) {
if (!source) {
return;
}
target = target === undefined ? exports.toParent : target;
// Array
if (Array.isArray(source)) {
for (const ref of source) {
this.register(ref, target);
}
return;
}
// Schema
if (Common.isSchema(source)) {
for (const item of source._refs.refs) {
if (item.ancestor - target >= 0) {
this.refs.push({ ancestor: item.ancestor - target, root: item.root });
}
}
return;
}
// Reference
if (exports.isRef(source) &&
source.type === 'value' &&
source.ancestor - target >= 0) {
this.refs.push({ ancestor: source.ancestor - target, root: source.root });
}
// Template
Template = Template || __nccwpck_require__(51396);
if (Template.isTemplate(source)) {
this.register(source.refs(), target);
}
}
get length() {
return this.refs.length;
}
clone() {
const copy = new exports.Manager();
copy.refs = Clone(this.refs);
return copy;
}
reset() {
this.refs = [];
}
roots() {
return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root);
}
};
/***/ }),
/***/ 85614:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Joi = __nccwpck_require__(20918);
const internals = {};
// Preferences
internals.wrap = Joi.string()
.min(1)
.max(2)
.allow(false);
exports.preferences = Joi.object({
allowUnknown: Joi.boolean(),
abortEarly: Joi.boolean(),
artifacts: Joi.boolean(),
cache: Joi.boolean(),
context: Joi.object(),
convert: Joi.boolean(),
dateFormat: Joi.valid('date', 'iso', 'string', 'time', 'utc'),
debug: Joi.boolean(),
errors: {
escapeHtml: Joi.boolean(),
label: Joi.valid('path', 'key', false),
language: [
Joi.string(),
Joi.object().ref()
],
render: Joi.boolean(),
stack: Joi.boolean(),
wrap: {
label: internals.wrap,
array: internals.wrap,
string: internals.wrap
}
},
externals: Joi.boolean(),
messages: Joi.object(),
noDefaults: Joi.boolean(),
nonEnumerables: Joi.boolean(),
presence: Joi.valid('required', 'optional', 'forbidden'),
skipFunctions: Joi.boolean(),
stripUnknown: Joi.object({
arrays: Joi.boolean(),
objects: Joi.boolean()
})
.or('arrays', 'objects')
.allow(true, false),
warnings: Joi.boolean()
})
.strict();
// Extensions
internals.nameRx = /^[a-zA-Z0-9]\w*$/;
internals.rule = Joi.object({
alias: Joi.array().items(Joi.string().pattern(internals.nameRx)).single(),
args: Joi.array().items(
Joi.string(),
Joi.object({
name: Joi.string().pattern(internals.nameRx).required(),
ref: Joi.boolean(),
assert: Joi.alternatives([
Joi.function(),
Joi.object().schema()
])
.conditional('ref', { is: true, then: Joi.required() }),
normalize: Joi.function(),
message: Joi.string().when('assert', { is: Joi.function(), then: Joi.required() })
})
),
convert: Joi.boolean(),
manifest: Joi.boolean(),
method: Joi.function().allow(false),
multi: Joi.boolean(),
validate: Joi.function()
});
exports.extension = Joi.object({
type: Joi.alternatives([
Joi.string(),
Joi.object().regex()
])
.required(),
args: Joi.function(),
cast: Joi.object().pattern(internals.nameRx, Joi.object({
from: Joi.function().maxArity(1).required(),
to: Joi.function().minArity(1).maxArity(2).required()
})),
base: Joi.object().schema()
.when('type', { is: Joi.object().regex(), then: Joi.forbidden() }),
coerce: [
Joi.function().maxArity(3),
Joi.object({ method: Joi.function().maxArity(3).required(), from: Joi.array().items(Joi.string()).single() })
],
flags: Joi.object().pattern(internals.nameRx, Joi.object({
setter: Joi.string(),
default: Joi.any()
})),
manifest: {
build: Joi.function().arity(2)
},
messages: [Joi.object(), Joi.string()],
modifiers: Joi.object().pattern(internals.nameRx, Joi.function().minArity(1).maxArity(2)),
overrides: Joi.object().pattern(internals.nameRx, Joi.function()),
prepare: Joi.function().maxArity(3),
rebuild: Joi.function().arity(1),
rules: Joi.object().pattern(internals.nameRx, internals.rule),
terms: Joi.object().pattern(internals.nameRx, Joi.object({
init: Joi.array().allow(null).required(),
manifest: Joi.object().pattern(/.+/, [
Joi.valid('schema', 'single'),
Joi.object({
mapped: Joi.object({
from: Joi.string().required(),
to: Joi.string().required()
})
.required()
})
])
})),
validate: Joi.function().maxArity(3)
})
.strict();
exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict();
// Manifest
internals.desc = {
buffer: Joi.object({
buffer: Joi.string()
}),
func: Joi.object({
function: Joi.function().required(),
options: {
literal: true
}
}),
override: Joi.object({
override: true
}),
ref: Joi.object({
ref: Joi.object({
type: Joi.valid('value', 'global', 'local'),
path: Joi.array().required(),
separator: Joi.string().length(1).allow(false),
ancestor: Joi.number().min(0).integer().allow('root'),
map: Joi.array().items(Joi.array().length(2)).min(1),
adjust: Joi.function(),
iterables: Joi.boolean(),
in: Joi.boolean(),
render: Joi.boolean()
})
.required()
}),
regex: Joi.object({
regex: Joi.string().min(3)
}),
special: Joi.object({
special: Joi.valid('deep').required()
}),
template: Joi.object({
template: Joi.string().required(),
options: Joi.object()
}),
value: Joi.object({
value: Joi.alternatives([Joi.object(), Joi.array()]).required()
})
};
internals.desc.entity = Joi.alternatives([
Joi.array().items(Joi.link('...')),
Joi.boolean(),
Joi.function(),
Joi.number(),
Joi.string(),
internals.desc.buffer,
internals.desc.func,
internals.desc.ref,
internals.desc.regex,
internals.desc.special,
internals.desc.template,
internals.desc.value,
Joi.link('/')
]);
internals.desc.values = Joi.array()
.items(
null,
Joi.boolean(),
Joi.function(),
Joi.number().allow(Infinity, -Infinity),
Joi.string().allow(''),
Joi.symbol(),
internals.desc.buffer,
internals.desc.func,
internals.desc.override,
internals.desc.ref,
internals.desc.regex,
internals.desc.template,
internals.desc.value
);
internals.desc.messages = Joi.object()
.pattern(/.+/, [
Joi.string(),
internals.desc.template,
Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template])
]);
exports.description = Joi.object({
type: Joi.string().required(),
flags: Joi.object({
cast: Joi.string(),
default: Joi.any(),
description: Joi.string(),
empty: Joi.link('/'),
failover: internals.desc.entity,
id: Joi.string(),
label: Joi.string(),
only: true,
presence: ['optional', 'required', 'forbidden'],
result: ['raw', 'strip'],
strip: Joi.boolean(),
unit: Joi.string()
})
.unknown(),
preferences: {
allowUnknown: Joi.boolean(),
abortEarly: Joi.boolean(),
artifacts: Joi.boolean(),
cache: Joi.boolean(),
convert: Joi.boolean(),
dateFormat: ['date', 'iso', 'string', 'time', 'utc'],
errors: {
escapeHtml: Joi.boolean(),
label: ['path', 'key'],
language: [
Joi.string(),
internals.desc.ref
],
wrap: {
label: internals.wrap,
array: internals.wrap
}
},
externals: Joi.boolean(),
messages: internals.desc.messages,
noDefaults: Joi.boolean(),
nonEnumerables: Joi.boolean(),
presence: ['required', 'optional', 'forbidden'],
skipFunctions: Joi.boolean(),
stripUnknown: Joi.object({
arrays: Joi.boolean(),
objects: Joi.boolean()
})
.or('arrays', 'objects')
.allow(true, false),
warnings: Joi.boolean()
},
allow: internals.desc.values,
invalid: internals.desc.values,
rules: Joi.array().min(1).items({
name: Joi.string().required(),
args: Joi.object().min(1),
keep: Joi.boolean(),
message: [
Joi.string(),
internals.desc.messages
],
warn: Joi.boolean()
}),
// Terms
keys: Joi.object().pattern(/.*/, Joi.link('/')),
link: internals.desc.ref
})
.pattern(/^[a-z]\w*$/, Joi.any());
/***/ }),
/***/ 73634:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Clone = __nccwpck_require__(85578);
const Reach = __nccwpck_require__(18891);
const Common = __nccwpck_require__(72448);
const internals = {
value: Symbol('value')
};
module.exports = internals.State = class {
constructor(path, ancestors, state) {
this.path = path;
this.ancestors = ancestors; // [parent, ..., root]
this.mainstay = state.mainstay;
this.schemas = state.schemas; // [current, ..., root]
this.debug = null;
}
localize(path, ancestors = null, schema = null) {
const state = new internals.State(path, ancestors, this);
if (schema &&
state.schemas) {
state.schemas = [internals.schemas(schema), ...state.schemas];
}
return state;
}
nest(schema, debug) {
const state = new internals.State(this.path, this.ancestors, this);
state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas];
state.debug = debug;
return state;
}
shadow(value, reason) {
this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow();
this.mainstay.shadow.set(this.path, value, reason);
}
snapshot() {
if (this.mainstay.shadow) {
this._snapshot = Clone(this.mainstay.shadow.node(this.path));
}
this.mainstay.snapshot();
}
restore() {
if (this.mainstay.shadow) {
this.mainstay.shadow.override(this.path, this._snapshot);
this._snapshot = undefined;
}
this.mainstay.restore();
}
commit() {
if (this.mainstay.shadow) {
this.mainstay.shadow.override(this.path, this._snapshot);
this._snapshot = undefined;
}
this.mainstay.commit();
}
};
internals.schemas = function (schema) {
if (Common.isSchema(schema)) {
return { schema };
}
return schema;
};
internals.Shadow = class {
constructor() {
this._values = null;
}
set(path, value, reason) {
if (!path.length) { // No need to store root value
return;
}
if (reason === 'strip' &&
typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift)
return;
}
this._values = this._values || new Map();
let node = this._values;
for (let i = 0; i < path.length; ++i) {
const segment = path[i];
let next = node.get(segment);
if (!next) {
next = new Map();
node.set(segment, next);
}
node = next;
}
node[internals.value] = value;
}
get(path) {
const node = this.node(path);
if (node) {
return node[internals.value];
}
}
node(path) {
if (!this._values) {
return;
}
return Reach(this._values, path, { iterables: true });
}
override(path, node) {
if (!this._values) {
return;
}
const parents = path.slice(0, -1);
const own = path[path.length - 1];
const parent = Reach(this._values, parents, { iterables: true });
if (node) {
parent.set(own, node);
return;
}
if (parent) {
parent.delete(own);
}
}
};
/***/ }),
/***/ 51396:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const EscapeHtml = __nccwpck_require__(24752);
const Formula = __nccwpck_require__(34379);
const Common = __nccwpck_require__(72448);
const Errors = __nccwpck_require__(69490);
const Ref = __nccwpck_require__(73838);
const internals = {
symbol: Symbol('template'),
opens: new Array(1000).join('\u0000'),
closes: new Array(1000).join('\u0001'),
dateFormat: {
date: Date.prototype.toDateString,
iso: Date.prototype.toISOString,
string: Date.prototype.toString,
time: Date.prototype.toTimeString,
utc: Date.prototype.toUTCString
}
};
module.exports = exports = internals.Template = class {
constructor(source, options) {
Assert(typeof source === 'string', 'Template source must be a string');
Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters');
this.source = source;
this.rendered = source;
this._template = null;
if (options) {
const { functions, ...opts } = options;
this._settings = Object.keys(opts).length ? Clone(opts) : undefined;
this._functions = functions;
if (this._functions) {
Assert(Object.keys(this._functions).every((key) => typeof key === 'string'), 'Functions keys must be strings');
Assert(Object.values(this._functions).every((key) => typeof key === 'function'), 'Functions values must be functions');
}
}
else {
this._settings = undefined;
this._functions = undefined;
}
this._parse();
}
_parse() {
// 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}'
if (!this.source.includes('{')) {
return;
}
// Encode escaped \\{{{{{
const encoded = internals.encode(this.source);
// Split on first { in each set
const parts = internals.split(encoded);
// Process parts
let refs = false;
const processed = [];
const head = parts.shift();
if (head) {
processed.push(head);
}
for (const part of parts) {
const raw = part[0] !== '{';
const ender = raw ? '}' : '}}';
const end = part.indexOf(ender);
if (end === -1 || // Ignore non-matching closing
part[1] === '{') { // Ignore more than two {
processed.push(`{${internals.decode(part)}`);
continue;
}
let variable = part.slice(raw ? 0 : 1, end);
const wrapped = variable[0] === ':';
if (wrapped) {
variable = variable.slice(1);
}
const dynamic = this._ref(internals.decode(variable), { raw, wrapped });
processed.push(dynamic);
if (typeof dynamic !== 'string') {
refs = true;
}
const rest = part.slice(end + ender.length);
if (rest) {
processed.push(internals.decode(rest));
}
}
if (!refs) {
this.rendered = processed.join('');
return;
}
this._template = processed;
}
static date(date, prefs) {
return internals.dateFormat[prefs.dateFormat].call(date);
}
describe(options = {}) {
if (!this._settings &&
options.compact) {
return this.source;
}
const desc = { template: this.source };
if (this._settings) {
desc.options = this._settings;
}
if (this._functions) {
desc.functions = this._functions;
}
return desc;
}
static build(desc) {
return new internals.Template(desc.template, desc.options || desc.functions ? { ...desc.options, functions: desc.functions } : undefined);
}
isDynamic() {
return !!this._template;
}
static isTemplate(template) {
return template ? !!template[Common.symbols.template] : false;
}
refs() {
if (!this._template) {
return;
}
const refs = [];
for (const part of this._template) {
if (typeof part !== 'string') {
refs.push(...part.refs);
}
}
return refs;
}
resolve(value, state, prefs, local) {
if (this._template &&
this._template.length === 1) {
return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */);
}
return this.render(value, state, prefs, local);
}
_part(part, ...args) {
if (part.ref) {
return part.ref.resolve(...args);
}
return part.formula.evaluate(args);
}
render(value, state, prefs, local, options = {}) {
if (!this.isDynamic()) {
return this.rendered;
}
const parts = [];
for (const part of this._template) {
if (typeof part === 'string') {
parts.push(part);
}
else {
const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */);
const string = internals.stringify(rendered, value, state, prefs, local, options);
if (string !== undefined) {
const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string);
parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label));
}
}
}
return parts.join('');
}
_ref(content, { raw, wrapped }) {
const refs = [];
const reference = (variable) => {
const ref = Ref.create(variable, this._settings);
refs.push(ref);
return (context) => {
const resolved = ref.resolve(...context);
return resolved !== undefined ? resolved : null;
};
};
try {
const functions = this._functions ? { ...internals.functions, ...this._functions } : internals.functions;
var formula = new Formula.Parser(content, { reference, functions, constants: internals.constants });
}
catch (err) {
err.message = `Invalid template variable "${content}" fails due to: ${err.message}`;
throw err;
}
if (formula.single) {
if (formula.single.type === 'reference') {
const ref = refs[0];
return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' };
}
return internals.stringify(formula.single.value);
}
return { formula, raw, refs };
}
toString() {
return this.source;
}
};
internals.Template.prototype[Common.symbols.template] = true;
internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects
internals.encode = function (string) {
return string
.replace(/\\(\{+)/g, ($0, $1) => {
return internals.opens.slice(0, $1.length);
})
.replace(/\\(\}+)/g, ($0, $1) => {
return internals.closes.slice(0, $1.length);
});
};
internals.decode = function (string) {
return string
.replace(/\u0000/g, '{')
.replace(/\u0001/g, '}');
};
internals.split = function (string) {
const parts = [];
let current = '';
for (let i = 0; i < string.length; ++i) {
const char = string[i];
if (char === '{') {
let next = '';
while (i + 1 < string.length &&
string[i + 1] === '{') {
next += '{';
++i;
}
parts.push(current);
current = next;
}
else {
current += char;
}
}
parts.push(current);
return parts;
};
internals.wrap = function (value, ends) {
if (!ends) {
return value;
}
if (ends.length === 1) {
return `${ends}${value}${ends}`;
}
return `${ends[0]}${value}${ends[1]}`;
};
internals.stringify = function (value, original, state, prefs, local, options = {}) {
const type = typeof value;
const wrap = prefs && prefs.errors && prefs.errors.wrap || {};
let skipWrap = false;
if (Ref.isRef(value) &&
value.render) {
skipWrap = value.in;
value = value.resolve(original, state, prefs, local, { in: value.in, ...options });
}
if (value === null) {
return 'null';
}
if (type === 'string') {
return internals.wrap(value, options.arrayItems && wrap.string);
}
if (type === 'number' ||
type === 'function' ||
type === 'symbol') {
return value.toString();
}
if (type !== 'object') {
return JSON.stringify(value);
}
if (value instanceof Date) {
return internals.Template.date(value, prefs);
}
if (value instanceof Map) {
const pairs = [];
for (const [key, sym] of value.entries()) {
pairs.push(`${key.toString()} -> ${sym.toString()}`);
}
value = pairs;
}
if (!Array.isArray(value)) {
return value.toString();
}
const values = [];
for (const item of value) {
values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options }));
}
return internals.wrap(values.join(', '), !skipWrap && wrap.array);
};
internals.constants = {
true: true,
false: false,
null: null,
second: 1000,
minute: 60 * 1000,
hour: 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000
};
internals.functions = {
if(condition, then, otherwise) {
return condition ? then : otherwise;
},
length(item) {
if (typeof item === 'string') {
return item.length;
}
if (!item || typeof item !== 'object') {
return null;
}
if (Array.isArray(item)) {
return item.length;
}
return Object.keys(item).length;
},
msg(code) {
const [value, state, prefs, local, options] = this;
const messages = options.messages;
if (!messages) {
return '';
}
const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs);
if (!template) {
return '';
}
return template.render(value, state, prefs, local, options);
},
number(value) {
if (typeof value === 'number') {
return value;
}
if (typeof value === 'string') {
return parseFloat(value);
}
if (typeof value === 'boolean') {
return value ? 1 : 0;
}
if (value instanceof Date) {
return value.getTime();
}
return null;
}
};
/***/ }),
/***/ 43171:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const DeepEqual = __nccwpck_require__(55801);
const Pinpoint = __nccwpck_require__(75604);
const Errors = __nccwpck_require__(69490);
const internals = {
codes: {
error: 1,
pass: 2,
full: 3
},
labels: {
0: 'never used',
1: 'always error',
2: 'always pass'
}
};
exports.setup = function (root) {
const trace = function () {
root._tracer = root._tracer || new internals.Tracer();
return root._tracer;
};
root.trace = trace;
root[Symbol.for('@hapi/lab/coverage/initialize')] = trace;
root.untrace = () => {
root._tracer = null;
};
};
exports.location = function (schema) {
return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller
};
internals.Tracer = class {
constructor() {
this.name = 'Joi';
this._schemas = new Map();
}
_register(schema) {
const existing = this._schemas.get(schema);
if (existing) {
return existing.store;
}
const store = new internals.Store(schema);
const { filename, line } = schema._flags._tracerLocation || Pinpoint.location(5); // internals.tracer(), internals.entry(), exports.entry(), validate(), caller
this._schemas.set(schema, { filename, line, store });
return store;
}
_combine(merged, sources) {
for (const { store } of this._schemas.values()) {
store._combine(merged, sources);
}
}
report(file) {
const coverage = [];
// Process each registered schema
for (const { filename, line, store } of this._schemas.values()) {
if (file &&
file !== filename) {
continue;
}
// Process sub schemas of the registered root
const missing = [];
const skipped = [];
for (const [schema, log] of store._sources.entries()) {
// Check if sub schema parent skipped
if (internals.sub(log.paths, skipped)) {
continue;
}
// Check if sub schema reached
if (!log.entry) {
missing.push({
status: 'never reached',
paths: [...log.paths]
});
skipped.push(...log.paths);
continue;
}
// Check values
for (const type of ['valid', 'invalid']) {
const set = schema[`_${type}s`];
if (!set) {
continue;
}
const values = new Set(set._values);
const refs = new Set(set._refs);
for (const { value, ref } of log[type]) {
values.delete(value);
refs.delete(ref);
}
if (values.size ||
refs.size) {
missing.push({
status: [...values, ...[...refs].map((ref) => ref.display)],
rule: `${type}s`
});
}
}
// Check rules status
const rules = schema._rules.map((rule) => rule.name);
for (const type of ['default', 'failover']) {
if (schema._flags[type] !== undefined) {
rules.push(type);
}
}
for (const name of rules) {
const status = internals.labels[log.rule[name] || 0];
if (status) {
const report = { rule: name, status };
if (log.paths.size) {
report.paths = [...log.paths];
}
missing.push(report);
}
}
}
if (missing.length) {
coverage.push({
filename,
line,
missing,
severity: 'error',
message: `Schema missing tests for ${missing.map(internals.message).join(', ')}`
});
}
}
return coverage.length ? coverage : null;
}
};
internals.Store = class {
constructor(schema) {
this.active = true;
this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid }
this._combos = new Map(); // merged -> [sources]
this._scan(schema);
}
debug(state, source, name, result) {
state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path });
}
entry(schema, state) {
internals.debug(state, { type: 'entry' });
this._record(schema, (log) => {
log.entry = true;
});
}
filter(schema, state, source, value) {
internals.debug(state, { type: source, ...value });
this._record(schema, (log) => {
log[source].add(value);
});
}
log(schema, state, source, name, result) {
internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result });
this._record(schema, (log) => {
log[source][name] = log[source][name] || 0;
log[source][name] |= internals.codes[result];
});
}
resolve(state, ref, to) {
if (!state.mainstay.debug) {
return;
}
const log = { type: 'resolve', ref: ref.display, to, path: state.path };
state.mainstay.debug.push(log);
}
value(state, by, from, to, name) {
if (!state.mainstay.debug ||
DeepEqual(from, to)) {
return;
}
const log = { type: 'value', by, from, to, path: state.path };
if (name) {
log.name = name;
}
state.mainstay.debug.push(log);
}
_record(schema, each) {
const log = this._sources.get(schema);
if (log) {
each(log);
return;
}
const sources = this._combos.get(schema);
for (const source of sources) {
this._record(source, each);
}
}
_scan(schema, _path) {
const path = _path || [];
let log = this._sources.get(schema);
if (!log) {
log = {
paths: new Set(),
entry: false,
rule: {},
valid: new Set(),
invalid: new Set()
};
this._sources.set(schema, log);
}
if (path.length) {
log.paths.add(path);
}
const each = (sub, source) => {
const subId = internals.id(sub, source);
this._scan(sub, path.concat(subId));
};
schema.$_modify({ each, ref: false });
}
_combine(merged, sources) {
this._combos.set(merged, sources);
}
};
internals.message = function (item) {
const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : '';
return `${path}${item.rule || ''} (${item.status})`;
};
internals.id = function (schema, { source, name, path, key }) {
if (schema._flags.id) {
return schema._flags.id;
}
if (key) {
return key;
}
name = `@${name}`;
if (source === 'terms') {
return [name, path[Math.min(path.length - 1, 1)]];
}
return name;
};
internals.sub = function (paths, skipped) {
for (const path of paths) {
for (const skip of skipped) {
if (DeepEqual(path.slice(0, skip.length), skip)) {
return true;
}
}
}
return false;
};
internals.debug = function (state, event) {
if (state.mainstay.debug) {
event.path = state.debug ? [...state.path, state.debug] : state.path;
state.mainstay.debug.push(event);
}
};
/***/ }),
/***/ 26867:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Merge = __nccwpck_require__(60445);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const Errors = __nccwpck_require__(69490);
const Ref = __nccwpck_require__(73838);
const internals = {};
module.exports = Any.extend({
type: 'alternatives',
flags: {
match: { default: 'any' } // 'any', 'one', 'all'
},
terms: {
matches: { init: [], register: Ref.toSibling }
},
args(schema, ...schemas) {
if (schemas.length === 1) {
if (Array.isArray(schemas[0])) {
return schema.try(...schemas[0]);
}
}
return schema.try(...schemas);
},
validate(value, helpers) {
const { schema, error, state, prefs } = helpers;
// Match all or one
if (schema._flags.match) {
const matched = [];
const failed = [];
for (let i = 0; i < schema.$_terms.matches.length; ++i) {
const item = schema.$_terms.matches[i];
const localState = state.nest(item.schema, `match.${i}`);
localState.snapshot();
const result = item.schema.$_validate(value, localState, prefs);
if (!result.errors) {
matched.push(result.value);
localState.commit();
}
else {
failed.push(result.errors);
localState.restore();
}
}
if (matched.length === 0) {
const context = {
details: failed.map((f) => Errors.details(f, { override: false }))
};
return { errors: error('alternatives.any', context) };
}
// Match one
if (schema._flags.match === 'one') {
return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') };
}
// Match all
if (matched.length !== schema.$_terms.matches.length) {
const context = {
details: failed.map((f) => Errors.details(f, { override: false }))
};
return { errors: error('alternatives.all', context) };
}
const isAnyObj = (alternative) => {
return alternative.$_terms.matches.some((v) => {
return v.schema.type === 'object' ||
(v.schema.type === 'alternatives' && isAnyObj(v.schema));
});
};
return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] };
}
// Match any
const errors = [];
for (let i = 0; i < schema.$_terms.matches.length; ++i) {
const item = schema.$_terms.matches[i];
// Try
if (item.schema) {
const localState = state.nest(item.schema, `match.${i}`);
localState.snapshot();
const result = item.schema.$_validate(value, localState, prefs);
if (!result.errors) {
localState.commit();
return result;
}
localState.restore();
errors.push({ schema: item.schema, reports: result.errors });
continue;
}
// Conditional
const input = item.ref ? item.ref.resolve(value, state, prefs) : value;
const tests = item.is ? [item] : item.switch;
for (let j = 0; j < tests.length; ++j) {
const test = tests[j];
const { is, then, otherwise } = test;
const id = `match.${i}${item.switch ? '.' + j : ''}`;
if (!is.$_match(input, state.nest(is, `${id}.is`), prefs)) {
if (otherwise) {
return otherwise.$_validate(value, state.nest(otherwise, `${id}.otherwise`), prefs);
}
}
else if (then) {
return then.$_validate(value, state.nest(then, `${id}.then`), prefs);
}
}
}
return internals.errors(errors, helpers);
},
rules: {
conditional: {
method(condition, options) {
Assert(!this._flags._endedSwitch, 'Unreachable condition');
Assert(!this._flags.match, 'Cannot combine match mode', this._flags.match, 'with conditional rule');
Assert(options.break === undefined, 'Cannot use break option with alternatives conditional');
const obj = this.clone();
const match = Compile.when(obj, condition, options);
const conditions = match.is ? [match] : match.switch;
for (const item of conditions) {
if (item.then &&
item.otherwise) {
obj.$_setFlag('_endedSwitch', true, { clone: false });
break;
}
}
obj.$_terms.matches.push(match);
return obj.$_mutateRebuild();
}
},
match: {
method(mode) {
Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode);
if (mode !== 'any') {
for (const match of this.$_terms.matches) {
Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules');
}
}
return this.$_setFlag('match', mode);
}
},
try: {
method(...schemas) {
Assert(schemas.length, 'Missing alternative schemas');
Common.verifyFlat(schemas, 'try');
Assert(!this._flags._endedSwitch, 'Unreachable condition');
const obj = this.clone();
for (const schema of schemas) {
obj.$_terms.matches.push({ schema: obj.$_compile(schema) });
}
return obj.$_mutateRebuild();
}
}
},
overrides: {
label(name) {
const obj = this.$_parent('label', name);
const each = (item, source) => {
return source.path[0] !== 'is' && typeof item._flags.label !== 'string' ? item.label(name) : undefined;
};
return obj.$_modify({ each, ref: false });
}
},
rebuild(schema) {
// Flag when an alternative type is an array
const each = (item) => {
if (Common.isSchema(item) &&
item.type === 'array') {
schema.$_setFlag('_arrayItems', true, { clone: false });
}
};
schema.$_modify({ each });
},
manifest: {
build(obj, desc) {
if (desc.matches) {
for (const match of desc.matches) {
const { schema, ref, is, not, then, otherwise } = match;
if (schema) {
obj = obj.try(schema);
}
else if (ref) {
obj = obj.conditional(ref, { is, then, not, otherwise, switch: match.switch });
}
else {
obj = obj.conditional(is, { then, otherwise });
}
}
}
return obj;
}
},
messages: {
'alternatives.all': '{{#label}} does not match all of the required types',
'alternatives.any': '{{#label}} does not match any of the allowed types',
'alternatives.match': '{{#label}} does not match any of the allowed types',
'alternatives.one': '{{#label}} matches more than one allowed type',
'alternatives.types': '{{#label}} must be one of {{#types}}'
}
});
// Helpers
internals.errors = function (failures, { error, state }) {
// Nothing matched due to type criteria rules
if (!failures.length) {
return { errors: error('alternatives.any') };
}
// Single error
if (failures.length === 1) {
return { errors: failures[0].reports };
}
// Analyze reasons
const valids = new Set();
const complex = [];
for (const { reports, schema } of failures) {
// Multiple errors (!abortEarly)
if (reports.length > 1) {
return internals.unmatched(failures, error);
}
// Custom error
const report = reports[0];
if (report instanceof Errors.Report === false) {
return internals.unmatched(failures, error);
}
// Internal object or array error
if (report.state.path.length !== state.path.length) {
complex.push({ type: schema.type, report });
continue;
}
// Valids
if (report.code === 'any.only') {
for (const valid of report.local.valids) {
valids.add(valid);
}
continue;
}
// Base type
const [type, code] = report.code.split('.');
if (code !== 'base') {
complex.push({ type: schema.type, report });
continue;
}
valids.add(type);
}
// All errors are base types or valids
if (!complex.length) {
return { errors: error('alternatives.types', { types: [...valids] }) };
}
// Single complex error
if (complex.length === 1) {
return { errors: complex[0].report };
}
return internals.unmatched(failures, error);
};
internals.unmatched = function (failures, error) {
const errors = [];
for (const failure of failures) {
errors.push(...failure.reports);
}
return { errors: error('alternatives.match', Errors.details(errors, { override: false })) };
};
/***/ }),
/***/ 9512:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Base = __nccwpck_require__(95184);
const Common = __nccwpck_require__(72448);
const Messages = __nccwpck_require__(86103);
const internals = {};
module.exports = Base.extend({
type: 'any',
flags: {
only: { default: false }
},
terms: {
alterations: { init: null },
examples: { init: null },
externals: { init: null },
metas: { init: [] },
notes: { init: [] },
shared: { init: null },
tags: { init: [] },
whens: { init: null }
},
rules: {
custom: {
method(method, description) {
Assert(typeof method === 'function', 'Method must be a function');
Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string');
return this.$_addRule({ name: 'custom', args: { method, description } });
},
validate(value, helpers, { method }) {
try {
return method(value, helpers);
}
catch (err) {
return helpers.error('any.custom', { error: err });
}
},
args: ['method', 'description'],
multi: true
},
messages: {
method(messages) {
return this.prefs({ messages });
}
},
shared: {
method(schema) {
Assert(Common.isSchema(schema) && schema._flags.id, 'Schema must be a schema with an id');
const obj = this.clone();
obj.$_terms.shared = obj.$_terms.shared || [];
obj.$_terms.shared.push(schema);
obj.$_mutateRegister(schema);
return obj;
}
},
warning: {
method(code, local) {
Assert(code && typeof code === 'string', 'Invalid warning code');
return this.$_addRule({ name: 'warning', args: { code, local }, warn: true });
},
validate(value, helpers, { code, local }) {
return helpers.error(code, local);
},
args: ['code', 'local'],
multi: true
}
},
modifiers: {
keep(rule, enabled = true) {
rule.keep = enabled;
},
message(rule, message) {
rule.message = Messages.compile(message);
},
warn(rule, enabled = true) {
rule.warn = enabled;
}
},
manifest: {
build(obj, desc) {
for (const key in desc) {
const values = desc[key];
if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) {
for (const value of values) {
obj = obj[key.slice(0, -1)](value);
}
continue;
}
if (key === 'alterations') {
const alter = {};
for (const { target, adjuster } of values) {
alter[target] = adjuster;
}
obj = obj.alter(alter);
continue;
}
if (key === 'whens') {
for (const value of values) {
const { ref, is, not, then, otherwise, concat } = value;
if (concat) {
obj = obj.concat(concat);
}
else if (ref) {
obj = obj.when(ref, { is, not, then, otherwise, switch: value.switch, break: value.break });
}
else {
obj = obj.when(is, { then, otherwise, break: value.break });
}
}
continue;
}
if (key === 'shared') {
for (const value of values) {
obj = obj.shared(value);
}
}
}
return obj;
}
},
messages: {
'any.custom': '{{#label}} failed custom validation because {{#error.message}}',
'any.default': '{{#label}} threw an error when running default method',
'any.failover': '{{#label}} threw an error when running failover method',
'any.invalid': '{{#label}} contains an invalid value',
'any.only': '{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}',
'any.ref': '{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}',
'any.required': '{{#label}} is required',
'any.unknown': '{{#label}} is not allowed'
}
});
/***/ }),
/***/ 20270:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const DeepEqual = __nccwpck_require__(55801);
const Reach = __nccwpck_require__(18891);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const internals = {};
module.exports = Any.extend({
type: 'array',
flags: {
single: { default: false },
sparse: { default: false }
},
terms: {
items: { init: [], manifest: 'schema' },
ordered: { init: [], manifest: 'schema' },
_exclusions: { init: [] },
_inclusions: { init: [] },
_requireds: { init: [] }
},
coerce: {
from: 'object',
method(value, { schema, state, prefs }) {
if (!Array.isArray(value)) {
return;
}
const sort = schema.$_getRule('sort');
if (!sort) {
return;
}
return internals.sort(schema, value, sort.args.options, state, prefs);
}
},
validate(value, { schema, error }) {
if (!Array.isArray(value)) {
if (schema._flags.single) {
const single = [value];
single[Common.symbols.arraySingle] = true;
return { value: single };
}
return { errors: error('array.base') };
}
if (!schema.$_getRule('items') &&
!schema.$_terms.externals) {
return;
}
return { value: value.slice() }; // Clone the array so that we don't modify the original
},
rules: {
has: {
method(schema) {
schema = this.$_compile(schema, { appendPath: true });
const obj = this.$_addRule({ name: 'has', args: { schema } });
obj.$_mutateRegister(schema);
return obj;
},
validate(value, { state, prefs, error }, { schema: has }) {
const ancestors = [value, ...state.ancestors];
for (let i = 0; i < value.length; ++i) {
const localState = state.localize([...state.path, i], ancestors, has);
if (has.$_match(value[i], localState, prefs)) {
return value;
}
}
const patternLabel = has._flags.label;
if (patternLabel) {
return error('array.hasKnown', { patternLabel });
}
return error('array.hasUnknown', null);
},
multi: true
},
items: {
method(...schemas) {
Common.verifyFlat(schemas, 'items');
const obj = this.$_addRule('items');
for (let i = 0; i < schemas.length; ++i) {
const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true });
obj.$_terms.items.push(type);
}
return obj.$_mutateRebuild();
},
validate(value, { schema, error, state, prefs, errorsArray }) {
const requireds = schema.$_terms._requireds.slice();
const ordereds = schema.$_terms.ordered.slice();
const inclusions = [...schema.$_terms._inclusions, ...requireds];
const wasArray = !value[Common.symbols.arraySingle];
delete value[Common.symbols.arraySingle];
const errors = errorsArray();
let il = value.length;
for (let i = 0; i < il; ++i) {
const item = value[i];
let errored = false;
let isValid = false;
const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers
const path = [...state.path, key];
// Sparse
if (!schema._flags.sparse &&
item === undefined) {
errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path)));
if (prefs.abortEarly) {
return errors;
}
ordereds.shift();
continue;
}
// Exclusions
const ancestors = [value, ...state.ancestors];
for (const exclusion of schema.$_terms._exclusions) {
if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) {
continue;
}
errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path)));
if (prefs.abortEarly) {
return errors;
}
errored = true;
ordereds.shift();
break;
}
if (errored) {
continue;
}
// Ordered
if (schema.$_terms.ordered.length) {
if (ordereds.length) {
const ordered = ordereds.shift();
const res = ordered.$_validate(item, state.localize(path, ancestors, ordered), prefs);
if (!res.errors) {
if (ordered._flags.result === 'strip') {
internals.fastSplice(value, i);
--i;
--il;
}
else if (!schema._flags.sparse && res.value === undefined) {
errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path)));
if (prefs.abortEarly) {
return errors;
}
continue;
}
else {
value[i] = res.value;
}
}
else {
errors.push(...res.errors);
if (prefs.abortEarly) {
return errors;
}
}
continue;
}
else if (!schema.$_terms.items.length) {
errors.push(error('array.orderedLength', { pos: i, limit: schema.$_terms.ordered.length }));
if (prefs.abortEarly) {
return errors;
}
break; // No reason to continue since there are no other rules to validate other than array.orderedLength
}
}
// Requireds
const requiredChecks = [];
let jl = requireds.length;
for (let j = 0; j < jl; ++j) {
const localState = state.localize(path, ancestors, requireds[j]);
localState.snapshot();
const res = requireds[j].$_validate(item, localState, prefs);
requiredChecks[j] = res;
if (!res.errors) {
localState.commit();
value[i] = res.value;
isValid = true;
internals.fastSplice(requireds, j);
--j;
--jl;
if (!schema._flags.sparse &&
res.value === undefined) {
errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path)));
if (prefs.abortEarly) {
return errors;
}
}
break;
}
localState.restore();
}
if (isValid) {
continue;
}
// Inclusions
const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false;
jl = inclusions.length;
for (const inclusion of inclusions) {
// Avoid re-running requireds that already didn't match in the previous loop
let res;
const previousCheck = requireds.indexOf(inclusion);
if (previousCheck !== -1) {
res = requiredChecks[previousCheck];
}
else {
const localState = state.localize(path, ancestors, inclusion);
localState.snapshot();
res = inclusion.$_validate(item, localState, prefs);
if (!res.errors) {
localState.commit();
if (inclusion._flags.result === 'strip') {
internals.fastSplice(value, i);
--i;
--il;
}
else if (!schema._flags.sparse &&
res.value === undefined) {
errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path)));
errored = true;
}
else {
value[i] = res.value;
}
isValid = true;
break;
}
localState.restore();
}
// Return the actual error if only one inclusion defined
if (jl === 1) {
if (stripUnknown) {
internals.fastSplice(value, i);
--i;
--il;
isValid = true;
break;
}
errors.push(...res.errors);
if (prefs.abortEarly) {
return errors;
}
errored = true;
break;
}
}
if (errored) {
continue;
}
if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) &&
!isValid) {
if (stripUnknown) {
internals.fastSplice(value, i);
--i;
--il;
continue;
}
errors.push(error('array.includes', { pos: i, value: item }, state.localize(path)));
if (prefs.abortEarly) {
return errors;
}
}
}
if (requireds.length) {
internals.fillMissedErrors(schema, errors, requireds, value, state, prefs);
}
if (ordereds.length) {
internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs);
if (!errors.length) {
internals.fillDefault(ordereds, value, state, prefs);
}
}
return errors.length ? errors : value;
},
priority: true,
manifest: false
},
length: {
method(limit) {
return this.$_addRule({ name: 'length', args: { limit }, operator: '=' });
},
validate(value, helpers, { limit }, { name, operator, args }) {
if (Common.compare(value.length, limit, operator)) {
return value;
}
return helpers.error('array.' + name, { limit: args.limit, value });
},
args: [
{
name: 'limit',
ref: true,
assert: Common.limit,
message: 'must be a positive integer'
}
]
},
max: {
method(limit) {
return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' });
}
},
min: {
method(limit) {
return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' });
}
},
ordered: {
method(...schemas) {
Common.verifyFlat(schemas, 'ordered');
const obj = this.$_addRule('items');
for (let i = 0; i < schemas.length; ++i) {
const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true });
internals.validateSingle(type, obj);
obj.$_mutateRegister(type);
obj.$_terms.ordered.push(type);
}
return obj.$_mutateRebuild();
}
},
single: {
method(enabled) {
const value = enabled === undefined ? true : !!enabled;
Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items');
return this.$_setFlag('single', value);
}
},
sort: {
method(options = {}) {
Common.assertOptions(options, ['by', 'order']);
const settings = {
order: options.order || 'ascending'
};
if (options.by) {
settings.by = Compile.ref(options.by, { ancestor: 0 });
Assert(!settings.by.ancestor, 'Cannot sort by ancestor');
}
return this.$_addRule({ name: 'sort', args: { options: settings } });
},
validate(value, { error, state, prefs, schema }, { options }) {
const { value: sorted, errors } = internals.sort(schema, value, options, state, prefs);
if (errors) {
return errors;
}
for (let i = 0; i < value.length; ++i) {
if (value[i] !== sorted[i]) {
return error('array.sort', { order: options.order, by: options.by ? options.by.key : 'value' });
}
}
return value;
},
convert: true
},
sparse: {
method(enabled) {
const value = enabled === undefined ? true : !!enabled;
if (this._flags.sparse === value) {
return this;
}
const obj = value ? this.clone() : this.$_addRule('items');
return obj.$_setFlag('sparse', value, { clone: false });
}
},
unique: {
method(comparator, options = {}) {
Assert(!comparator || typeof comparator === 'function' || typeof comparator === 'string', 'comparator must be a function or a string');
Common.assertOptions(options, ['ignoreUndefined', 'separator']);
const rule = { name: 'unique', args: { options, comparator } };
if (comparator) {
if (typeof comparator === 'string') {
const separator = Common.default(options.separator, '.');
rule.path = separator ? comparator.split(separator) : [comparator];
}
else {
rule.comparator = comparator;
}
}
return this.$_addRule(rule);
},
validate(value, { state, error, schema }, { comparator: raw, options }, { comparator, path }) {
const found = {
string: Object.create(null),
number: Object.create(null),
undefined: Object.create(null),
boolean: Object.create(null),
bigint: Object.create(null),
object: new Map(),
function: new Map(),
custom: new Map()
};
const compare = comparator || DeepEqual;
const ignoreUndefined = options.ignoreUndefined;
for (let i = 0; i < value.length; ++i) {
const item = path ? Reach(value[i], path) : value[i];
const records = comparator ? found.custom : found[typeof item];
Assert(records, 'Failed to find unique map container for type', typeof item);
if (records instanceof Map) {
const entries = records.entries();
let current;
while (!(current = entries.next()).done) {
if (compare(current.value[0], item)) {
const localState = state.localize([...state.path, i], [value, ...state.ancestors]);
const context = {
pos: i,
value: value[i],
dupePos: current.value[1],
dupeValue: value[current.value[1]]
};
if (path) {
context.path = raw;
}
return error('array.unique', context, localState);
}
}
records.set(item, i);
}
else {
if ((!ignoreUndefined || item !== undefined) &&
records[item] !== undefined) {
const context = {
pos: i,
value: value[i],
dupePos: records[item],
dupeValue: value[records[item]]
};
if (path) {
context.path = raw;
}
const localState = state.localize([...state.path, i], [value, ...state.ancestors]);
return error('array.unique', context, localState);
}
records[item] = i;
}
}
return value;
},
args: ['comparator', 'options'],
multi: true
}
},
cast: {
set: {
from: Array.isArray,
to(value, helpers) {
return new Set(value);
}
}
},
rebuild(schema) {
schema.$_terms._inclusions = [];
schema.$_terms._exclusions = [];
schema.$_terms._requireds = [];
for (const type of schema.$_terms.items) {
internals.validateSingle(type, schema);
if (type._flags.presence === 'required') {
schema.$_terms._requireds.push(type);
}
else if (type._flags.presence === 'forbidden') {
schema.$_terms._exclusions.push(type);
}
else {
schema.$_terms._inclusions.push(type);
}
}
for (const type of schema.$_terms.ordered) {
internals.validateSingle(type, schema);
}
},
manifest: {
build(obj, desc) {
if (desc.items) {
obj = obj.items(...desc.items);
}
if (desc.ordered) {
obj = obj.ordered(...desc.ordered);
}
return obj;
}
},
messages: {
'array.base': '{{#label}} must be an array',
'array.excludes': '{{#label}} contains an excluded value',
'array.hasKnown': '{{#label}} does not contain at least one required match for type {:#patternLabel}',
'array.hasUnknown': '{{#label}} does not contain at least one required match',
'array.includes': '{{#label}} does not match any of the allowed types',
'array.includesRequiredBoth': '{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)',
'array.includesRequiredKnowns': '{{#label}} does not contain {{#knownMisses}}',
'array.includesRequiredUnknowns': '{{#label}} does not contain {{#unknownMisses}} required value(s)',
'array.length': '{{#label}} must contain {{#limit}} items',
'array.max': '{{#label}} must contain less than or equal to {{#limit}} items',
'array.min': '{{#label}} must contain at least {{#limit}} items',
'array.orderedLength': '{{#label}} must contain at most {{#limit}} items',
'array.sort': '{{#label}} must be sorted in {#order} order by {{#by}}',
'array.sort.mismatching': '{{#label}} cannot be sorted due to mismatching types',
'array.sort.unsupported': '{{#label}} cannot be sorted due to unsupported type {#type}',
'array.sparse': '{{#label}} must not be a sparse array item',
'array.unique': '{{#label}} contains a duplicate value'
}
});
// Helpers
internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) {
const knownMisses = [];
let unknownMisses = 0;
for (const required of requireds) {
const label = required._flags.label;
if (label) {
knownMisses.push(label);
}
else {
++unknownMisses;
}
}
if (knownMisses.length) {
if (unknownMisses) {
errors.push(schema.$_createError('array.includesRequiredBoth', value, { knownMisses, unknownMisses }, state, prefs));
}
else {
errors.push(schema.$_createError('array.includesRequiredKnowns', value, { knownMisses }, state, prefs));
}
}
else {
errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs));
}
};
internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) {
const requiredOrdereds = [];
for (const ordered of ordereds) {
if (ordered._flags.presence === 'required') {
requiredOrdereds.push(ordered);
}
}
if (requiredOrdereds.length) {
internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs);
}
};
internals.fillDefault = function (ordereds, value, state, prefs) {
const overrides = [];
let trailingUndefined = true;
for (let i = ordereds.length - 1; i >= 0; --i) {
const ordered = ordereds[i];
const ancestors = [value, ...state.ancestors];
const override = ordered.$_validate(undefined, state.localize(state.path, ancestors, ordered), prefs).value;
if (trailingUndefined) {
if (override === undefined) {
continue;
}
trailingUndefined = false;
}
overrides.unshift(override);
}
if (overrides.length) {
value.push(...overrides);
}
};
internals.fastSplice = function (arr, i) {
let pos = i;
while (pos < arr.length) {
arr[pos++] = arr[pos];
}
--arr.length;
};
internals.validateSingle = function (type, obj) {
if (type.type === 'array' ||
type._flags._arrayItems) {
Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled');
obj.$_setFlag('_arrayItems', true, { clone: false });
}
};
internals.sort = function (schema, value, settings, state, prefs) {
const order = settings.order === 'ascending' ? 1 : -1;
const aFirst = -1 * order;
const bFirst = order;
const sort = (a, b) => {
let compare = internals.compare(a, b, aFirst, bFirst);
if (compare !== null) {
return compare;
}
if (settings.by) {
a = settings.by.resolve(a, state, prefs);
b = settings.by.resolve(b, state, prefs);
}
compare = internals.compare(a, b, aFirst, bFirst);
if (compare !== null) {
return compare;
}
const type = typeof a;
if (type !== typeof b) {
throw schema.$_createError('array.sort.mismatching', value, null, state, prefs);
}
if (type !== 'number' &&
type !== 'string') {
throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs);
}
if (type === 'number') {
return (a - b) * order;
}
return a < b ? aFirst : bFirst;
};
try {
return { value: value.slice().sort(sort) };
}
catch (err) {
return { errors: err };
}
};
internals.compare = function (a, b, aFirst, bFirst) {
if (a === b) {
return 0;
}
if (a === undefined) {
return 1; // Always last regardless of sort order
}
if (b === undefined) {
return -1; // Always last regardless of sort order
}
if (a === null) {
return bFirst;
}
if (b === null) {
return aFirst;
}
return null;
};
/***/ }),
/***/ 34288:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const internals = {};
module.exports = Any.extend({
type: 'binary',
coerce: {
from: ['string', 'object'],
method(value, { schema }) {
if (typeof value === 'string' || (value !== null && value.type === 'Buffer')) {
try {
return { value: Buffer.from(value, schema._flags.encoding) };
}
catch (ignoreErr) { }
}
}
},
validate(value, { error }) {
if (!Buffer.isBuffer(value)) {
return { value, errors: error('binary.base') };
}
},
rules: {
encoding: {
method(encoding) {
Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding);
return this.$_setFlag('encoding', encoding);
}
},
length: {
method(limit) {
return this.$_addRule({ name: 'length', method: 'length', args: { limit }, operator: '=' });
},
validate(value, helpers, { limit }, { name, operator, args }) {
if (Common.compare(value.length, limit, operator)) {
return value;
}
return helpers.error('binary.' + name, { limit: args.limit, value });
},
args: [
{
name: 'limit',
ref: true,
assert: Common.limit,
message: 'must be a positive integer'
}
]
},
max: {
method(limit) {
return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' });
}
},
min: {
method(limit) {
return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' });
}
}
},
cast: {
string: {
from: (value) => Buffer.isBuffer(value),
to(value, helpers) {
return value.toString();
}
}
},
messages: {
'binary.base': '{{#label}} must be a buffer or a string',
'binary.length': '{{#label}} must be {{#limit}} bytes',
'binary.max': '{{#label}} must be less than or equal to {{#limit}} bytes',
'binary.min': '{{#label}} must be at least {{#limit}} bytes'
}
});
/***/ }),
/***/ 47489:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Values = __nccwpck_require__(71944);
const internals = {};
internals.isBool = function (value) {
return typeof value === 'boolean';
};
module.exports = Any.extend({
type: 'boolean',
flags: {
sensitive: { default: false }
},
terms: {
falsy: {
init: null,
manifest: 'values'
},
truthy: {
init: null,
manifest: 'values'
}
},
coerce(value, { schema }) {
if (typeof value === 'boolean') {
return;
}
if (typeof value === 'string') {
const normalized = schema._flags.sensitive ? value : value.toLowerCase();
value = normalized === 'true' ? true : (normalized === 'false' ? false : value);
}
if (typeof value !== 'boolean') {
value = schema.$_terms.truthy && schema.$_terms.truthy.has(value, null, null, !schema._flags.sensitive) ||
(schema.$_terms.falsy && schema.$_terms.falsy.has(value, null, null, !schema._flags.sensitive) ? false : value);
}
return { value };
},
validate(value, { error }) {
if (typeof value !== 'boolean') {
return { value, errors: error('boolean.base') };
}
},
rules: {
truthy: {
method(...values) {
Common.verifyFlat(values, 'truthy');
const obj = this.clone();
obj.$_terms.truthy = obj.$_terms.truthy || new Values();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Assert(value !== undefined, 'Cannot call truthy with undefined');
obj.$_terms.truthy.add(value);
}
return obj;
}
},
falsy: {
method(...values) {
Common.verifyFlat(values, 'falsy');
const obj = this.clone();
obj.$_terms.falsy = obj.$_terms.falsy || new Values();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Assert(value !== undefined, 'Cannot call falsy with undefined');
obj.$_terms.falsy.add(value);
}
return obj;
}
},
sensitive: {
method(enabled = true) {
return this.$_setFlag('sensitive', enabled);
}
}
},
cast: {
number: {
from: internals.isBool,
to(value, helpers) {
return value ? 1 : 0;
}
},
string: {
from: internals.isBool,
to(value, helpers) {
return value ? 'true' : 'false';
}
}
},
manifest: {
build(obj, desc) {
if (desc.truthy) {
obj = obj.truthy(...desc.truthy);
}
if (desc.falsy) {
obj = obj.falsy(...desc.falsy);
}
return obj;
}
},
messages: {
'boolean.base': '{{#label}} must be a boolean'
}
});
/***/ }),
/***/ 6624:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Template = __nccwpck_require__(51396);
const internals = {};
internals.isDate = function (value) {
return value instanceof Date;
};
module.exports = Any.extend({
type: 'date',
coerce: {
from: ['number', 'string'],
method(value, { schema }) {
return { value: internals.parse(value, schema._flags.format) || value };
}
},
validate(value, { schema, error, prefs }) {
if (value instanceof Date &&
!isNaN(value.getTime())) {
return;
}
const format = schema._flags.format;
if (!prefs.convert ||
!format ||
typeof value !== 'string') {
return { value, errors: error('date.base') };
}
return { value, errors: error('date.format', { format }) };
},
rules: {
compare: {
method: false,
validate(value, helpers, { date }, { name, operator, args }) {
const to = date === 'now' ? Date.now() : date.getTime();
if (Common.compare(value.getTime(), to, operator)) {
return value;
}
return helpers.error('date.' + name, { limit: args.date, value });
},
args: [
{
name: 'date',
ref: true,
normalize: (date) => {
return date === 'now' ? date : internals.parse(date);
},
assert: (date) => date !== null,
message: 'must have a valid date format'
}
]
},
format: {
method(format) {
Assert(['iso', 'javascript', 'unix'].includes(format), 'Unknown date format', format);
return this.$_setFlag('format', format);
}
},
greater: {
method(date) {
return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' });
}
},
iso: {
method() {
return this.format('iso');
}
},
less: {
method(date) {
return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' });
}
},
max: {
method(date) {
return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' });
}
},
min: {
method(date) {
return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' });
}
},
timestamp: {
method(type = 'javascript') {
Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"');
return this.format(type);
}
}
},
cast: {
number: {
from: internals.isDate,
to(value, helpers) {
return value.getTime();
}
},
string: {
from: internals.isDate,
to(value, { prefs }) {
return Template.date(value, prefs);
}
}
},
messages: {
'date.base': '{{#label}} must be a valid date',
'date.format': '{{#label}} must be in {msg("date.format." + #format) || #format} format',
'date.greater': '{{#label}} must be greater than {{:#limit}}',
'date.less': '{{#label}} must be less than {{:#limit}}',
'date.max': '{{#label}} must be less than or equal to {{:#limit}}',
'date.min': '{{#label}} must be greater than or equal to {{:#limit}}',
// Messages used in date.format
'date.format.iso': 'ISO 8601 date',
'date.format.javascript': 'timestamp or number of milliseconds',
'date.format.unix': 'timestamp or number of seconds'
}
});
// Helpers
internals.parse = function (value, format) {
if (value instanceof Date) {
return value;
}
if (typeof value !== 'string' &&
(isNaN(value) || !isFinite(value))) {
return null;
}
if (/^\s*$/.test(value)) {
return null;
}
// ISO
if (format === 'iso') {
if (!Common.isIsoDate(value)) {
return null;
}
return internals.date(value.toString());
}
// Normalize number string
const original = value;
if (typeof value === 'string' &&
/^[+-]?\d+(\.\d+)?$/.test(value)) {
value = parseFloat(value);
}
// Timestamp
if (format) {
if (format === 'javascript') {
return internals.date(1 * value); // Casting to number
}
if (format === 'unix') {
return internals.date(1000 * value);
}
if (typeof original === 'string') {
return null;
}
}
// Plain
return internals.date(value);
};
internals.date = function (value) {
const date = new Date(value);
if (!isNaN(date.getTime())) {
return date;
}
return null;
};
/***/ }),
/***/ 62269:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Keys = __nccwpck_require__(79130);
const internals = {};
module.exports = Keys.extend({
type: 'function',
properties: {
typeof: 'function'
},
rules: {
arity: {
method(n) {
Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer');
return this.$_addRule({ name: 'arity', args: { n } });
},
validate(value, helpers, { n }) {
if (value.length === n) {
return value;
}
return helpers.error('function.arity', { n });
}
},
class: {
method() {
return this.$_addRule('class');
},
validate(value, helpers) {
if ((/^\s*class\s/).test(value.toString())) {
return value;
}
return helpers.error('function.class', { value });
}
},
minArity: {
method(n) {
Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer');
return this.$_addRule({ name: 'minArity', args: { n } });
},
validate(value, helpers, { n }) {
if (value.length >= n) {
return value;
}
return helpers.error('function.minArity', { n });
}
},
maxArity: {
method(n) {
Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer');
return this.$_addRule({ name: 'maxArity', args: { n } });
},
validate(value, helpers, { n }) {
if (value.length <= n) {
return value;
}
return helpers.error('function.maxArity', { n });
}
}
},
messages: {
'function.arity': '{{#label}} must have an arity of {{#n}}',
'function.class': '{{#label}} must be a class',
'function.maxArity': '{{#label}} must have an arity lesser or equal to {{#n}}',
'function.minArity': '{{#label}} must have an arity greater or equal to {{#n}}'
}
});
/***/ }),
/***/ 79130:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const ApplyToDefaults = __nccwpck_require__(85545);
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Topo = __nccwpck_require__(88392);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const Errors = __nccwpck_require__(69490);
const Ref = __nccwpck_require__(73838);
const Template = __nccwpck_require__(51396);
const internals = {
renameDefaults: {
alias: false, // Keep old value in place
multiple: false, // Allow renaming multiple keys into the same target
override: false // Overrides an existing key
}
};
module.exports = Any.extend({
type: '_keys',
properties: {
typeof: 'object'
},
flags: {
unknown: { default: false }
},
terms: {
dependencies: { init: null },
keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } },
patterns: { init: null },
renames: { init: null }
},
args(schema, keys) {
return schema.keys(keys);
},
validate(value, { schema, error, state, prefs }) {
if (!value ||
typeof value !== schema.$_property('typeof') ||
Array.isArray(value)) {
return { value, errors: error('object.base', { type: schema.$_property('typeof') }) };
}
// Skip if there are no other rules to test
if (!schema.$_terms.renames &&
!schema.$_terms.dependencies &&
!schema.$_terms.keys && // null allows any keys
!schema.$_terms.patterns &&
!schema.$_terms.externals) {
return;
}
// Shallow clone value
value = internals.clone(value, prefs);
const errors = [];
// Rename keys
if (schema.$_terms.renames &&
!internals.rename(schema, value, state, prefs, errors)) {
return { value, errors };
}
// Anything allowed
if (!schema.$_terms.keys && // null allows any keys
!schema.$_terms.patterns &&
!schema.$_terms.dependencies) {
return { value, errors };
}
// Defined keys
const unprocessed = new Set(Object.keys(value));
if (schema.$_terms.keys) {
const ancestors = [value, ...state.ancestors];
for (const child of schema.$_terms.keys) {
const key = child.key;
const item = value[key];
unprocessed.delete(key);
const localState = state.localize([...state.path, key], ancestors, child);
const result = child.schema.$_validate(item, localState, prefs);
if (result.errors) {
if (prefs.abortEarly) {
return { value, errors: result.errors };
}
if (result.value !== undefined) {
value[key] = result.value;
}
errors.push(...result.errors);
}
else if (child.schema._flags.result === 'strip' ||
result.value === undefined && item !== undefined) {
delete value[key];
}
else if (result.value !== undefined) {
value[key] = result.value;
}
}
}
// Unknown keys
if (unprocessed.size ||
schema._flags._hasPatternMatch) {
const early = internals.unknown(schema, value, unprocessed, errors, state, prefs);
if (early) {
return early;
}
}
// Validate dependencies
if (schema.$_terms.dependencies) {
for (const dep of schema.$_terms.dependencies) {
if (
dep.key !== null &&
internals.isPresent(dep.options)(dep.key.resolve(value, state, prefs, null, { shadow: false })) === false
) {
continue;
}
const failed = internals.dependencies[dep.rel](schema, dep, value, state, prefs);
if (failed) {
const report = schema.$_createError(failed.code, value, failed.context, state, prefs);
if (prefs.abortEarly) {
return { value, errors: report };
}
errors.push(report);
}
}
}
return { value, errors };
},
rules: {
and: {
method(...peers /*, [options] */) {
Common.verifyFlat(peers, 'and');
return internals.dependency(this, 'and', null, peers);
}
},
append: {
method(schema) {
if (schema === null ||
schema === undefined ||
Object.keys(schema).length === 0) {
return this;
}
return this.keys(schema);
}
},
assert: {
method(subject, schema, message) {
if (!Template.isTemplate(subject)) {
subject = Compile.ref(subject);
}
Assert(message === undefined || typeof message === 'string', 'Message must be a string');
schema = this.$_compile(schema, { appendPath: true });
const obj = this.$_addRule({ name: 'assert', args: { subject, schema, message } });
obj.$_mutateRegister(subject);
obj.$_mutateRegister(schema);
return obj;
},
validate(value, { error, prefs, state }, { subject, schema, message }) {
const about = subject.resolve(value, state, prefs);
const path = Ref.isRef(subject) ? subject.absolute(state) : [];
if (schema.$_match(about, state.localize(path, [value, ...state.ancestors], schema), prefs)) {
return value;
}
return error('object.assert', { subject, message });
},
args: ['subject', 'schema', 'message'],
multi: true
},
instance: {
method(constructor, name) {
Assert(typeof constructor === 'function', 'constructor must be a function');
name = name || constructor.name;
return this.$_addRule({ name: 'instance', args: { constructor, name } });
},
validate(value, helpers, { constructor, name }) {
if (value instanceof constructor) {
return value;
}
return helpers.error('object.instance', { type: name, value });
},
args: ['constructor', 'name']
},
keys: {
method(schema) {
Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema');
const obj = this.clone();
if (!schema) { // Allow all
obj.$_terms.keys = null;
}
else if (!Object.keys(schema).length) { // Allow none
obj.$_terms.keys = new internals.Keys();
}
else {
obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys();
for (const key in schema) {
Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key);
}
}
return obj.$_mutateRebuild();
}
},
length: {
method(limit) {
return this.$_addRule({ name: 'length', args: { limit }, operator: '=' });
},
validate(value, helpers, { limit }, { name, operator, args }) {
if (Common.compare(Object.keys(value).length, limit, operator)) {
return value;
}
return helpers.error('object.' + name, { limit: args.limit, value });
},
args: [
{
name: 'limit',
ref: true,
assert: Common.limit,
message: 'must be a positive integer'
}
]
},
max: {
method(limit) {
return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' });
}
},
min: {
method(limit) {
return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' });
}
},
nand: {
method(...peers /*, [options] */) {
Common.verifyFlat(peers, 'nand');
return internals.dependency(this, 'nand', null, peers);
}
},
or: {
method(...peers /*, [options] */) {
Common.verifyFlat(peers, 'or');
return internals.dependency(this, 'or', null, peers);
}
},
oxor: {
method(...peers /*, [options] */) {
return internals.dependency(this, 'oxor', null, peers);
}
},
pattern: {
method(pattern, schema, options = {}) {
const isRegExp = pattern instanceof RegExp;
if (!isRegExp) {
pattern = this.$_compile(pattern, { appendPath: true });
}
Assert(schema !== undefined, 'Invalid rule');
Common.assertOptions(options, ['fallthrough', 'matches']);
if (isRegExp) {
Assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode');
}
schema = this.$_compile(schema, { appendPath: true });
const obj = this.clone();
obj.$_terms.patterns = obj.$_terms.patterns || [];
const config = { [isRegExp ? 'regex' : 'schema']: pattern, rule: schema };
if (options.matches) {
config.matches = this.$_compile(options.matches);
if (config.matches.type !== 'array') {
config.matches = config.matches.$_root.array().items(config.matches);
}
obj.$_mutateRegister(config.matches);
obj.$_setFlag('_hasPatternMatch', true, { clone: false });
}
if (options.fallthrough) {
config.fallthrough = true;
}
obj.$_terms.patterns.push(config);
obj.$_mutateRegister(schema);
return obj;
}
},
ref: {
method() {
return this.$_addRule('ref');
},
validate(value, helpers) {
if (Ref.isRef(value)) {
return value;
}
return helpers.error('object.refType', { value });
}
},
regex: {
method() {
return this.$_addRule('regex');
},
validate(value, helpers) {
if (value instanceof RegExp) {
return value;
}
return helpers.error('object.regex', { value });
}
},
rename: {
method(from, to, options = {}) {
Assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument');
Assert(typeof to === 'string' || to instanceof Template, 'Invalid rename to argument');
Assert(to !== from, 'Cannot rename key to same name:', from);
Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']);
const obj = this.clone();
obj.$_terms.renames = obj.$_terms.renames || [];
for (const rename of obj.$_terms.renames) {
Assert(rename.from !== from, 'Cannot rename the same key multiple times');
}
if (to instanceof Template) {
obj.$_mutateRegister(to);
}
obj.$_terms.renames.push({
from,
to,
options: ApplyToDefaults(internals.renameDefaults, options)
});
return obj;
}
},
schema: {
method(type = 'any') {
return this.$_addRule({ name: 'schema', args: { type } });
},
validate(value, helpers, { type }) {
if (Common.isSchema(value) &&
(type === 'any' || value.type === type)) {
return value;
}
return helpers.error('object.schema', { type });
}
},
unknown: {
method(allow) {
return this.$_setFlag('unknown', allow !== false);
}
},
with: {
method(key, peers, options = {}) {
return internals.dependency(this, 'with', key, peers, options);
}
},
without: {
method(key, peers, options = {}) {
return internals.dependency(this, 'without', key, peers, options);
}
},
xor: {
method(...peers /*, [options] */) {
Common.verifyFlat(peers, 'xor');
return internals.dependency(this, 'xor', null, peers);
}
}
},
overrides: {
default(value, options) {
if (value === undefined) {
value = Common.symbols.deepDefault;
}
return this.$_parent('default', value, options);
}
},
rebuild(schema) {
if (schema.$_terms.keys) {
const topo = new Topo.Sorter();
for (const child of schema.$_terms.keys) {
Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key);
}
schema.$_terms.keys = new internals.Keys(...topo.nodes);
}
},
manifest: {
build(obj, desc) {
if (desc.keys) {
obj = obj.keys(desc.keys);
}
if (desc.dependencies) {
for (const { rel, key = null, peers, options } of desc.dependencies) {
obj = internals.dependency(obj, rel, key, peers, options);
}
}
if (desc.patterns) {
for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) {
obj = obj.pattern(regex || schema, rule, { fallthrough, matches });
}
}
if (desc.renames) {
for (const { from, to, options } of desc.renames) {
obj = obj.rename(from, to, options);
}
}
return obj;
}
},
messages: {
'object.and': '{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}',
'object.assert': '{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}',
'object.base': '{{#label}} must be of type {{#type}}',
'object.instance': '{{#label}} must be an instance of {{:#type}}',
'object.length': '{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}',
'object.max': '{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}',
'object.min': '{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}',
'object.missing': '{{#label}} must contain at least one of {{#peersWithLabels}}',
'object.nand': '{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}',
'object.oxor': '{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}',
'object.pattern.match': '{{#label}} keys failed to match pattern requirements',
'object.refType': '{{#label}} must be a Joi reference',
'object.regex': '{{#label}} must be a RegExp object',
'object.rename.multiple': '{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}',
'object.rename.override': '{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists',
'object.schema': '{{#label}} must be a Joi schema of {{#type}} type',
'object.unknown': '{{#label}} is not allowed',
'object.with': '{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}',
'object.without': '{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}',
'object.xor': '{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}'
}
});
// Helpers
internals.clone = function (value, prefs) {
// Object
if (typeof value === 'object') {
if (prefs.nonEnumerables) {
return Clone(value, { shallow: true });
}
const clone = Object.create(Object.getPrototypeOf(value));
Object.assign(clone, value);
return clone;
}
// Function
const clone = function (...args) {
return value.apply(this, args);
};
clone.prototype = Clone(value.prototype);
Object.defineProperty(clone, 'name', { value: value.name, writable: false });
Object.defineProperty(clone, 'length', { value: value.length, writable: false });
Object.assign(clone, value);
return clone;
};
internals.dependency = function (schema, rel, key, peers, options) {
Assert(key === null || typeof key === 'string', rel, 'key must be a strings');
// Extract options from peers array
if (!options) {
options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {};
}
Common.assertOptions(options, ['separator', 'isPresent']);
peers = [].concat(peers);
// Cast peer paths
const separator = Common.default(options.separator, '.');
const paths = [];
for (const peer of peers) {
Assert(typeof peer === 'string', rel, 'peers must be strings');
paths.push(Compile.ref(peer, { separator, ancestor: 0, prefix: false }));
}
// Cast key
if (key !== null) {
key = Compile.ref(key, { separator, ancestor: 0, prefix: false });
}
// Add rule
const obj = schema.clone();
obj.$_terms.dependencies = obj.$_terms.dependencies || [];
obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers, options));
return obj;
};
internals.dependencies = {
and(schema, dep, value, state, prefs) {
const missing = [];
const present = [];
const count = dep.peers.length;
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) {
missing.push(peer.key);
}
else {
present.push(peer.key);
}
}
if (missing.length !== count &&
present.length !== count) {
return {
code: 'object.and',
context: {
present,
presentWithLabels: internals.keysToLabels(schema, present),
missing,
missingWithLabels: internals.keysToLabels(schema, missing)
}
};
}
},
nand(schema, dep, value, state, prefs) {
const present = [];
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) {
present.push(peer.key);
}
}
if (present.length !== dep.peers.length) {
return;
}
const main = dep.paths[0];
const values = dep.paths.slice(1);
return {
code: 'object.nand',
context: {
main,
mainWithLabel: internals.keysToLabels(schema, main),
peers: values,
peersWithLabels: internals.keysToLabels(schema, values)
}
};
},
or(schema, dep, value, state, prefs) {
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) {
return;
}
}
return {
code: 'object.missing',
context: {
peers: dep.paths,
peersWithLabels: internals.keysToLabels(schema, dep.paths)
}
};
},
oxor(schema, dep, value, state, prefs) {
const present = [];
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) {
present.push(peer.key);
}
}
if (!present.length ||
present.length === 1) {
return;
}
const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) };
context.present = present;
context.presentWithLabels = internals.keysToLabels(schema, present);
return { code: 'object.oxor', context };
},
with(schema, dep, value, state, prefs) {
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) {
return {
code: 'object.with',
context: {
main: dep.key.key,
mainWithLabel: internals.keysToLabels(schema, dep.key.key),
peer: peer.key,
peerWithLabel: internals.keysToLabels(schema, peer.key)
}
};
}
}
},
without(schema, dep, value, state, prefs) {
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) {
return {
code: 'object.without',
context: {
main: dep.key.key,
mainWithLabel: internals.keysToLabels(schema, dep.key.key),
peer: peer.key,
peerWithLabel: internals.keysToLabels(schema, peer.key)
}
};
}
}
},
xor(schema, dep, value, state, prefs) {
const present = [];
const isPresent = internals.isPresent(dep.options);
for (const peer of dep.peers) {
if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) {
present.push(peer.key);
}
}
if (present.length === 1) {
return;
}
const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) };
if (present.length === 0) {
return { code: 'object.missing', context };
}
context.present = present;
context.presentWithLabels = internals.keysToLabels(schema, present);
return { code: 'object.xor', context };
}
};
internals.keysToLabels = function (schema, keys) {
if (Array.isArray(keys)) {
return keys.map((key) => schema.$_mapLabels(key));
}
return schema.$_mapLabels(keys);
};
internals.isPresent = function (options) {
return typeof options.isPresent === 'function' ? options.isPresent : (resolved) => resolved !== undefined;
};
internals.rename = function (schema, value, state, prefs, errors) {
const renamed = {};
for (const rename of schema.$_terms.renames) {
const matches = [];
const pattern = typeof rename.from !== 'string';
if (!pattern) {
if (Object.prototype.hasOwnProperty.call(value, rename.from) &&
(value[rename.from] !== undefined || !rename.options.ignoreUndefined)) {
matches.push(rename);
}
}
else {
for (const from in value) {
if (value[from] === undefined &&
rename.options.ignoreUndefined) {
continue;
}
if (from === rename.to) {
continue;
}
const match = rename.from.exec(from);
if (!match) {
continue;
}
matches.push({ from, to: rename.to, match });
}
}
for (const match of matches) {
const from = match.from;
let to = match.to;
if (to instanceof Template) {
to = to.render(value, state, prefs, match.match);
}
if (from === to) {
continue;
}
if (!rename.options.multiple &&
renamed[to]) {
errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs));
if (prefs.abortEarly) {
return false;
}
}
if (Object.prototype.hasOwnProperty.call(value, to) &&
!rename.options.override &&
!renamed[to]) {
errors.push(schema.$_createError('object.rename.override', value, { from, to, pattern }, state, prefs));
if (prefs.abortEarly) {
return false;
}
}
if (value[from] === undefined) {
delete value[to];
}
else {
value[to] = value[from];
}
renamed[to] = true;
if (!rename.options.alias) {
delete value[from];
}
}
}
return true;
};
internals.unknown = function (schema, value, unprocessed, errors, state, prefs) {
if (schema.$_terms.patterns) {
let hasMatches = false;
const matches = schema.$_terms.patterns.map((pattern) => {
if (pattern.matches) {
hasMatches = true;
return [];
}
});
const ancestors = [value, ...state.ancestors];
for (const key of unprocessed) {
const item = value[key];
const path = [...state.path, key];
for (let i = 0; i < schema.$_terms.patterns.length; ++i) {
const pattern = schema.$_terms.patterns[i];
if (pattern.regex) {
const match = pattern.regex.test(key);
state.mainstay.tracer.debug(state, 'rule', `pattern.${i}`, match ? 'pass' : 'error');
if (!match) {
continue;
}
}
else {
if (!pattern.schema.$_match(key, state.nest(pattern.schema, `pattern.${i}`), prefs)) {
continue;
}
}
unprocessed.delete(key);
const localState = state.localize(path, ancestors, { schema: pattern.rule, key });
const result = pattern.rule.$_validate(item, localState, prefs);
if (result.errors) {
if (prefs.abortEarly) {
return { value, errors: result.errors };
}
errors.push(...result.errors);
}
if (pattern.matches) {
matches[i].push(key);
}
value[key] = result.value;
if (!pattern.fallthrough) {
break;
}
}
}
// Validate pattern matches rules
if (hasMatches) {
for (let i = 0; i < matches.length; ++i) {
const match = matches[i];
if (!match) {
continue;
}
const stpm = schema.$_terms.patterns[i].matches;
const localState = state.localize(state.path, ancestors, stpm);
const result = stpm.$_validate(match, localState, prefs);
if (result.errors) {
const details = Errors.details(result.errors, { override: false });
details.matches = match;
const report = schema.$_createError('object.pattern.match', value, details, state, prefs);
if (prefs.abortEarly) {
return { value, errors: report };
}
errors.push(report);
}
}
}
}
if (!unprocessed.size ||
!schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed
return;
}
if (prefs.stripUnknown && !schema._flags.unknown ||
prefs.skipFunctions) {
const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false;
for (const key of unprocessed) {
if (stripUnknown) {
delete value[key];
unprocessed.delete(key);
}
else if (typeof value[key] === 'function') {
unprocessed.delete(key);
}
}
}
const forbidUnknown = !Common.default(schema._flags.unknown, prefs.allowUnknown);
if (forbidUnknown) {
for (const unprocessedKey of unprocessed) {
const localState = state.localize([...state.path, unprocessedKey], []);
const report = schema.$_createError('object.unknown', value[unprocessedKey], { child: unprocessedKey }, localState, prefs, { flags: false });
if (prefs.abortEarly) {
return { value, errors: report };
}
errors.push(report);
}
}
};
internals.Dependency = class {
constructor(rel, key, peers, paths, options) {
this.rel = rel;
this.key = key;
this.peers = peers;
this.paths = paths;
this.options = options;
}
describe() {
const desc = {
rel: this.rel,
peers: this.paths
};
if (this.key !== null) {
desc.key = this.key.key;
}
if (this.peers[0].separator !== '.') {
desc.options = { ...desc.options, separator: this.peers[0].separator };
}
if (this.options.isPresent) {
desc.options = { ...desc.options, isPresent: this.options.isPresent };
}
return desc;
}
};
internals.Keys = class extends Array {
concat(source) {
const result = this.slice();
const keys = new Map();
for (let i = 0; i < result.length; ++i) {
keys.set(result[i].key, i);
}
for (const item of source) {
const key = item.key;
const pos = keys.get(key);
if (pos !== undefined) {
result[pos] = { key, schema: result[pos].schema.concat(item.schema) };
}
else {
result.push(item);
}
}
return result;
}
};
/***/ }),
/***/ 69869:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const Compile = __nccwpck_require__(3038);
const Errors = __nccwpck_require__(69490);
const internals = {};
module.exports = Any.extend({
type: 'link',
properties: {
schemaChain: true
},
terms: {
link: { init: null, manifest: 'single', register: false }
},
args(schema, ref) {
return schema.ref(ref);
},
validate(value, { schema, state, prefs }) {
Assert(schema.$_terms.link, 'Uninitialized link schema');
const linked = internals.generate(schema, value, state, prefs);
const ref = schema.$_terms.link[0].ref;
return linked.$_validate(value, state.nest(linked, `link:${ref.display}:${linked.type}`), prefs);
},
generate(schema, value, state, prefs) {
return internals.generate(schema, value, state, prefs);
},
rules: {
ref: {
method(ref) {
Assert(!this.$_terms.link, 'Cannot reinitialize schema');
ref = Compile.ref(ref);
Assert(ref.type === 'value' || ref.type === 'local', 'Invalid reference type:', ref.type);
Assert(ref.type === 'local' || ref.ancestor === 'root' || ref.ancestor > 0, 'Link cannot reference itself');
const obj = this.clone();
obj.$_terms.link = [{ ref }];
return obj;
}
},
relative: {
method(enabled = true) {
return this.$_setFlag('relative', enabled);
}
}
},
overrides: {
concat(source) {
Assert(this.$_terms.link, 'Uninitialized link schema');
Assert(Common.isSchema(source), 'Invalid schema object');
Assert(source.type !== 'link', 'Cannot merge type link with another link');
const obj = this.clone();
if (!obj.$_terms.whens) {
obj.$_terms.whens = [];
}
obj.$_terms.whens.push({ concat: source });
return obj.$_mutateRebuild();
}
},
manifest: {
build(obj, desc) {
Assert(desc.link, 'Invalid link description missing link');
return obj.ref(desc.link);
}
}
});
// Helpers
internals.generate = function (schema, value, state, prefs) {
let linked = state.mainstay.links.get(schema);
if (linked) {
return linked._generate(value, state, prefs).schema;
}
const ref = schema.$_terms.link[0].ref;
const { perspective, path } = internals.perspective(ref, state);
internals.assert(perspective, 'which is outside of schema boundaries', ref, schema, state, prefs);
try {
linked = path.length ? perspective.$_reach(path) : perspective;
}
catch (ignoreErr) {
internals.assert(false, 'to non-existing schema', ref, schema, state, prefs);
}
internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs);
if (!schema._flags.relative) {
state.mainstay.links.set(schema, linked);
}
return linked._generate(value, state, prefs).schema;
};
internals.perspective = function (ref, state) {
if (ref.type === 'local') {
for (const { schema, key } of state.schemas) { // From parent to root
const id = schema._flags.id || key;
if (id === ref.path[0]) {
return { perspective: schema, path: ref.path.slice(1) };
}
if (schema.$_terms.shared) {
for (const shared of schema.$_terms.shared) {
if (shared._flags.id === ref.path[0]) {
return { perspective: shared, path: ref.path.slice(1) };
}
}
}
}
return { perspective: null, path: null };
}
if (ref.ancestor === 'root') {
return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path };
}
return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path };
};
internals.assert = function (condition, message, ref, schema, state, prefs) {
if (condition) { // Manual check to avoid generating error message on success
return;
}
Assert(false, `"${Errors.label(schema._flags, state, prefs)}" contains link reference "${ref.display}" ${message}`);
};
/***/ }),
/***/ 15855:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const internals = {
numberRx: /^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i,
precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,
exponentialPartRegex: /[eE][+-]?\d+$/,
leadingSignAndZerosRegex: /^[+-]?(0*)?/,
dotRegex: /\./,
trailingZerosRegex: /0+$/,
decimalPlaces(value) {
const str = value.toString();
const dindex = str.indexOf('.');
const eindex = str.indexOf('e');
return (
(dindex < 0 ? 0 : (eindex < 0 ? str.length : eindex) - dindex - 1) +
(eindex < 0 ? 0 : Math.max(0, -parseInt(str.slice(eindex + 1))))
);
}
};
module.exports = Any.extend({
type: 'number',
flags: {
unsafe: { default: false }
},
coerce: {
from: 'string',
method(value, { schema, error }) {
const matches = value.match(internals.numberRx);
if (!matches) {
return;
}
value = value.trim();
const result = { value: parseFloat(value) };
if (result.value === 0) {
result.value = 0; // -0
}
if (!schema._flags.unsafe) {
if (value.match(/e/i)) {
if (internals.extractSignificantDigits(value) !== internals.extractSignificantDigits(String(result.value))) {
result.errors = error('number.unsafe');
return result;
}
}
else {
const string = result.value.toString();
if (string.match(/e/i)) {
return result;
}
if (string !== internals.normalizeDecimal(value)) {
result.errors = error('number.unsafe');
return result;
}
}
}
return result;
}
},
validate(value, { schema, error, prefs }) {
if (value === Infinity ||
value === -Infinity) {
return { value, errors: error('number.infinity') };
}
if (!Common.isNumber(value)) {
return { value, errors: error('number.base') };
}
const result = { value };
if (prefs.convert) {
const rule = schema.$_getRule('precision');
if (rule) {
const precision = Math.pow(10, rule.args.limit); // This is conceptually equivalent to using toFixed but it should be much faster
result.value = Math.round(result.value * precision) / precision;
}
}
if (result.value === 0) {
result.value = 0; // -0
}
if (!schema._flags.unsafe &&
(value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) {
result.errors = error('number.unsafe');
}
return result;
},
rules: {
compare: {
method: false,
validate(value, helpers, { limit }, { name, operator, args }) {
if (Common.compare(value, limit, operator)) {
return value;
}
return helpers.error('number.' + name, { limit: args.limit, value });
},
args: [
{
name: 'limit',
ref: true,
assert: Common.isNumber,
message: 'must be a number'
}
]
},
greater: {
method(limit) {
return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' });
}
},
integer: {
method() {
return this.$_addRule('integer');
},
validate(value, helpers) {
if (Math.trunc(value) - value === 0) {
return value;
}
return helpers.error('number.integer');
}
},
less: {
method(limit) {
return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' });
}
},
max: {
method(limit) {
return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' });
}
},
min: {
method(limit) {
return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' });
}
},
multiple: {
method(base) {
const baseDecimalPlace = typeof base === 'number' ? internals.decimalPlaces(base) : null;
const pfactor = Math.pow(10, baseDecimalPlace);
return this.$_addRule({
name: 'multiple',
args: {
base,
baseDecimalPlace,
pfactor
}
});
},
validate(value, helpers, { base, baseDecimalPlace, pfactor }, options) {
const valueDecimalPlace = internals.decimalPlaces(value);
if (valueDecimalPlace > baseDecimalPlace) {
// Value with higher precision than base can never be a multiple
return helpers.error('number.multiple', { multiple: options.args.base, value });
}
return Math.round(pfactor * value) % Math.round(pfactor * base) === 0 ?
value :
helpers.error('number.multiple', { multiple: options.args.base, value });
},
args: [
{
name: 'base',
ref: true,
assert: (value) => typeof value === 'number' && isFinite(value) && value > 0,
message: 'must be a positive number'
},
'baseDecimalPlace',
'pfactor'
],
multi: true
},
negative: {
method() {
return this.sign('negative');
}
},
port: {
method() {
return this.$_addRule('port');
},
validate(value, helpers) {
if (Number.isSafeInteger(value) &&
value >= 0 &&
value <= 65535) {
return value;
}
return helpers.error('number.port');
}
},
positive: {
method() {
return this.sign('positive');
}
},
precision: {
method(limit) {
Assert(Number.isSafeInteger(limit), 'limit must be an integer');
return this.$_addRule({ name: 'precision', args: { limit } });
},
validate(value, helpers, { limit }) {
const places = value.toString().match(internals.precisionRx);
const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
if (decimals <= limit) {
return value;
}
return helpers.error('number.precision', { limit, value });
},
convert: true
},
sign: {
method(sign) {
Assert(['negative', 'positive'].includes(sign), 'Invalid sign', sign);
return this.$_addRule({ name: 'sign', args: { sign } });
},
validate(value, helpers, { sign }) {
if (sign === 'negative' && value < 0 ||
sign === 'positive' && value > 0) {
return value;
}
return helpers.error(`number.${sign}`);
}
},
unsafe: {
method(enabled = true) {
Assert(typeof enabled === 'boolean', 'enabled must be a boolean');
return this.$_setFlag('unsafe', enabled);
}
}
},
cast: {
string: {
from: (value) => typeof value === 'number',
to(value, helpers) {
return value.toString();
}
}
},
messages: {
'number.base': '{{#label}} must be a number',
'number.greater': '{{#label}} must be greater than {{#limit}}',
'number.infinity': '{{#label}} cannot be infinity',
'number.integer': '{{#label}} must be an integer',
'number.less': '{{#label}} must be less than {{#limit}}',
'number.max': '{{#label}} must be less than or equal to {{#limit}}',
'number.min': '{{#label}} must be greater than or equal to {{#limit}}',
'number.multiple': '{{#label}} must be a multiple of {{#multiple}}',
'number.negative': '{{#label}} must be a negative number',
'number.port': '{{#label}} must be a valid port',
'number.positive': '{{#label}} must be a positive number',
'number.precision': '{{#label}} must have no more than {{#limit}} decimal places',
'number.unsafe': '{{#label}} must be a safe number'
}
});
// Helpers
internals.extractSignificantDigits = function (value) {
return value
.replace(internals.exponentialPartRegex, '')
.replace(internals.dotRegex, '')
.replace(internals.trailingZerosRegex, '')
.replace(internals.leadingSignAndZerosRegex, '');
};
internals.normalizeDecimal = function (str) {
str = str
// Remove leading plus signs
.replace(/^\+/, '')
// Remove trailing zeros if there is a decimal point and unecessary decimal points
.replace(/\.0*$/, '')
// Add a integer 0 if the numbers starts with a decimal point
.replace(/^(-?)\.([^\.]*)$/, '$10.$2')
// Remove leading zeros
.replace(/^(-?)0+([0-9])/, '$1$2');
if (str.includes('.') &&
str.endsWith('0')) {
str = str.replace(/0+$/, '');
}
if (str === '-0') {
return '0';
}
return str;
};
/***/ }),
/***/ 46878:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Keys = __nccwpck_require__(79130);
const internals = {};
module.exports = Keys.extend({
type: 'object',
cast: {
map: {
from: (value) => value && typeof value === 'object',
to(value, helpers) {
return new Map(Object.entries(value));
}
}
}
});
/***/ }),
/***/ 72260:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Domain = __nccwpck_require__(97425);
const Email = __nccwpck_require__(3283);
const Ip = __nccwpck_require__(82337);
const EscapeRegex = __nccwpck_require__(91965);
const Tlds = __nccwpck_require__(53092);
const Uri = __nccwpck_require__(74983);
const Any = __nccwpck_require__(9512);
const Common = __nccwpck_require__(72448);
const internals = {
tlds: Tlds instanceof Set ? { tlds: { allow: Tlds, deny: null } } : false, // $lab:coverage:ignore$
base64Regex: {
// paddingRequired
true: {
// urlSafe
true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/,
false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/
},
false: {
true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/,
false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/
}
},
dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,
hexRegex: {
withPrefix: /^0x[0-9a-f]+$/i,
withOptionalPrefix: /^(?:0x)?[0-9a-f]+$/i,
withoutPrefix: /^[0-9a-f]+$/i
},
ipRegex: Ip.regex({ cidr: 'forbidden' }).regex,
isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,
guidBrackets: {
'{': '}', '[': ']', '(': ')', '': ''
},
guidVersions: {
uuidv1: '1',
uuidv2: '2',
uuidv3: '3',
uuidv4: '4',
uuidv5: '5',
uuidv6: '6',
uuidv7: '7',
uuidv8: '8'
},
guidSeparators: new Set([undefined, true, false, '-', ':']),
normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD']
};
module.exports = Any.extend({
type: 'string',
flags: {
insensitive: { default: false },
truncate: { default: false }
},
terms: {
replacements: { init: null }
},
coerce: {
from: 'string',
method(value, { schema, state, prefs }) {
const normalize = schema.$_getRule('normalize');
if (normalize) {
value = value.normalize(normalize.args.form);
}
const casing = schema.$_getRule('case');
if (casing) {
value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase();
}
const trim = schema.$_getRule('trim');
if (trim &&
trim.args.enabled) {
value = value.trim();
}
if (schema.$_terms.replacements) {
for (const replacement of schema.$_terms.replacements) {
value = value.replace(replacement.pattern, replacement.replacement);
}
}
const hex = schema.$_getRule('hex');
if (hex &&
hex.args.options.byteAligned &&
value.length % 2 !== 0) {
value = `0${value}`;
}
if (schema.$_getRule('isoDate')) {
const iso = internals.isoDate(value);
if (iso) {
value = iso;
}
}
if (schema._flags.truncate) {
const rule = schema.$_getRule('max');
if (rule) {
let limit = rule.args.limit;
if (Common.isResolvable(limit)) {
limit = limit.resolve(value, state, prefs);
if (!Common.limit(limit)) {
return { value, errors: schema.$_createError('any.ref', limit, { ref: rule.args.limit, arg: 'limit', reason: 'must be a positive integer' }, state, prefs) };
}
}
value = value.slice(0, limit);
}
}
return { value };
}
},
validate(value, { schema, error }) {
if (typeof value !== 'string') {
return { value, errors: error('string.base') };
}
if (value === '') {
const min = schema.$_getRule('min');
if (min &&
min.args.limit === 0) {
return;
}
return { value, errors: error('string.empty') };
}
},
rules: {
alphanum: {
method() {
return this.$_addRule('alphanum');
},
validate(value, helpers) {
if (/^[a-zA-Z0-9]+$/.test(value)) {
return value;
}
return helpers.error('string.alphanum');
}
},
base64: {
method(options = {}) {
Common.assertOptions(options, ['paddingRequired', 'urlSafe']);
options = { urlSafe: false, paddingRequired: true, ...options };
Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean');
Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean');
return this.$_addRule({ name: 'base64', args: { options } });
},
validate(value, helpers, { options }) {
const regex = internals.base64Regex[options.paddingRequired][options.urlSafe];
if (regex.test(value)) {
return value;
}
return helpers.error('string.base64');
}
},
case: {
method(direction) {
Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction);
return this.$_addRule({ name: 'case', args: { direction } });
},
validate(value, helpers, { direction }) {
if (direction === 'lower' && value === value.toLocaleLowerCase() ||
direction === 'upper' && value === value.toLocaleUpperCase()) {
return value;
}
return helpers.error(`string.${direction}case`);
},
convert: true
},
creditCard: {
method() {
return this.$_addRule('creditCard');
},
validate(value, helpers) {
let i = value.length;
let sum = 0;
let mul = 1;
while (i--) {
const char = value.charAt(i) * mul;
sum = sum + (char - (char > 9) * 9);
mul = mul ^ 3;
}
if (sum > 0 &&
sum % 10 === 0) {
return value;
}
return helpers.error('string.creditCard');
}
},
dataUri: {
method(options = {}) {
Common.assertOptions(options, ['paddingRequired']);
options = { paddingRequired: true, ...options };
Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean');
return this.$_addRule({ name: 'dataUri', args: { options } });
},
validate(value, helpers, { options }) {
const matches = value.match(internals.dataUriRegex);
if (matches) {
if (!matches[2]) {
return value;
}
if (matches[2] !== 'base64') {
return value;
}
const base64regex = internals.base64Regex[options.paddingRequired].false;
if (base64regex.test(matches[3])) {
return value;
}
}
return helpers.error('string.dataUri');
}
},
domain: {
method(options) {
if (options) {
Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']);
}
const address = internals.addressOptions(options);
return this.$_addRule({ name: 'domain', args: { options }, address });
},
validate(value, helpers, args, { address }) {
if (Domain.isValid(value, address)) {
return value;
}
return helpers.error('string.domain');
}
},
email: {
method(options = {}) {
Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'ignoreLength', 'maxDomainSegments', 'minDomainSegments', 'multiple', 'separator', 'tlds']);
Assert(options.multiple === undefined || typeof options.multiple === 'boolean', 'multiple option must be an boolean');
const address = internals.addressOptions(options);
const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`);
return this.$_addRule({ name: 'email', args: { options }, regex, address });
},
validate(value, helpers, { options }, { regex, address }) {
const emails = options.multiple ? value.split(regex) : [value];
const invalids = [];
for (const email of emails) {
if (!Email.isValid(email, address)) {
invalids.push(email);
}
}
if (!invalids.length) {
return value;
}
return helpers.error('string.email', { value, invalids });
}
},
guid: {
alias: 'uuid',
method(options = {}) {
Common.assertOptions(options, ['version', 'separator']);
let versionNumbers = '';
if (options.version) {
const versions = [].concat(options.version);
Assert(versions.length >= 1, 'version must have at least 1 valid version specified');
const set = new Set();
for (let i = 0; i < versions.length; ++i) {
const version = versions[i];
Assert(typeof version === 'string', 'version at position ' + i + ' must be a string');
const versionNumber = internals.guidVersions[version.toLowerCase()];
Assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', '));
Assert(!set.has(versionNumber), 'version at position ' + i + ' must not be a duplicate');
versionNumbers += versionNumber;
set.add(versionNumber);
}
}
Assert(internals.guidSeparators.has(options.separator), 'separator must be one of true, false, "-", or ":"');
const separator = options.separator === undefined ? '[:-]?' :
options.separator === true ? '[:-]' :
options.separator === false ? '[]?' : `\\${options.separator}`;
const regex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${separator})[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i');
return this.$_addRule({ name: 'guid', args: { options }, regex });
},
validate(value, helpers, args, { regex }) {
const results = regex.exec(value);
if (!results) {
return helpers.error('string.guid');
}
// Matching braces
if (internals.guidBrackets[results[1]] !== results[results.length - 1]) {
return helpers.error('string.guid');
}
return value;
}
},
hex: {
method(options = {}) {
Common.assertOptions(options, ['byteAligned', 'prefix']);
options = { byteAligned: false, prefix: false, ...options };
Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean');
Assert(typeof options.prefix === 'boolean' || options.prefix === 'optional', 'prefix must be boolean or "optional"');
return this.$_addRule({ name: 'hex', args: { options } });
},
validate(value, helpers, { options }) {
const re = options.prefix === 'optional' ?
internals.hexRegex.withOptionalPrefix :
options.prefix === true ?
internals.hexRegex.withPrefix :
internals.hexRegex.withoutPrefix;
if (!re.test(value)) {
return helpers.error('string.hex');
}
if (options.byteAligned &&
value.length % 2 !== 0) {
return helpers.error('string.hexAlign');
}
return value;
}
},
hostname: {
method() {
return this.$_addRule('hostname');
},
validate(value, helpers) {
if (Domain.isValid(value, { minDomainSegments: 1 }) ||
internals.ipRegex.test(value)) {
return value;
}
return helpers.error('string.hostname');
}
},
insensitive: {
method() {
return this.$_setFlag('insensitive', true);
}
},
ip: {
method(options = {}) {
Common.assertOptions(options, ['cidr', 'version']);
const { cidr, versions, regex } = Ip.regex(options);
const version = options.version ? versions : undefined;
return this.$_addRule({ name: 'ip', args: { options: { cidr, version } }, regex });
},
validate(value, helpers, { options }, { regex }) {
if (regex.test(value)) {
return value;
}
if (options.version) {
return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version });
}
return helpers.error('string.ip', { value, cidr: options.cidr });
}
},
isoDate: {
method() {
return this.$_addRule('isoDate');
},
validate(value, { error }) {
if (internals.isoDate(value)) {
return value;
}
return error('string.isoDate');
}
},
isoDuration: {
method() {
return this.$_addRule('isoDuration');
},
validate(value, helpers) {
if (internals.isoDurationRegex.test(value)) {
return value;
}
return helpers.error('string.isoDuration');
}
},
length: {
method(limit, encoding) {
return internals.length(this, 'length', limit, '=', encoding);
},
validate(value, helpers, { limit, encoding }, { name, operator, args }) {
const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$
if (Common.compare(length, limit, operator)) {
return value;
}
return helpers.error('string.' + name, { limit: args.limit, value, encoding });
},
args: [
{
name: 'limit',
ref: true,
assert: Common.limit,
message: 'must be a positive integer'
},
'encoding'
]
},
lowercase: {
method() {
return this.case('lower');
}
},
max: {
method(limit, encoding) {
return internals.length(this, 'max', limit, '<=', encoding);
},
args: ['limit', 'encoding']
},
min: {
method(limit, encoding) {
return internals.length(this, 'min', limit, '>=', encoding);
},
args: ['limit', 'encoding']
},
normalize: {
method(form = 'NFC') {
Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', '));
return this.$_addRule({ name: 'normalize', args: { form } });
},
validate(value, { error }, { form }) {
if (value === value.normalize(form)) {
return value;
}
return error('string.normalize', { value, form });
},
convert: true
},
pattern: {
alias: 'regex',
method(regex, options = {}) {
Assert(regex instanceof RegExp, 'regex must be a RegExp');
Assert(!regex.flags.includes('g') && !regex.flags.includes('y'), 'regex should not use global or sticky mode');
if (typeof options === 'string') {
options = { name: options };
}
Common.assertOptions(options, ['invert', 'name']);
const errorCode = ['string.pattern', options.invert ? '.invert' : '', options.name ? '.name' : '.base'].join('');
return this.$_addRule({ name: 'pattern', args: { regex, options }, errorCode });
},
validate(value, helpers, { regex, options }, { errorCode }) {
const patternMatch = regex.test(value);
if (patternMatch ^ options.invert) {
return value;
}
return helpers.error(errorCode, { name: options.name, regex, value });
},
args: ['regex', 'options'],
multi: true
},
replace: {
method(pattern, replacement) {
if (typeof pattern === 'string') {
pattern = new RegExp(EscapeRegex(pattern), 'g');
}
Assert(pattern instanceof RegExp, 'pattern must be a RegExp');
Assert(typeof replacement === 'string', 'replacement must be a String');
const obj = this.clone();
if (!obj.$_terms.replacements) {
obj.$_terms.replacements = [];
}
obj.$_terms.replacements.push({ pattern, replacement });
return obj;
}
},
token: {
method() {
return this.$_addRule('token');
},
validate(value, helpers) {
if (/^\w+$/.test(value)) {
return value;
}
return helpers.error('string.token');
}
},
trim: {
method(enabled = true) {
Assert(typeof enabled === 'boolean', 'enabled must be a boolean');
return this.$_addRule({ name: 'trim', args: { enabled } });
},
validate(value, helpers, { enabled }) {
if (!enabled ||
value === value.trim()) {
return value;
}
return helpers.error('string.trim');
},
convert: true
},
truncate: {
method(enabled = true) {
Assert(typeof enabled === 'boolean', 'enabled must be a boolean');
return this.$_setFlag('truncate', enabled);
}
},
uppercase: {
method() {
return this.case('upper');
}
},
uri: {
method(options = {}) {
Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme', 'encodeUri']);
if (options.domain) {
Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']);
}
const { regex, scheme } = Uri.regex(options);
const domain = options.domain ? internals.addressOptions(options.domain) : null;
return this.$_addRule({ name: 'uri', args: { options }, regex, domain, scheme });
},
validate(value, helpers, { options }, { regex, domain, scheme }) {
if (['http:/', 'https:/'].includes(value)) { // scheme:/ is technically valid but makes no sense
return helpers.error('string.uri');
}
let match = regex.exec(value);
if (!match && helpers.prefs.convert && options.encodeUri) {
const encoded = encodeURI(value);
match = regex.exec(encoded);
if (match) {
value = encoded;
}
}
if (match) {
const matched = match[1] || match[2];
if (domain &&
(!options.allowRelative || matched) &&
!Domain.isValid(matched, domain)) {
return helpers.error('string.domain', { value: matched });
}
return value;
}
if (options.relativeOnly) {
return helpers.error('string.uriRelativeOnly');
}
if (options.scheme) {
return helpers.error('string.uriCustomScheme', { scheme, value });
}
return helpers.error('string.uri');
}
}
},
manifest: {
build(obj, desc) {
if (desc.replacements) {
for (const { pattern, replacement } of desc.replacements) {
obj = obj.replace(pattern, replacement);
}
}
return obj;
}
},
messages: {
'string.alphanum': '{{#label}} must only contain alpha-numeric characters',
'string.base': '{{#label}} must be a string',
'string.base64': '{{#label}} must be a valid base64 string',
'string.creditCard': '{{#label}} must be a credit card',
'string.dataUri': '{{#label}} must be a valid dataUri string',
'string.domain': '{{#label}} must contain a valid domain name',
'string.email': '{{#label}} must be a valid email',
'string.empty': '{{#label}} is not allowed to be empty',
'string.guid': '{{#label}} must be a valid GUID',
'string.hex': '{{#label}} must only contain hexadecimal characters',
'string.hexAlign': '{{#label}} hex decoded representation must be byte aligned',
'string.hostname': '{{#label}} must be a valid hostname',
'string.ip': '{{#label}} must be a valid ip address with a {{#cidr}} CIDR',
'string.ipVersion': '{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR',
'string.isoDate': '{{#label}} must be in iso format',
'string.isoDuration': '{{#label}} must be a valid ISO 8601 duration',
'string.length': '{{#label}} length must be {{#limit}} characters long',
'string.lowercase': '{{#label}} must only contain lowercase characters',
'string.max': '{{#label}} length must be less than or equal to {{#limit}} characters long',
'string.min': '{{#label}} length must be at least {{#limit}} characters long',
'string.normalize': '{{#label}} must be unicode normalized in the {{#form}} form',
'string.token': '{{#label}} must only contain alpha-numeric and underscore characters',
'string.pattern.base': '{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}',
'string.pattern.name': '{{#label}} with value {:[.]} fails to match the {{#name}} pattern',
'string.pattern.invert.base': '{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}',
'string.pattern.invert.name': '{{#label}} with value {:[.]} matches the inverted {{#name}} pattern',
'string.trim': '{{#label}} must not have leading or trailing whitespace',
'string.uri': '{{#label}} must be a valid uri',
'string.uriCustomScheme': '{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern',
'string.uriRelativeOnly': '{{#label}} must be a valid relative uri',
'string.uppercase': '{{#label}} must only contain uppercase characters'
}
});
// Helpers
internals.addressOptions = function (options) {
if (!options) {
return internals.tlds || options; // $lab:coverage:ignore$
}
// minDomainSegments
Assert(options.minDomainSegments === undefined ||
Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer');
// maxDomainSegments
Assert(options.maxDomainSegments === undefined ||
Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer');
// tlds
if (options.tlds === false) {
return options;
}
if (options.tlds === true ||
options.tlds === undefined) {
Assert(internals.tlds, 'Built-in TLD list disabled');
return Object.assign({}, options, internals.tlds);
}
Assert(typeof options.tlds === 'object', 'tlds must be true, false, or an object');
const deny = options.tlds.deny;
if (deny) {
if (Array.isArray(deny)) {
options = Object.assign({}, options, { tlds: { deny: new Set(deny) } });
}
Assert(options.tlds.deny instanceof Set, 'tlds.deny must be an array, Set, or boolean');
Assert(!options.tlds.allow, 'Cannot specify both tlds.allow and tlds.deny lists');
internals.validateTlds(options.tlds.deny, 'tlds.deny');
return options;
}
const allow = options.tlds.allow;
if (!allow) {
return options;
}
if (allow === true) {
Assert(internals.tlds, 'Built-in TLD list disabled');
return Object.assign({}, options, internals.tlds);
}
if (Array.isArray(allow)) {
options = Object.assign({}, options, { tlds: { allow: new Set(allow) } });
}
Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean');
internals.validateTlds(options.tlds.allow, 'tlds.allow');
return options;
};
internals.validateTlds = function (set, source) {
for (const tld of set) {
Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`);
}
};
internals.isoDate = function (value) {
if (!Common.isIsoDate(value)) {
return null;
}
if (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift
value += '00';
}
const date = new Date(value);
if (isNaN(date.getTime())) {
return null;
}
return date.toISOString();
};
internals.length = function (schema, name, limit, operator, encoding) {
Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$
return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator });
};
/***/ }),
/***/ 40971:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Any = __nccwpck_require__(9512);
const internals = {};
internals.Map = class extends Map {
slice() {
return new internals.Map(this);
}
};
module.exports = Any.extend({
type: 'symbol',
terms: {
map: { init: new internals.Map() }
},
coerce: {
method(value, { schema, error }) {
const lookup = schema.$_terms.map.get(value);
if (lookup) {
value = lookup;
}
if (!schema._flags.only ||
typeof value === 'symbol') {
return { value };
}
return { value, errors: error('symbol.map', { map: schema.$_terms.map }) };
}
},
validate(value, { error }) {
if (typeof value !== 'symbol') {
return { value, errors: error('symbol.base') };
}
},
rules: {
map: {
method(iterable) {
if (iterable &&
!iterable[Symbol.iterator] &&
typeof iterable === 'object') {
iterable = Object.entries(iterable);
}
Assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object');
const obj = this.clone();
const symbols = [];
for (const entry of iterable) {
Assert(entry && entry[Symbol.iterator], 'Entry must be an iterable');
const [key, value] = entry;
Assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be of type object, function, or Symbol');
Assert(typeof value === 'symbol', 'Value must be a Symbol');
obj.$_terms.map.set(key, value);
symbols.push(value);
}
return obj.valid(...symbols);
}
}
},
manifest: {
build(obj, desc) {
if (desc.map) {
obj = obj.map(desc.map);
}
return obj;
}
},
messages: {
'symbol.base': '{{#label}} must be a symbol',
'symbol.map': '{{#label}} must be one of {{#map}}'
}
});
/***/ }),
/***/ 91804:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const Clone = __nccwpck_require__(85578);
const Ignore = __nccwpck_require__(12887);
const Reach = __nccwpck_require__(18891);
const Common = __nccwpck_require__(72448);
const Errors = __nccwpck_require__(69490);
const State = __nccwpck_require__(73634);
const internals = {
result: Symbol('result')
};
exports.entry = function (value, schema, prefs) {
let settings = Common.defaults;
if (prefs) {
Assert(prefs.warnings === undefined, 'Cannot override warnings preference in synchronous validation');
Assert(prefs.artifacts === undefined, 'Cannot override artifacts preference in synchronous validation');
settings = Common.preferences(Common.defaults, prefs);
}
const result = internals.entry(value, schema, settings);
Assert(!result.mainstay.externals.length, 'Schema with external rules must use validateAsync()');
const outcome = { value: result.value };
if (result.error) {
outcome.error = result.error;
}
if (result.mainstay.warnings.length) {
outcome.warning = Errors.details(result.mainstay.warnings);
}
if (result.mainstay.debug) {
outcome.debug = result.mainstay.debug;
}
if (result.mainstay.artifacts) {
outcome.artifacts = result.mainstay.artifacts;
}
return outcome;
};
exports.entryAsync = async function (value, schema, prefs) {
let settings = Common.defaults;
if (prefs) {
settings = Common.preferences(Common.defaults, prefs);
}
const result = internals.entry(value, schema, settings);
const mainstay = result.mainstay;
if (result.error) {
if (mainstay.debug) {
result.error.debug = mainstay.debug;
}
throw result.error;
}
if (mainstay.externals.length) {
let root = result.value;
const errors = [];
for (const external of mainstay.externals) {
const path = external.state.path;
const linked = external.schema.type === 'link' ? mainstay.links.get(external.schema) : null;
let node = root;
let key;
let parent;
const ancestors = path.length ? [root] : [];
const original = path.length ? Reach(value, path) : value;
if (path.length) {
key = path[path.length - 1];
let current = root;
for (const segment of path.slice(0, -1)) {
current = current[segment];
ancestors.unshift(current);
}
parent = ancestors[0];
node = parent[key];
}
try {
const createError = (code, local) => (linked || external.schema).$_createError(code, node, local, external.state, settings);
const output = await external.method(node, {
schema: external.schema,
linked,
state: external.state,
prefs,
original,
error: createError,
errorsArray: internals.errorsArray,
warn: (code, local) => mainstay.warnings.push((linked || external.schema).$_createError(code, node, local, external.state, settings)),
message: (messages, local) => (linked || external.schema).$_createError('external', node, local, external.state, settings, { messages })
});
if (output === undefined ||
output === node) {
continue;
}
if (output instanceof Errors.Report) {
mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error');
errors.push(output);
if (settings.abortEarly) {
break;
}
continue;
}
if (Array.isArray(output) &&
output[Common.symbols.errors]) {
mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error');
errors.push(...output);
if (settings.abortEarly) {
break;
}
continue;
}
if (parent) {
mainstay.tracer.value(external.state, 'rule', node, output, 'external');
parent[key] = output;
}
else {
mainstay.tracer.value(external.state, 'rule', root, output, 'external');
root = output;
}
}
catch (err) {
if (settings.errors.label) {
err.message += ` (${(external.label)})`; // Change message to include path
}
throw err;
}
}
result.value = root;
if (errors.length) {
result.error = Errors.process(errors, value, settings);
if (mainstay.debug) {
result.error.debug = mainstay.debug;
}
throw result.error;
}
}
if (!settings.warnings &&
!settings.debug &&
!settings.artifacts) {
return result.value;
}
const outcome = { value: result.value };
if (mainstay.warnings.length) {
outcome.warning = Errors.details(mainstay.warnings);
}
if (mainstay.debug) {
outcome.debug = mainstay.debug;
}
if (mainstay.artifacts) {
outcome.artifacts = mainstay.artifacts;
}
return outcome;
};
internals.Mainstay = class {
constructor(tracer, debug, links) {
this.externals = [];
this.warnings = [];
this.tracer = tracer;
this.debug = debug;
this.links = links;
this.shadow = null;
this.artifacts = null;
this._snapshots = [];
}
snapshot() {
this._snapshots.push({
externals: this.externals.slice(),
warnings: this.warnings.slice()
});
}
restore() {
const snapshot = this._snapshots.pop();
this.externals = snapshot.externals;
this.warnings = snapshot.warnings;
}
commit() {
this._snapshots.pop();
}
};
internals.entry = function (value, schema, prefs) {
// Prepare state
const { tracer, cleanup } = internals.tracer(schema, prefs);
const debug = prefs.debug ? [] : null;
const links = schema._ids._schemaChain ? new Map() : null;
const mainstay = new internals.Mainstay(tracer, debug, links);
const schemas = schema._ids._schemaChain ? [{ schema }] : null;
const state = new State([], [], { mainstay, schemas });
// Validate value
const result = exports.validate(value, schema, state, prefs);
// Process value and errors
if (cleanup) {
schema.$_root.untrace();
}
const error = Errors.process(result.errors, value, prefs);
return { value: result.value, error, mainstay };
};
internals.tracer = function (schema, prefs) {
if (schema.$_root._tracer) {
return { tracer: schema.$_root._tracer._register(schema) };
}
if (prefs.debug) {
Assert(schema.$_root.trace, 'Debug mode not supported');
return { tracer: schema.$_root.trace()._register(schema), cleanup: true };
}
return { tracer: internals.ignore };
};
exports.validate = function (value, schema, state, prefs, overrides = {}) {
if (schema.$_terms.whens) {
schema = schema._generate(value, state, prefs).schema;
}
// Setup state and settings
if (schema._preferences) {
prefs = internals.prefs(schema, prefs);
}
// Cache
if (schema._cache &&
prefs.cache) {
const result = schema._cache.get(value);
state.mainstay.tracer.debug(state, 'validate', 'cached', !!result);
if (result) {
return result;
}
}
// Helpers
const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs);
const helpers = {
original: value,
prefs,
schema,
state,
error: createError,
errorsArray: internals.errorsArray,
warn: (code, local, localState) => state.mainstay.warnings.push(createError(code, local, localState)),
message: (messages, local) => schema.$_createError('custom', value, local, state, prefs, { messages })
};
// Prepare
state.mainstay.tracer.entry(schema, state);
const def = schema._definition;
if (def.prepare &&
value !== undefined &&
prefs.convert) {
const prepared = def.prepare(value, helpers);
if (prepared) {
state.mainstay.tracer.value(state, 'prepare', value, prepared.value);
if (prepared.errors) {
return internals.finalize(prepared.value, [].concat(prepared.errors), helpers); // Prepare error always aborts early
}
value = prepared.value;
}
}
// Type coercion
if (def.coerce &&
value !== undefined &&
prefs.convert &&
(!def.coerce.from || def.coerce.from.includes(typeof value))) {
const coerced = def.coerce.method(value, helpers);
if (coerced) {
state.mainstay.tracer.value(state, 'coerced', value, coerced.value);
if (coerced.errors) {
return internals.finalize(coerced.value, [].concat(coerced.errors), helpers); // Coerce error always aborts early
}
value = coerced.value;
}
}
// Empty value
const empty = schema._flags.empty;
if (empty &&
empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) {
state.mainstay.tracer.value(state, 'empty', value, undefined);
value = undefined;
}
// Presence requirements (required, optional, forbidden)
const presence = overrides.presence || schema._flags.presence || (schema._flags._endedSwitch ? null : prefs.presence);
if (value === undefined) {
if (presence === 'forbidden') {
return internals.finalize(value, null, helpers);
}
if (presence === 'required') {
return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers);
}
if (presence === 'optional') {
if (schema._flags.default !== Common.symbols.deepDefault) {
return internals.finalize(value, null, helpers);
}
state.mainstay.tracer.value(state, 'default', value, {});
value = {};
}
}
else if (presence === 'forbidden') {
return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers);
}
// Allowed values
const errors = [];
if (schema._valids) {
const match = schema._valids.get(value, state, prefs, schema._flags.insensitive);
if (match) {
if (prefs.convert) {
state.mainstay.tracer.value(state, 'valids', value, match.value);
value = match.value;
}
state.mainstay.tracer.filter(schema, state, 'valid', match);
return internals.finalize(value, null, helpers);
}
if (schema._flags.only) {
const report = schema.$_createError('any.only', value, { valids: schema._valids.values({ display: true }) }, state, prefs);
if (prefs.abortEarly) {
return internals.finalize(value, [report], helpers);
}
errors.push(report);
}
}
// Denied values
if (schema._invalids) {
const match = schema._invalids.get(value, state, prefs, schema._flags.insensitive);
if (match) {
state.mainstay.tracer.filter(schema, state, 'invalid', match);
const report = schema.$_createError('any.invalid', value, { invalids: schema._invalids.values({ display: true }) }, state, prefs);
if (prefs.abortEarly) {
return internals.finalize(value, [report], helpers);
}
errors.push(report);
}
}
// Base type
if (def.validate) {
const base = def.validate(value, helpers);
if (base) {
state.mainstay.tracer.value(state, 'base', value, base.value);
value = base.value;
if (base.errors) {
if (!Array.isArray(base.errors)) {
errors.push(base.errors);
return internals.finalize(value, errors, helpers); // Base error always aborts early
}
if (base.errors.length) {
errors.push(...base.errors);
return internals.finalize(value, errors, helpers); // Base error always aborts early
}
}
}
}
// Validate tests
if (!schema._rules.length) {
return internals.finalize(value, errors, helpers);
}
return internals.rules(value, errors, helpers);
};
internals.rules = function (value, errors, helpers) {
const { schema, state, prefs } = helpers;
for (const rule of schema._rules) {
const definition = schema._definition.rules[rule.method];
// Skip rules that are also applied in coerce step
if (definition.convert &&
prefs.convert) {
state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full');
continue;
}
// Resolve references
let ret;
let args = rule.args;
if (rule._resolve.length) {
args = Object.assign({}, args); // Shallow copy
for (const key of rule._resolve) {
const resolver = definition.argsByName.get(key);
const resolved = args[key].resolve(value, state, prefs);
const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved;
const invalid = Common.validateArg(normalized, null, resolver);
if (invalid) {
ret = schema.$_createError('any.ref', resolved, { arg: key, ref: args[key], reason: invalid }, state, prefs);
break;
}
args[key] = normalized;
}
}
// Test rule
ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error
const result = internals.rule(ret, rule);
if (result.errors) {
state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error');
if (rule.warn) {
state.mainstay.warnings.push(...result.errors);
continue;
}
if (prefs.abortEarly) {
return internals.finalize(value, result.errors, helpers);
}
errors.push(...result.errors);
}
else {
state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'pass');
state.mainstay.tracer.value(state, 'rule', value, result.value, rule.name);
value = result.value;
}
}
return internals.finalize(value, errors, helpers);
};
internals.rule = function (ret, rule) {
if (ret instanceof Errors.Report) {
internals.error(ret, rule);
return { errors: [ret], value: null };
}
if (Array.isArray(ret) &&
ret[Common.symbols.errors]) {
ret.forEach((report) => internals.error(report, rule));
return { errors: ret, value: null };
}
return { errors: null, value: ret };
};
internals.error = function (report, rule) {
if (rule.message) {
report._setTemplate(rule.message);
}
return report;
};
internals.finalize = function (value, errors, helpers) {
errors = errors || [];
const { schema, state, prefs } = helpers;
// Failover value
if (errors.length) {
const failover = internals.default('failover', undefined, errors, helpers);
if (failover !== undefined) {
state.mainstay.tracer.value(state, 'failover', value, failover);
value = failover;
errors = [];
}
}
// Error override
if (errors.length &&
schema._flags.error) {
if (typeof schema._flags.error === 'function') {
errors = schema._flags.error(errors);
if (!Array.isArray(errors)) {
errors = [errors];
}
for (const error of errors) {
Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object');
}
}
else {
errors = [schema._flags.error];
}
}
// Default
if (value === undefined) {
const defaulted = internals.default('default', value, errors, helpers);
state.mainstay.tracer.value(state, 'default', value, defaulted);
value = defaulted;
}
// Cast
if (schema._flags.cast &&
value !== undefined) {
const caster = schema._definition.cast[schema._flags.cast];
if (caster.from(value)) {
const casted = caster.to(value, helpers);
state.mainstay.tracer.value(state, 'cast', value, casted, schema._flags.cast);
value = casted;
}
}
// Externals
if (schema.$_terms.externals &&
prefs.externals &&
prefs._externals !== false) { // Disabled for matching
for (const { method } of schema.$_terms.externals) {
state.mainstay.externals.push({ method, schema, state, label: Errors.label(schema._flags, state, prefs) });
}
}
// Result
const result = { value, errors: errors.length ? errors : null };
if (schema._flags.result) {
result.value = schema._flags.result === 'strip' ? undefined : /* raw */ helpers.original;
state.mainstay.tracer.value(state, schema._flags.result, value, result.value);
state.shadow(value, schema._flags.result);
}
// Cache
if (schema._cache &&
prefs.cache !== false &&
!schema._refs.length) {
schema._cache.set(helpers.original, result);
}
// Artifacts
if (value !== undefined &&
!result.errors &&
schema._flags.artifact !== undefined) {
state.mainstay.artifacts = state.mainstay.artifacts || new Map();
if (!state.mainstay.artifacts.has(schema._flags.artifact)) {
state.mainstay.artifacts.set(schema._flags.artifact, []);
}
state.mainstay.artifacts.get(schema._flags.artifact).push(state.path);
}
return result;
};
internals.prefs = function (schema, prefs) {
const isDefaultOptions = prefs === Common.defaults;
if (isDefaultOptions &&
schema._preferences[Common.symbols.prefs]) {
return schema._preferences[Common.symbols.prefs];
}
prefs = Common.preferences(prefs, schema._preferences);
if (isDefaultOptions) {
schema._preferences[Common.symbols.prefs] = prefs;
}
return prefs;
};
internals.default = function (flag, value, errors, helpers) {
const { schema, state, prefs } = helpers;
const source = schema._flags[flag];
if (prefs.noDefaults ||
source === undefined) {
return value;
}
state.mainstay.tracer.log(schema, state, 'rule', flag, 'full');
if (!source) {
return source;
}
if (typeof source === 'function') {
const args = source.length ? [Clone(state.ancestors[0]), helpers] : [];
try {
return source(...args);
}
catch (err) {
errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs));
return;
}
}
if (typeof source !== 'object') {
return source;
}
if (source[Common.symbols.literal]) {
return source.literal;
}
if (Common.isResolvable(source)) {
return source.resolve(value, state, prefs);
}
return Clone(source);
};
internals.trim = function (value, schema) {
if (typeof value !== 'string') {
return value;
}
const trim = schema.$_getRule('trim');
if (!trim ||
!trim.args.enabled) {
return value;
}
return value.trim();
};
internals.ignore = {
active: false,
debug: Ignore,
entry: Ignore,
filter: Ignore,
log: Ignore,
resolve: Ignore,
value: Ignore
};
internals.errorsArray = function () {
const errors = [];
errors[Common.symbols.errors] = true;
return errors;
};
/***/ }),
/***/ 71944:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Assert = __nccwpck_require__(32718);
const DeepEqual = __nccwpck_require__(55801);
const Common = __nccwpck_require__(72448);
const internals = {};
module.exports = internals.Values = class {
constructor(values, refs) {
this._values = new Set(values);
this._refs = new Set(refs);
this._lowercase = internals.lowercases(values);
this._override = false;
}
get length() {
return this._values.size + this._refs.size;
}
add(value, refs) {
// Reference
if (Common.isResolvable(value)) {
if (!this._refs.has(value)) {
this._refs.add(value);
if (refs) { // Skipped in a merge
refs.register(value);
}
}
return;
}
// Value
if (!this.has(value, null, null, false)) {
this._values.add(value);
if (typeof value === 'string') {
this._lowercase.set(value.toLowerCase(), value);
}
}
}
static merge(target, source, remove) {
target = target || new internals.Values();
if (source) {
if (source._override) {
return source.clone();
}
for (const item of [...source._values, ...source._refs]) {
target.add(item);
}
}
if (remove) {
for (const item of [...remove._values, ...remove._refs]) {
target.remove(item);
}
}
return target.length ? target : null;
}
remove(value) {
// Reference
if (Common.isResolvable(value)) {
this._refs.delete(value);
return;
}
// Value
this._values.delete(value);
if (typeof value === 'string') {
this._lowercase.delete(value.toLowerCase());
}
}
has(value, state, prefs, insensitive) {
return !!this.get(value, state, prefs, insensitive);
}
get(value, state, prefs, insensitive) {
if (!this.length) {
return false;
}
// Simple match
if (this._values.has(value)) {
return { value };
}
// Case insensitive string match
if (typeof value === 'string' &&
value &&
insensitive) {
const found = this._lowercase.get(value.toLowerCase());
if (found) {
return { value: found };
}
}
if (!this._refs.size &&
typeof value !== 'object') {
return false;
}
// Objects
if (typeof value === 'object') {
for (const item of this._values) {
if (DeepEqual(item, value)) {
return { value: item };
}
}
}
// References
if (state) {
for (const ref of this._refs) {
const resolved = ref.resolve(value, state, prefs, null, { in: true });
if (resolved === undefined) {
continue;
}
const items = !ref.in || typeof resolved !== 'object'
? [resolved]
: Array.isArray(resolved) ? resolved : Object.keys(resolved);
for (const item of items) {
if (typeof item !== typeof value) {
continue;
}
if (insensitive &&
value &&
typeof value === 'string') {
if (item.toLowerCase() === value.toLowerCase()) {
return { value: item, ref };
}
}
else {
if (DeepEqual(item, value)) {
return { value: item, ref };
}
}
}
}
}
return false;
}
override() {
this._override = true;
}
values(options) {
if (options &&
options.display) {
const values = [];
for (const item of [...this._values, ...this._refs]) {
if (item !== undefined) {
values.push(item);
}
}
return values;
}
return Array.from([...this._values, ...this._refs]);
}
clone() {
const set = new internals.Values(this._values, this._refs);
set._override = this._override;
return set;
}
concat(source) {
Assert(!source._override, 'Cannot concat override set of values');
const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]);
set._override = this._override;
return set;
}
describe() {
const normalized = [];
if (this._override) {
normalized.push({ override: true });
}
for (const value of this._values.values()) {
normalized.push(value && typeof value === 'object' ? { value } : value);
}
for (const value of this._refs.values()) {
normalized.push(value.describe());
}
return normalized;
}
};
internals.Values.prototype[Common.symbols.values] = true;
// Aliases
internals.Values.prototype.slice = internals.Values.prototype.clone;
// Helpers
internals.lowercases = function (from) {
const map = new Map();
if (from) {
for (const value of from) {
if (typeof value === 'string') {
map.set(value.toLowerCase(), value);
}
}
}
return map;
};
/***/ }),
/***/ 24060:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const deepEqual = __nccwpck_require__(28206)
const jsonSchemaRefSymbol = Symbol.for('json-schema-ref')
class RefResolver {
#schemas
#derefSchemas
#insertRefSymbol
#allowEqualDuplicates
#cloneSchemaWithoutRefs
constructor (opts = {}) {
this.#schemas = {}
this.#derefSchemas = {}
this.#insertRefSymbol = opts.insertRefSymbol ?? false
this.#allowEqualDuplicates = opts.allowEqualDuplicates ?? true
this.#cloneSchemaWithoutRefs = opts.cloneSchemaWithoutRefs ?? false
}
addSchema (schema, schemaId) {
if (schema.$id !== undefined && schema.$id.charAt(0) !== '#') {
// Schema has an $id that is not an anchor
schemaId = schema.$id
} else {
// Schema has no $id or $id is an anchor
this.#insertSchemaBySchemaId(schema, schemaId)
}
this.#addSchema(schema, schemaId)
}
getSchema (schemaId, jsonPointer = '#') {
const schema = this.#schemas[schemaId]
if (schema === undefined) {
throw new Error(
`Cannot resolve ref "${schemaId}${jsonPointer}". Schema with id "${schemaId}" is not found.`
)
}
if (schema.anchors[jsonPointer] !== undefined) {
return schema.anchors[jsonPointer]
}
return getDataByJSONPointer(schema.schema, jsonPointer)
}
hasSchema (schemaId) {
return this.#schemas[schemaId] !== undefined
}
getSchemaRefs (schemaId) {
const schema = this.#schemas[schemaId]
if (schema === undefined) {
throw new Error(`Schema with id "${schemaId}" is not found.`)
}
return schema.refs
}
getSchemaDependencies (schemaId, dependencies = {}) {
const schema = this.#schemas[schemaId]
for (const ref of schema.refs) {
const dependencySchemaId = ref.schemaId
if (dependencies[dependencySchemaId] !== undefined) continue
dependencies[dependencySchemaId] = this.getSchema(dependencySchemaId)
this.getSchemaDependencies(dependencySchemaId, dependencies)
}
return dependencies
}
derefSchema (schemaId) {
if (this.#derefSchemas[schemaId] !== undefined) return
const schema = this.#schemas[schemaId]
if (schema === undefined) {
throw new Error(`Schema with id "${schemaId}" is not found.`)
}
if (!this.#cloneSchemaWithoutRefs && schema.refs.length === 0) {
this.#derefSchemas[schemaId] = {
schema: schema.schema,
anchors: schema.anchors
}
}
const refs = []
this.#addDerefSchema(schema.schema, schemaId, refs)
const dependencies = this.getSchemaDependencies(schemaId)
for (const schemaId in dependencies) {
const schema = dependencies[schemaId]
this.#addDerefSchema(schema, schemaId, refs)
}
for (const ref of refs) {
const {
refSchemaId,
refJsonPointer
} = this.#parseSchemaRef(ref.ref, ref.sourceSchemaId)
const targetSchema = this.getDerefSchema(refSchemaId, refJsonPointer)
if (targetSchema === null) {
throw new Error(
`Cannot resolve ref "${ref.ref}". Ref "${refJsonPointer}" is not found in schema "${refSchemaId}".`
)
}
ref.targetSchema = targetSchema
ref.targetSchemaId = refSchemaId
}
for (const ref of refs) {
this.#resolveRef(ref, refs)
}
}
getDerefSchema (schemaId, jsonPointer = '#') {
let derefSchema = this.#derefSchemas[schemaId]
if (derefSchema === undefined) {
this.derefSchema(schemaId)
derefSchema = this.#derefSchemas[schemaId]
}
if (derefSchema.anchors[jsonPointer] !== undefined) {
return derefSchema.anchors[jsonPointer]
}
return getDataByJSONPointer(derefSchema.schema, jsonPointer)
}
#parseSchemaRef (ref, schemaId) {
const sharpIndex = ref.indexOf('#')
if (sharpIndex === -1) {
return { refSchemaId: ref, refJsonPointer: '#' }
}
if (sharpIndex === 0) {
return { refSchemaId: schemaId, refJsonPointer: ref }
}
return {
refSchemaId: ref.slice(0, sharpIndex),
refJsonPointer: ref.slice(sharpIndex)
}
}
#addSchema (schema, rootSchemaId) {
const schemaId = schema.$id
if (schemaId !== undefined && typeof schemaId === 'string') {
if (schemaId.charAt(0) === '#') {
this.#insertSchemaByAnchor(schema, rootSchemaId, schemaId)
} else {
this.#insertSchemaBySchemaId(schema, schemaId)
rootSchemaId = schemaId
}
}
const ref = schema.$ref
if (ref !== undefined && typeof ref === 'string') {
const { refSchemaId, refJsonPointer } = this.#parseSchemaRef(ref, rootSchemaId)
this.#schemas[rootSchemaId].refs.push({
schemaId: refSchemaId,
jsonPointer: refJsonPointer
})
}
for (const key in schema) {
if (typeof schema[key] === 'object' && schema[key] !== null) {
this.#addSchema(schema[key], rootSchemaId)
}
}
}
#addDerefSchema (schema, rootSchemaId, refs = []) {
const derefSchema = Array.isArray(schema) ? [...schema] : { ...schema }
const schemaId = derefSchema.$id
if (schemaId !== undefined && typeof schemaId === 'string') {
if (schemaId.charAt(0) === '#') {
this.#insertDerefSchemaByAnchor(derefSchema, rootSchemaId, schemaId)
} else {
this.#insertDerefSchemaBySchemaId(derefSchema, schemaId)
rootSchemaId = schemaId
}
}
if (derefSchema.$ref !== undefined) {
refs.push({
ref: derefSchema.$ref,
sourceSchemaId: rootSchemaId,
sourceSchema: derefSchema
})
}
for (const key in derefSchema) {
const value = derefSchema[key]
if (typeof value === 'object' && value !== null) {
derefSchema[key] = this.#addDerefSchema(value, rootSchemaId, refs)
}
}
return derefSchema
}
#resolveRef (ref, refs) {
const { sourceSchema, targetSchema } = ref
if (!sourceSchema.$ref) return
if (this.#insertRefSymbol) {
sourceSchema[jsonSchemaRefSymbol] = sourceSchema.$ref
}
delete sourceSchema.$ref
if (targetSchema.$ref) {
const targetSchemaRef = refs.find(ref => ref.sourceSchema === targetSchema)
this.#resolveRef(targetSchemaRef, refs)
}
for (const key in targetSchema) {
if (key === '$id') continue
if (sourceSchema[key] !== undefined) {
if (deepEqual(sourceSchema[key], targetSchema[key])) continue
throw new Error(
`Cannot resolve ref "${ref.ref}". Property "${key}" is already exist in schema "${ref.sourceSchemaId}".`
)
}
sourceSchema[key] = targetSchema[key]
}
ref.isResolved = true
}
#insertSchemaBySchemaId (schema, schemaId) {
const foundSchema = this.#schemas[schemaId]
if (foundSchema !== undefined) {
if (this.#allowEqualDuplicates && deepEqual(schema, foundSchema.schema)) return
throw new Error(`There is already another schema with id "${schemaId}".`)
}
this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }
}
#insertSchemaByAnchor (schema, schemaId, anchor) {
const { anchors } = this.#schemas[schemaId]
if (anchors[anchor] !== undefined) {
throw new Error(`There is already another anchor "${anchor}" in a schema "${schemaId}".`)
}
anchors[anchor] = schema
}
#insertDerefSchemaBySchemaId (schema, schemaId) {
const foundSchema = this.#derefSchemas[schemaId]
if (foundSchema !== undefined) return
this.#derefSchemas[schemaId] = { schema, anchors: {} }
}
#insertDerefSchemaByAnchor (schema, schemaId, anchor) {
const { anchors } = this.#derefSchemas[schemaId]
anchors[anchor] = schema
}
}
function getDataByJSONPointer (data, jsonPointer) {
const parts = jsonPointer.split('/')
let current = data
for (const part of parts) {
if (part === '' || part === '#') continue
if (typeof current !== 'object' || current === null) {
return null
}
current = current[part]
}
return current ?? null
}
module.exports = { RefResolver }
/***/ }),
/***/ 14542:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var _ = (__nccwpck_require__(97063).runInContext)();
module.exports = __nccwpck_require__(30477)(_, _);
/***/ }),
/***/ 30477:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var mapping = __nccwpck_require__(96114),
fallbackHolder = __nccwpck_require__(21817);
/** Built-in value reference. */
var push = Array.prototype.push;
/**
* Creates a function, with an arity of `n`, that invokes `func` with the
* arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} n The arity of the new function.
* @returns {Function} Returns the new function.
*/
function baseArity(func, n) {
return n == 2
? function(a, b) { return func.apply(undefined, arguments); }
: function(a) { return func.apply(undefined, arguments); };
}
/**
* Creates a function that invokes `func`, with up to `n` arguments, ignoring
* any additional arguments.
*
* @private
* @param {Function} func The function to cap arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function baseAry(func, n) {
return n == 2
? function(a, b) { return func(a, b); }
: function(a) { return func(a); };
}
/**
* Creates a clone of `array`.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the cloned array.
*/
function cloneArray(array) {
var length = array ? array.length : 0,
result = Array(length);
while (length--) {
result[length] = array[length];
}
return result;
}
/**
* Creates a function that clones a given object using the assignment `func`.
*
* @private
* @param {Function} func The assignment function.
* @returns {Function} Returns the new cloner function.
*/
function createCloner(func) {
return function(object) {
return func({}, object);
};
}
/**
* A specialized version of `_.spread` which flattens the spread array into
* the arguments of the invoked `func`.
*
* @private
* @param {Function} func The function to spread arguments over.
* @param {number} start The start position of the spread.
* @returns {Function} Returns the new function.
*/
function flatSpread(func, start) {
return function() {
var length = arguments.length,
lastIndex = length - 1,
args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var array = args[start],
otherArgs = args.slice(0, start);
if (array) {
push.apply(otherArgs, array);
}
if (start != lastIndex) {
push.apply(otherArgs, args.slice(start + 1));
}
return func.apply(this, otherArgs);
};
}
/**
* Creates a function that wraps `func` and uses `cloner` to clone the first
* argument it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} cloner The function to clone arguments.
* @returns {Function} Returns the new immutable function.
*/
function wrapImmutable(func, cloner) {
return function() {
var length = arguments.length;
if (!length) {
return;
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var result = args[0] = cloner.apply(undefined, args);
func.apply(undefined, args);
return result;
};
}
/**
* The base implementation of `convert` which accepts a `util` object of methods
* required to perform conversions.
*
* @param {Object} util The util object.
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @param {Object} [options] The options object.
* @param {boolean} [options.cap=true] Specify capping iteratee arguments.
* @param {boolean} [options.curry=true] Specify currying.
* @param {boolean} [options.fixed=true] Specify fixed arity.
* @param {boolean} [options.immutable=true] Specify immutable operations.
* @param {boolean} [options.rearg=true] Specify rearranging arguments.
* @returns {Function|Object} Returns the converted function or object.
*/
function baseConvert(util, name, func, options) {
var isLib = typeof name == 'function',
isObj = name === Object(name);
if (isObj) {
options = func;
func = name;
name = undefined;
}
if (func == null) {
throw new TypeError;
}
options || (options = {});
var config = {
'cap': 'cap' in options ? options.cap : true,
'curry': 'curry' in options ? options.curry : true,
'fixed': 'fixed' in options ? options.fixed : true,
'immutable': 'immutable' in options ? options.immutable : true,
'rearg': 'rearg' in options ? options.rearg : true
};
var defaultHolder = isLib ? func : fallbackHolder,
forceCurry = ('curry' in options) && options.curry,
forceFixed = ('fixed' in options) && options.fixed,
forceRearg = ('rearg' in options) && options.rearg,
pristine = isLib ? func.runInContext() : undefined;
var helpers = isLib ? func : {
'ary': util.ary,
'assign': util.assign,
'clone': util.clone,
'curry': util.curry,
'forEach': util.forEach,
'isArray': util.isArray,
'isError': util.isError,
'isFunction': util.isFunction,
'isWeakMap': util.isWeakMap,
'iteratee': util.iteratee,
'keys': util.keys,
'rearg': util.rearg,
'toInteger': util.toInteger,
'toPath': util.toPath
};
var ary = helpers.ary,
assign = helpers.assign,
clone = helpers.clone,
curry = helpers.curry,
each = helpers.forEach,
isArray = helpers.isArray,
isError = helpers.isError,
isFunction = helpers.isFunction,
isWeakMap = helpers.isWeakMap,
keys = helpers.keys,
rearg = helpers.rearg,
toInteger = helpers.toInteger,
toPath = helpers.toPath;
var aryMethodKeys = keys(mapping.aryMethod);
var wrappers = {
'castArray': function(castArray) {
return function() {
var value = arguments[0];
return isArray(value)
? castArray(cloneArray(value))
: castArray.apply(undefined, arguments);
};
},
'iteratee': function(iteratee) {
return function() {
var func = arguments[0],
arity = arguments[1],
result = iteratee(func, arity),
length = result.length;
if (config.cap && typeof arity == 'number') {
arity = arity > 2 ? (arity - 2) : 1;
return (length && length <= arity) ? result : baseAry(result, arity);
}
return result;
};
},
'mixin': function(mixin) {
return function(source) {
var func = this;
if (!isFunction(func)) {
return mixin(func, Object(source));
}
var pairs = [];
each(keys(source), function(key) {
if (isFunction(source[key])) {
pairs.push([key, func.prototype[key]]);
}
});
mixin(func, Object(source));
each(pairs, function(pair) {
var value = pair[1];
if (isFunction(value)) {
func.prototype[pair[0]] = value;
} else {
delete func.prototype[pair[0]];
}
});
return func;
};
},
'nthArg': function(nthArg) {
return function(n) {
var arity = n < 0 ? 1 : (toInteger(n) + 1);
return curry(nthArg(n), arity);
};
},
'rearg': function(rearg) {
return function(func, indexes) {
var arity = indexes ? indexes.length : 0;
return curry(rearg(func, indexes), arity);
};
},
'runInContext': function(runInContext) {
return function(context) {
return baseConvert(util, runInContext(context), options);
};
}
};
/*--------------------------------------------------------------------------*/
/**
* Casts `func` to a function with an arity capped iteratee if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @returns {Function} Returns the cast function.
*/
function castCap(name, func) {
if (config.cap) {
var indexes = mapping.iterateeRearg[name];
if (indexes) {
return iterateeRearg(func, indexes);
}
var n = !isLib && mapping.iterateeAry[name];
if (n) {
return iterateeAry(func, n);
}
}
return func;
}
/**
* Casts `func` to a curried function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castCurry(name, func, n) {
return (forceCurry || (config.curry && n > 1))
? curry(func, n)
: func;
}
/**
* Casts `func` to a fixed arity function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity cap.
* @returns {Function} Returns the cast function.
*/
function castFixed(name, func, n) {
if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {
var data = mapping.methodSpread[name],
start = data && data.start;
return start === undefined ? ary(func, n) : flatSpread(func, start);
}
return func;
}
/**
* Casts `func` to an rearged function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castRearg(name, func, n) {
return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))
? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])
: func;
}
/**
* Creates a clone of `object` by `path`.
*
* @private
* @param {Object} object The object to clone.
* @param {Array|string} path The path to clone by.
* @returns {Object} Returns the cloned object.
*/
function cloneByPath(object, path) {
path = toPath(path);
var index = -1,
length = path.length,
lastIndex = length - 1,
result = clone(Object(object)),
nested = result;
while (nested != null && ++index < length) {
var key = path[index],
value = nested[key];
if (value != null &&
!(isFunction(value) || isError(value) || isWeakMap(value))) {
nested[key] = clone(index == lastIndex ? value : Object(value));
}
nested = nested[key];
}
return result;
}
/**
* Converts `lodash` to an immutable auto-curried iteratee-first data-last
* version with conversion `options` applied.
*
* @param {Object} [options] The options object. See `baseConvert` for more details.
* @returns {Function} Returns the converted `lodash`.
*/
function convertLib(options) {
return _.runInContext.convert(options)(undefined);
}
/**
* Create a converter function for `func` of `name`.
*
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @returns {Function} Returns the new converter function.
*/
function createConverter(name, func) {
var realName = mapping.aliasToReal[name] || name,
methodName = mapping.remap[realName] || realName,
oldOptions = options;
return function(options) {
var newUtil = isLib ? pristine : helpers,
newFunc = isLib ? pristine[methodName] : func,
newOptions = assign(assign({}, oldOptions), options);
return baseConvert(newUtil, realName, newFunc, newOptions);
};
}
/**
* Creates a function that wraps `func` to invoke its iteratee, with up to `n`
* arguments, ignoring any additional arguments.
*
* @private
* @param {Function} func The function to cap iteratee arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function iterateeAry(func, n) {
return overArg(func, function(func) {
return typeof func == 'function' ? baseAry(func, n) : func;
});
}
/**
* Creates a function that wraps `func` to invoke its iteratee with arguments
* arranged according to the specified `indexes` where the argument value at
* the first index is provided as the first argument, the argument value at
* the second index is provided as the second argument, and so on.
*
* @private
* @param {Function} func The function to rearrange iteratee arguments for.
* @param {number[]} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
*/
function iterateeRearg(func, indexes) {
return overArg(func, function(func) {
var n = indexes.length;
return baseArity(rearg(baseAry(func, n), indexes), n);
});
}
/**
* Creates a function that invokes `func` with its first argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function() {
var length = arguments.length;
if (!length) {
return func();
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var index = config.rearg ? 0 : (length - 1);
args[index] = transform(args[index]);
return func.apply(undefined, args);
};
}
/**
* Creates a function that wraps `func` and applys the conversions
* rules by `name`.
*
* @private
* @param {string} name The name of the function to wrap.
* @param {Function} func The function to wrap.
* @returns {Function} Returns the converted function.
*/
function wrap(name, func, placeholder) {
var result,
realName = mapping.aliasToReal[name] || name,
wrapped = func,
wrapper = wrappers[realName];
if (wrapper) {
wrapped = wrapper(func);
}
else if (config.immutable) {
if (mapping.mutate.array[realName]) {
wrapped = wrapImmutable(func, cloneArray);
}
else if (mapping.mutate.object[realName]) {
wrapped = wrapImmutable(func, createCloner(func));
}
else if (mapping.mutate.set[realName]) {
wrapped = wrapImmutable(func, cloneByPath);
}
}
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(otherName) {
if (realName == otherName) {
var data = mapping.methodSpread[realName],
afterRearg = data && data.afterRearg;
result = afterRearg
? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
: castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
result = castCap(realName, result);
result = castCurry(realName, result, aryKey);
return false;
}
});
return !result;
});
result || (result = wrapped);
if (result == func) {
result = forceCurry ? curry(result, 1) : function() {
return func.apply(this, arguments);
};
}
result.convert = createConverter(realName, func);
result.placeholder = func.placeholder = placeholder;
return result;
}
/*--------------------------------------------------------------------------*/
if (!isObj) {
return wrap(name, func, defaultHolder);
}
var _ = func;
// Convert methods by ary cap.
var pairs = [];
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(key) {
var func = _[mapping.remap[key] || key];
if (func) {
pairs.push([key, wrap(key, func, _)]);
}
});
});
// Convert remaining methods.
each(keys(_), function(key) {
var func = _[key];
if (typeof func == 'function') {
var length = pairs.length;
while (length--) {
if (pairs[length][0] == key) {
return;
}
}
func.convert = createConverter(key, func);
pairs.push([key, func]);
}
});
// Assign to `_` leaving `_.prototype` unchanged to allow chaining.
each(pairs, function(pair) {
_[pair[0]] = pair[1];
});
_.convert = convertLib;
_.placeholder = _;
// Assign aliases.
each(keys(_), function(key) {
each(mapping.realToAlias[key] || [], function(alias) {
_[alias] = _[key];
});
});
return _;
}
module.exports = baseConvert;
/***/ }),
/***/ 96114:
/***/ ((__unused_webpack_module, exports) => {
/** Used to map aliases to their real names. */
exports.aliasToReal = {
// Lodash aliases.
'each': 'forEach',
'eachRight': 'forEachRight',
'entries': 'toPairs',
'entriesIn': 'toPairsIn',
'extend': 'assignIn',
'extendAll': 'assignInAll',
'extendAllWith': 'assignInAllWith',
'extendWith': 'assignInWith',
'first': 'head',
// Methods that are curried variants of others.
'conforms': 'conformsTo',
'matches': 'isMatch',
'property': 'get',
// Ramda aliases.
'__': 'placeholder',
'F': 'stubFalse',
'T': 'stubTrue',
'all': 'every',
'allPass': 'overEvery',
'always': 'constant',
'any': 'some',
'anyPass': 'overSome',
'apply': 'spread',
'assoc': 'set',
'assocPath': 'set',
'complement': 'negate',
'compose': 'flowRight',
'contains': 'includes',
'dissoc': 'unset',
'dissocPath': 'unset',
'dropLast': 'dropRight',
'dropLastWhile': 'dropRightWhile',
'equals': 'isEqual',
'identical': 'eq',
'indexBy': 'keyBy',
'init': 'initial',
'invertObj': 'invert',
'juxt': 'over',
'omitAll': 'omit',
'nAry': 'ary',
'path': 'get',
'pathEq': 'matchesProperty',
'pathOr': 'getOr',
'paths': 'at',
'pickAll': 'pick',
'pipe': 'flow',
'pluck': 'map',
'prop': 'get',
'propEq': 'matchesProperty',
'propOr': 'getOr',
'props': 'at',
'symmetricDifference': 'xor',
'symmetricDifferenceBy': 'xorBy',
'symmetricDifferenceWith': 'xorWith',
'takeLast': 'takeRight',
'takeLastWhile': 'takeRightWhile',
'unapply': 'rest',
'unnest': 'flatten',
'useWith': 'overArgs',
'where': 'conformsTo',
'whereEq': 'isMatch',
'zipObj': 'zipObject'
};
/** Used to map ary to method names. */
exports.aryMethod = {
'1': [
'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
'uniqueId', 'words', 'zipAll'
],
'2': [
'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
'zipObjectDeep'
],
'3': [
'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
'xorWith', 'zipWith'
],
'4': [
'fill', 'setWith', 'updateWith'
]
};
/** Used to map ary to rearg configs. */
exports.aryRearg = {
'2': [1, 0],
'3': [2, 0, 1],
'4': [3, 2, 0, 1]
};
/** Used to map method names to their iteratee ary. */
exports.iterateeAry = {
'dropRightWhile': 1,
'dropWhile': 1,
'every': 1,
'filter': 1,
'find': 1,
'findFrom': 1,
'findIndex': 1,
'findIndexFrom': 1,
'findKey': 1,
'findLast': 1,
'findLastFrom': 1,
'findLastIndex': 1,
'findLastIndexFrom': 1,
'findLastKey': 1,
'flatMap': 1,
'flatMapDeep': 1,
'flatMapDepth': 1,
'forEach': 1,
'forEachRight': 1,
'forIn': 1,
'forInRight': 1,
'forOwn': 1,
'forOwnRight': 1,
'map': 1,
'mapKeys': 1,
'mapValues': 1,
'partition': 1,
'reduce': 2,
'reduceRight': 2,
'reject': 1,
'remove': 1,
'some': 1,
'takeRightWhile': 1,
'takeWhile': 1,
'times': 1,
'transform': 2
};
/** Used to map method names to iteratee rearg configs. */
exports.iterateeRearg = {
'mapKeys': [1],
'reduceRight': [1, 0]
};
/** Used to map method names to rearg configs. */
exports.methodRearg = {
'assignInAllWith': [1, 0],
'assignInWith': [1, 2, 0],
'assignAllWith': [1, 0],
'assignWith': [1, 2, 0],
'differenceBy': [1, 2, 0],
'differenceWith': [1, 2, 0],
'getOr': [2, 1, 0],
'intersectionBy': [1, 2, 0],
'intersectionWith': [1, 2, 0],
'isEqualWith': [1, 2, 0],
'isMatchWith': [2, 1, 0],
'mergeAllWith': [1, 0],
'mergeWith': [1, 2, 0],
'padChars': [2, 1, 0],
'padCharsEnd': [2, 1, 0],
'padCharsStart': [2, 1, 0],
'pullAllBy': [2, 1, 0],
'pullAllWith': [2, 1, 0],
'rangeStep': [1, 2, 0],
'rangeStepRight': [1, 2, 0],
'setWith': [3, 1, 2, 0],
'sortedIndexBy': [2, 1, 0],
'sortedLastIndexBy': [2, 1, 0],
'unionBy': [1, 2, 0],
'unionWith': [1, 2, 0],
'updateWith': [3, 1, 2, 0],
'xorBy': [1, 2, 0],
'xorWith': [1, 2, 0],
'zipWith': [1, 2, 0]
};
/** Used to map method names to spread configs. */
exports.methodSpread = {
'assignAll': { 'start': 0 },
'assignAllWith': { 'start': 0 },
'assignInAll': { 'start': 0 },
'assignInAllWith': { 'start': 0 },
'defaultsAll': { 'start': 0 },
'defaultsDeepAll': { 'start': 0 },
'invokeArgs': { 'start': 2 },
'invokeArgsMap': { 'start': 2 },
'mergeAll': { 'start': 0 },
'mergeAllWith': { 'start': 0 },
'partial': { 'start': 1 },
'partialRight': { 'start': 1 },
'without': { 'start': 1 },
'zipAll': { 'start': 0 }
};
/** Used to identify methods which mutate arrays or objects. */
exports.mutate = {
'array': {
'fill': true,
'pull': true,
'pullAll': true,
'pullAllBy': true,
'pullAllWith': true,
'pullAt': true,
'remove': true,
'reverse': true
},
'object': {
'assign': true,
'assignAll': true,
'assignAllWith': true,
'assignIn': true,
'assignInAll': true,
'assignInAllWith': true,
'assignInWith': true,
'assignWith': true,
'defaults': true,
'defaultsAll': true,
'defaultsDeep': true,
'defaultsDeepAll': true,
'merge': true,
'mergeAll': true,
'mergeAllWith': true,
'mergeWith': true,
},
'set': {
'set': true,
'setWith': true,
'unset': true,
'update': true,
'updateWith': true
}
};
/** Used to map real names to their aliases. */
exports.realToAlias = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
object = exports.aliasToReal,
result = {};
for (var key in object) {
var value = object[key];
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}
return result;
}());
/** Used to map method names to other names. */
exports.remap = {
'assignAll': 'assign',
'assignAllWith': 'assignWith',
'assignInAll': 'assignIn',
'assignInAllWith': 'assignInWith',
'curryN': 'curry',
'curryRightN': 'curryRight',
'defaultsAll': 'defaults',
'defaultsDeepAll': 'defaultsDeep',
'findFrom': 'find',
'findIndexFrom': 'findIndex',
'findLastFrom': 'findLast',
'findLastIndexFrom': 'findLastIndex',
'getOr': 'get',
'includesFrom': 'includes',
'indexOfFrom': 'indexOf',
'invokeArgs': 'invoke',
'invokeArgsMap': 'invokeMap',
'lastIndexOfFrom': 'lastIndexOf',
'mergeAll': 'merge',
'mergeAllWith': 'mergeWith',
'padChars': 'pad',
'padCharsEnd': 'padEnd',
'padCharsStart': 'padStart',
'propertyOf': 'get',
'rangeStep': 'range',
'rangeStepRight': 'rangeRight',
'restFrom': 'rest',
'spreadFrom': 'spread',
'trimChars': 'trim',
'trimCharsEnd': 'trimEnd',
'trimCharsStart': 'trimStart',
'zipAll': 'zip'
};
/** Used to track methods that skip fixing their arity. */
exports.skipFixed = {
'castArray': true,
'flow': true,
'flowRight': true,
'iteratee': true,
'mixin': true,
'rearg': true,
'runInContext': true
};
/** Used to track methods that skip rearranging arguments. */
exports.skipRearg = {
'add': true,
'assign': true,
'assignIn': true,
'bind': true,
'bindKey': true,
'concat': true,
'difference': true,
'divide': true,
'eq': true,
'gt': true,
'gte': true,
'isEqual': true,
'lt': true,
'lte': true,
'matchesProperty': true,
'merge': true,
'multiply': true,
'overArgs': true,
'partial': true,
'partialRight': true,
'propertyOf': true,
'random': true,
'range': true,
'rangeRight': true,
'subtract': true,
'zip': true,
'zipObject': true,
'zipObjectDeep': true
};
/***/ }),
/***/ 21817:
/***/ ((module) => {
/**
* The default argument placeholder value for methods.
*
* @type {Object}
*/
module.exports = {};
/***/ }),
/***/ 97063:
/***/ (function(module, exports, __nccwpck_require__) {
/* module decorator */ module = __nccwpck_require__.nmd(module);
/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
(function(){function n(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function t(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function r(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&t(n[r],r,n)!==!1;);return n}function e(n,t){for(var r=null==n?0:n.length;r--&&t(n[r],r,n)!==!1;);return n}function u(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return!1;
return!0}function i(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function o(n,t){return!!(null==n?0:n.length)&&y(n,t,0)>-1}function f(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return!0;return!1}function c(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function a(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function l(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);
return r}function s(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}function p(n){return n.split("")}function _(n){return n.match($t)||[]}function v(n,t,r){var e;return r(n,function(n,r,u){if(t(n,r,u))return e=r,!1}),e}function g(n,t,r,e){for(var u=n.length,i=r+(e?1:-1);e?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function y(n,t,r){return t===t?Z(n,t,r):g(n,b,r)}function d(n,t,r,e){
for(var u=r-1,i=n.length;++u<i;)if(e(n[u],t))return u;return-1}function b(n){return n!==n}function w(n,t){var r=null==n?0:n.length;return r?k(n,t)/r:Cn}function m(n){return function(t){return null==t?X:t[n]}}function x(n){return function(t){return null==n?X:n[t]}}function j(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)}),r}function A(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}function k(n,t){for(var r,e=-1,u=n.length;++e<u;){var i=t(n[e]);i!==X&&(r=r===X?i:r+i);
}return r}function O(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function I(n,t){return c(t,function(t){return[t,n[t]]})}function R(n){return n?n.slice(0,H(n)+1).replace(Lt,""):n}function z(n){return function(t){return n(t)}}function E(n,t){return c(t,function(t){return n[t]})}function S(n,t){return n.has(t)}function W(n,t){for(var r=-1,e=n.length;++r<e&&y(t,n[r],0)>-1;);return r}function L(n,t){for(var r=n.length;r--&&y(t,n[r],0)>-1;);return r}function C(n,t){for(var r=n.length,e=0;r--;)n[r]===t&&++e;
return e}function U(n){return"\\"+Yr[n]}function B(n,t){return null==n?X:n[t]}function T(n){return Nr.test(n)}function $(n){return Pr.test(n)}function D(n){for(var t,r=[];!(t=n.next()).done;)r.push(t.value);return r}function M(n){var t=-1,r=Array(n.size);return n.forEach(function(n,e){r[++t]=[e,n]}),r}function F(n,t){return function(r){return n(t(r))}}function N(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&o!==cn||(n[r]=cn,i[u++]=r)}return i}function P(n){var t=-1,r=Array(n.size);
return n.forEach(function(n){r[++t]=n}),r}function q(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=[n,n]}),r}function Z(n,t,r){for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}function K(n,t,r){for(var e=r+1;e--;)if(n[e]===t)return e;return e}function V(n){return T(n)?J(n):_e(n)}function G(n){return T(n)?Y(n):p(n)}function H(n){for(var t=n.length;t--&&Ct.test(n.charAt(t)););return t}function J(n){for(var t=Mr.lastIndex=0;Mr.test(n);)++t;return t}function Y(n){return n.match(Mr)||[];
}function Q(n){return n.match(Fr)||[]}var X,nn="4.17.21",tn=200,rn="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",en="Expected a function",un="Invalid `variable` option passed into `_.template`",on="__lodash_hash_undefined__",fn=500,cn="__lodash_placeholder__",an=1,ln=2,sn=4,hn=1,pn=2,_n=1,vn=2,gn=4,yn=8,dn=16,bn=32,wn=64,mn=128,xn=256,jn=512,An=30,kn="...",On=800,In=16,Rn=1,zn=2,En=3,Sn=1/0,Wn=9007199254740991,Ln=1.7976931348623157e308,Cn=NaN,Un=4294967295,Bn=Un-1,Tn=Un>>>1,$n=[["ary",mn],["bind",_n],["bindKey",vn],["curry",yn],["curryRight",dn],["flip",jn],["partial",bn],["partialRight",wn],["rearg",xn]],Dn="[object Arguments]",Mn="[object Array]",Fn="[object AsyncFunction]",Nn="[object Boolean]",Pn="[object Date]",qn="[object DOMException]",Zn="[object Error]",Kn="[object Function]",Vn="[object GeneratorFunction]",Gn="[object Map]",Hn="[object Number]",Jn="[object Null]",Yn="[object Object]",Qn="[object Promise]",Xn="[object Proxy]",nt="[object RegExp]",tt="[object Set]",rt="[object String]",et="[object Symbol]",ut="[object Undefined]",it="[object WeakMap]",ot="[object WeakSet]",ft="[object ArrayBuffer]",ct="[object DataView]",at="[object Float32Array]",lt="[object Float64Array]",st="[object Int8Array]",ht="[object Int16Array]",pt="[object Int32Array]",_t="[object Uint8Array]",vt="[object Uint8ClampedArray]",gt="[object Uint16Array]",yt="[object Uint32Array]",dt=/\b__p \+= '';/g,bt=/\b(__p \+=) '' \+/g,wt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,mt=/&(?:amp|lt|gt|quot|#39);/g,xt=/[&<>"']/g,jt=RegExp(mt.source),At=RegExp(xt.source),kt=/<%-([\s\S]+?)%>/g,Ot=/<%([\s\S]+?)%>/g,It=/<%=([\s\S]+?)%>/g,Rt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zt=/^\w*$/,Et=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,St=/[\\^$.*+?()[\]{}|]/g,Wt=RegExp(St.source),Lt=/^\s+/,Ct=/\s/,Ut=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Bt=/\{\n\/\* \[wrapped with (.+)\] \*/,Tt=/,? & /,$t=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Dt=/[()=,{}\[\]\/\s]/,Mt=/\\(\\)?/g,Ft=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Nt=/\w*$/,Pt=/^[-+]0x[0-9a-f]+$/i,qt=/^0b[01]+$/i,Zt=/^\[object .+?Constructor\]$/,Kt=/^0o[0-7]+$/i,Vt=/^(?:0|[1-9]\d*)$/,Gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ht=/($^)/,Jt=/['\n\r\u2028\u2029\\]/g,Yt="\\ud800-\\udfff",Qt="\\u0300-\\u036f",Xt="\\ufe20-\\ufe2f",nr="\\u20d0-\\u20ff",tr=Qt+Xt+nr,rr="\\u2700-\\u27bf",er="a-z\\xdf-\\xf6\\xf8-\\xff",ur="\\xac\\xb1\\xd7\\xf7",ir="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",or="\\u2000-\\u206f",fr=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",cr="A-Z\\xc0-\\xd6\\xd8-\\xde",ar="\\ufe0e\\ufe0f",lr=ur+ir+or+fr,sr="['\u2019]",hr="["+Yt+"]",pr="["+lr+"]",_r="["+tr+"]",vr="\\d+",gr="["+rr+"]",yr="["+er+"]",dr="[^"+Yt+lr+vr+rr+er+cr+"]",br="\\ud83c[\\udffb-\\udfff]",wr="(?:"+_r+"|"+br+")",mr="[^"+Yt+"]",xr="(?:\\ud83c[\\udde6-\\uddff]){2}",jr="[\\ud800-\\udbff][\\udc00-\\udfff]",Ar="["+cr+"]",kr="\\u200d",Or="(?:"+yr+"|"+dr+")",Ir="(?:"+Ar+"|"+dr+")",Rr="(?:"+sr+"(?:d|ll|m|re|s|t|ve))?",zr="(?:"+sr+"(?:D|LL|M|RE|S|T|VE))?",Er=wr+"?",Sr="["+ar+"]?",Wr="(?:"+kr+"(?:"+[mr,xr,jr].join("|")+")"+Sr+Er+")*",Lr="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Cr="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ur=Sr+Er+Wr,Br="(?:"+[gr,xr,jr].join("|")+")"+Ur,Tr="(?:"+[mr+_r+"?",_r,xr,jr,hr].join("|")+")",$r=RegExp(sr,"g"),Dr=RegExp(_r,"g"),Mr=RegExp(br+"(?="+br+")|"+Tr+Ur,"g"),Fr=RegExp([Ar+"?"+yr+"+"+Rr+"(?="+[pr,Ar,"$"].join("|")+")",Ir+"+"+zr+"(?="+[pr,Ar+Or,"$"].join("|")+")",Ar+"?"+Or+"+"+Rr,Ar+"+"+zr,Cr,Lr,vr,Br].join("|"),"g"),Nr=RegExp("["+kr+Yt+tr+ar+"]"),Pr=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,qr=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Zr=-1,Kr={};
Kr[at]=Kr[lt]=Kr[st]=Kr[ht]=Kr[pt]=Kr[_t]=Kr[vt]=Kr[gt]=Kr[yt]=!0,Kr[Dn]=Kr[Mn]=Kr[ft]=Kr[Nn]=Kr[ct]=Kr[Pn]=Kr[Zn]=Kr[Kn]=Kr[Gn]=Kr[Hn]=Kr[Yn]=Kr[nt]=Kr[tt]=Kr[rt]=Kr[it]=!1;var Vr={};Vr[Dn]=Vr[Mn]=Vr[ft]=Vr[ct]=Vr[Nn]=Vr[Pn]=Vr[at]=Vr[lt]=Vr[st]=Vr[ht]=Vr[pt]=Vr[Gn]=Vr[Hn]=Vr[Yn]=Vr[nt]=Vr[tt]=Vr[rt]=Vr[et]=Vr[_t]=Vr[vt]=Vr[gt]=Vr[yt]=!0,Vr[Zn]=Vr[Kn]=Vr[it]=!1;var Gr={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a",
"\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae",
"\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g",
"\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i","\u012f":"i","\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O",
"\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S","\u015e":"S","\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w",
"\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe","\u0149":"'n","\u017f":"s"},Hr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Jr={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},Yr={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Qr=parseFloat,Xr=parseInt,ne="object"==typeof global&&global&&global.Object===Object&&global,te="object"==typeof self&&self&&self.Object===Object&&self,re=ne||te||Function("return this")(),ee= true&&exports&&!exports.nodeType&&exports,ue=ee&&"object"=="object"&&module&&!module.nodeType&&module,ie=ue&&ue.exports===ee,oe=ie&&ne.process,fe=function(){
try{var n=ue&&ue.require&&ue.require("util").types;return n?n:oe&&oe.binding&&oe.binding("util")}catch(n){}}(),ce=fe&&fe.isArrayBuffer,ae=fe&&fe.isDate,le=fe&&fe.isMap,se=fe&&fe.isRegExp,he=fe&&fe.isSet,pe=fe&&fe.isTypedArray,_e=m("length"),ve=x(Gr),ge=x(Hr),ye=x(Jr),de=function p(x){function Z(n){if(cc(n)&&!bh(n)&&!(n instanceof Ct)){if(n instanceof Y)return n;if(bl.call(n,"__wrapped__"))return eo(n)}return new Y(n)}function J(){}function Y(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t,
this.__index__=0,this.__values__=X}function Ct(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Un,this.__views__=[]}function $t(){var n=new Ct(this.__wrapped__);return n.__actions__=Tu(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=Tu(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=Tu(this.__views__),n}function Yt(){if(this.__filtered__){var n=new Ct(this);n.__dir__=-1,
n.__filtered__=!0}else n=this.clone(),n.__dir__*=-1;return n}function Qt(){var n=this.__wrapped__.value(),t=this.__dir__,r=bh(n),e=t<0,u=r?n.length:0,i=Oi(0,u,this.__views__),o=i.start,f=i.end,c=f-o,a=e?f:o-1,l=this.__iteratees__,s=l.length,h=0,p=Hl(c,this.__takeCount__);if(!r||!e&&u==c&&p==c)return wu(n,this.__actions__);var _=[];n:for(;c--&&h<p;){a+=t;for(var v=-1,g=n[a];++v<s;){var y=l[v],d=y.iteratee,b=y.type,w=d(g);if(b==zn)g=w;else if(!w){if(b==Rn)continue n;break n}}_[h++]=g}return _}function Xt(n){
var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function nr(){this.__data__=is?is(null):{},this.size=0}function tr(n){var t=this.has(n)&&delete this.__data__[n];return this.size-=t?1:0,t}function rr(n){var t=this.__data__;if(is){var r=t[n];return r===on?X:r}return bl.call(t,n)?t[n]:X}function er(n){var t=this.__data__;return is?t[n]!==X:bl.call(t,n)}function ur(n,t){var r=this.__data__;return this.size+=this.has(n)?0:1,r[n]=is&&t===X?on:t,this}function ir(n){
var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function or(){this.__data__=[],this.size=0}function fr(n){var t=this.__data__,r=Wr(t,n);return!(r<0)&&(r==t.length-1?t.pop():Ll.call(t,r,1),--this.size,!0)}function cr(n){var t=this.__data__,r=Wr(t,n);return r<0?X:t[r][1]}function ar(n){return Wr(this.__data__,n)>-1}function lr(n,t){var r=this.__data__,e=Wr(r,n);return e<0?(++this.size,r.push([n,t])):r[e][1]=t,this}function sr(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){
var e=n[t];this.set(e[0],e[1])}}function hr(){this.size=0,this.__data__={hash:new Xt,map:new(ts||ir),string:new Xt}}function pr(n){var t=xi(this,n).delete(n);return this.size-=t?1:0,t}function _r(n){return xi(this,n).get(n)}function vr(n){return xi(this,n).has(n)}function gr(n,t){var r=xi(this,n),e=r.size;return r.set(n,t),this.size+=r.size==e?0:1,this}function yr(n){var t=-1,r=null==n?0:n.length;for(this.__data__=new sr;++t<r;)this.add(n[t])}function dr(n){return this.__data__.set(n,on),this}function br(n){
return this.__data__.has(n)}function wr(n){this.size=(this.__data__=new ir(n)).size}function mr(){this.__data__=new ir,this.size=0}function xr(n){var t=this.__data__,r=t.delete(n);return this.size=t.size,r}function jr(n){return this.__data__.get(n)}function Ar(n){return this.__data__.has(n)}function kr(n,t){var r=this.__data__;if(r instanceof ir){var e=r.__data__;if(!ts||e.length<tn-1)return e.push([n,t]),this.size=++r.size,this;r=this.__data__=new sr(e)}return r.set(n,t),this.size=r.size,this}function Or(n,t){
var r=bh(n),e=!r&&dh(n),u=!r&&!e&&mh(n),i=!r&&!e&&!u&&Oh(n),o=r||e||u||i,f=o?O(n.length,hl):[],c=f.length;for(var a in n)!t&&!bl.call(n,a)||o&&("length"==a||u&&("offset"==a||"parent"==a)||i&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||Ci(a,c))||f.push(a);return f}function Ir(n){var t=n.length;return t?n[tu(0,t-1)]:X}function Rr(n,t){return Xi(Tu(n),Mr(t,0,n.length))}function zr(n){return Xi(Tu(n))}function Er(n,t,r){(r===X||Gf(n[t],r))&&(r!==X||t in n)||Br(n,t,r)}function Sr(n,t,r){var e=n[t];
bl.call(n,t)&&Gf(e,r)&&(r!==X||t in n)||Br(n,t,r)}function Wr(n,t){for(var r=n.length;r--;)if(Gf(n[r][0],t))return r;return-1}function Lr(n,t,r,e){return ys(n,function(n,u,i){t(e,n,r(n),i)}),e}function Cr(n,t){return n&&$u(t,Pc(t),n)}function Ur(n,t){return n&&$u(t,qc(t),n)}function Br(n,t,r){"__proto__"==t&&Tl?Tl(n,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):n[t]=r}function Tr(n,t){for(var r=-1,e=t.length,u=il(e),i=null==n;++r<e;)u[r]=i?X:Mc(n,t[r]);return u}function Mr(n,t,r){return n===n&&(r!==X&&(n=n<=r?n:r),
t!==X&&(n=n>=t?n:t)),n}function Fr(n,t,e,u,i,o){var f,c=t&an,a=t&ln,l=t&sn;if(e&&(f=i?e(n,u,i,o):e(n)),f!==X)return f;if(!fc(n))return n;var s=bh(n);if(s){if(f=zi(n),!c)return Tu(n,f)}else{var h=zs(n),p=h==Kn||h==Vn;if(mh(n))return Iu(n,c);if(h==Yn||h==Dn||p&&!i){if(f=a||p?{}:Ei(n),!c)return a?Mu(n,Ur(f,n)):Du(n,Cr(f,n))}else{if(!Vr[h])return i?n:{};f=Si(n,h,c)}}o||(o=new wr);var _=o.get(n);if(_)return _;o.set(n,f),kh(n)?n.forEach(function(r){f.add(Fr(r,t,e,r,n,o))}):jh(n)&&n.forEach(function(r,u){
f.set(u,Fr(r,t,e,u,n,o))});var v=l?a?di:yi:a?qc:Pc,g=s?X:v(n);return r(g||n,function(r,u){g&&(u=r,r=n[u]),Sr(f,u,Fr(r,t,e,u,n,o))}),f}function Nr(n){var t=Pc(n);return function(r){return Pr(r,n,t)}}function Pr(n,t,r){var e=r.length;if(null==n)return!e;for(n=ll(n);e--;){var u=r[e],i=t[u],o=n[u];if(o===X&&!(u in n)||!i(o))return!1}return!0}function Gr(n,t,r){if("function"!=typeof n)throw new pl(en);return Ws(function(){n.apply(X,r)},t)}function Hr(n,t,r,e){var u=-1,i=o,a=!0,l=n.length,s=[],h=t.length;
if(!l)return s;r&&(t=c(t,z(r))),e?(i=f,a=!1):t.length>=tn&&(i=S,a=!1,t=new yr(t));n:for(;++u<l;){var p=n[u],_=null==r?p:r(p);if(p=e||0!==p?p:0,a&&_===_){for(var v=h;v--;)if(t[v]===_)continue n;s.push(p)}else i(t,_,e)||s.push(p)}return s}function Jr(n,t){var r=!0;return ys(n,function(n,e,u){return r=!!t(n,e,u)}),r}function Yr(n,t,r){for(var e=-1,u=n.length;++e<u;){var i=n[e],o=t(i);if(null!=o&&(f===X?o===o&&!bc(o):r(o,f)))var f=o,c=i}return c}function ne(n,t,r,e){var u=n.length;for(r=kc(r),r<0&&(r=-r>u?0:u+r),
e=e===X||e>u?u:kc(e),e<0&&(e+=u),e=r>e?0:Oc(e);r<e;)n[r++]=t;return n}function te(n,t){var r=[];return ys(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function ee(n,t,r,e,u){var i=-1,o=n.length;for(r||(r=Li),u||(u=[]);++i<o;){var f=n[i];t>0&&r(f)?t>1?ee(f,t-1,r,e,u):a(u,f):e||(u[u.length]=f)}return u}function ue(n,t){return n&&bs(n,t,Pc)}function oe(n,t){return n&&ws(n,t,Pc)}function fe(n,t){return i(t,function(t){return uc(n[t])})}function _e(n,t){t=ku(t,n);for(var r=0,e=t.length;null!=n&&r<e;)n=n[no(t[r++])];
return r&&r==e?n:X}function de(n,t,r){var e=t(n);return bh(n)?e:a(e,r(n))}function we(n){return null==n?n===X?ut:Jn:Bl&&Bl in ll(n)?ki(n):Ki(n)}function me(n,t){return n>t}function xe(n,t){return null!=n&&bl.call(n,t)}function je(n,t){return null!=n&&t in ll(n)}function Ae(n,t,r){return n>=Hl(t,r)&&n<Gl(t,r)}function ke(n,t,r){for(var e=r?f:o,u=n[0].length,i=n.length,a=i,l=il(i),s=1/0,h=[];a--;){var p=n[a];a&&t&&(p=c(p,z(t))),s=Hl(p.length,s),l[a]=!r&&(t||u>=120&&p.length>=120)?new yr(a&&p):X}p=n[0];
var _=-1,v=l[0];n:for(;++_<u&&h.length<s;){var g=p[_],y=t?t(g):g;if(g=r||0!==g?g:0,!(v?S(v,y):e(h,y,r))){for(a=i;--a;){var d=l[a];if(!(d?S(d,y):e(n[a],y,r)))continue n}v&&v.push(y),h.push(g)}}return h}function Oe(n,t,r,e){return ue(n,function(n,u,i){t(e,r(n),u,i)}),e}function Ie(t,r,e){r=ku(r,t),t=Gi(t,r);var u=null==t?t:t[no(jo(r))];return null==u?X:n(u,t,e)}function Re(n){return cc(n)&&we(n)==Dn}function ze(n){return cc(n)&&we(n)==ft}function Ee(n){return cc(n)&&we(n)==Pn}function Se(n,t,r,e,u){
return n===t||(null==n||null==t||!cc(n)&&!cc(t)?n!==n&&t!==t:We(n,t,r,e,Se,u))}function We(n,t,r,e,u,i){var o=bh(n),f=bh(t),c=o?Mn:zs(n),a=f?Mn:zs(t);c=c==Dn?Yn:c,a=a==Dn?Yn:a;var l=c==Yn,s=a==Yn,h=c==a;if(h&&mh(n)){if(!mh(t))return!1;o=!0,l=!1}if(h&&!l)return i||(i=new wr),o||Oh(n)?pi(n,t,r,e,u,i):_i(n,t,c,r,e,u,i);if(!(r&hn)){var p=l&&bl.call(n,"__wrapped__"),_=s&&bl.call(t,"__wrapped__");if(p||_){var v=p?n.value():n,g=_?t.value():t;return i||(i=new wr),u(v,g,r,e,i)}}return!!h&&(i||(i=new wr),vi(n,t,r,e,u,i));
}function Le(n){return cc(n)&&zs(n)==Gn}function Ce(n,t,r,e){var u=r.length,i=u,o=!e;if(null==n)return!i;for(n=ll(n);u--;){var f=r[u];if(o&&f[2]?f[1]!==n[f[0]]:!(f[0]in n))return!1}for(;++u<i;){f=r[u];var c=f[0],a=n[c],l=f[1];if(o&&f[2]){if(a===X&&!(c in n))return!1}else{var s=new wr;if(e)var h=e(a,l,c,n,t,s);if(!(h===X?Se(l,a,hn|pn,e,s):h))return!1}}return!0}function Ue(n){return!(!fc(n)||Di(n))&&(uc(n)?kl:Zt).test(to(n))}function Be(n){return cc(n)&&we(n)==nt}function Te(n){return cc(n)&&zs(n)==tt;
}function $e(n){return cc(n)&&oc(n.length)&&!!Kr[we(n)]}function De(n){return"function"==typeof n?n:null==n?La:"object"==typeof n?bh(n)?Ze(n[0],n[1]):qe(n):Fa(n)}function Me(n){if(!Mi(n))return Vl(n);var t=[];for(var r in ll(n))bl.call(n,r)&&"constructor"!=r&&t.push(r);return t}function Fe(n){if(!fc(n))return Zi(n);var t=Mi(n),r=[];for(var e in n)("constructor"!=e||!t&&bl.call(n,e))&&r.push(e);return r}function Ne(n,t){return n<t}function Pe(n,t){var r=-1,e=Hf(n)?il(n.length):[];return ys(n,function(n,u,i){
e[++r]=t(n,u,i)}),e}function qe(n){var t=ji(n);return 1==t.length&&t[0][2]?Ni(t[0][0],t[0][1]):function(r){return r===n||Ce(r,n,t)}}function Ze(n,t){return Bi(n)&&Fi(t)?Ni(no(n),t):function(r){var e=Mc(r,n);return e===X&&e===t?Nc(r,n):Se(t,e,hn|pn)}}function Ke(n,t,r,e,u){n!==t&&bs(t,function(i,o){if(u||(u=new wr),fc(i))Ve(n,t,o,r,Ke,e,u);else{var f=e?e(Ji(n,o),i,o+"",n,t,u):X;f===X&&(f=i),Er(n,o,f)}},qc)}function Ve(n,t,r,e,u,i,o){var f=Ji(n,r),c=Ji(t,r),a=o.get(c);if(a)return Er(n,r,a),X;var l=i?i(f,c,r+"",n,t,o):X,s=l===X;
if(s){var h=bh(c),p=!h&&mh(c),_=!h&&!p&&Oh(c);l=c,h||p||_?bh(f)?l=f:Jf(f)?l=Tu(f):p?(s=!1,l=Iu(c,!0)):_?(s=!1,l=Wu(c,!0)):l=[]:gc(c)||dh(c)?(l=f,dh(f)?l=Rc(f):fc(f)&&!uc(f)||(l=Ei(c))):s=!1}s&&(o.set(c,l),u(l,c,e,i,o),o.delete(c)),Er(n,r,l)}function Ge(n,t){var r=n.length;if(r)return t+=t<0?r:0,Ci(t,r)?n[t]:X}function He(n,t,r){t=t.length?c(t,function(n){return bh(n)?function(t){return _e(t,1===n.length?n[0]:n)}:n}):[La];var e=-1;return t=c(t,z(mi())),A(Pe(n,function(n,r,u){return{criteria:c(t,function(t){
return t(n)}),index:++e,value:n}}),function(n,t){return Cu(n,t,r)})}function Je(n,t){return Ye(n,t,function(t,r){return Nc(n,r)})}function Ye(n,t,r){for(var e=-1,u=t.length,i={};++e<u;){var o=t[e],f=_e(n,o);r(f,o)&&fu(i,ku(o,n),f)}return i}function Qe(n){return function(t){return _e(t,n)}}function Xe(n,t,r,e){var u=e?d:y,i=-1,o=t.length,f=n;for(n===t&&(t=Tu(t)),r&&(f=c(n,z(r)));++i<o;)for(var a=0,l=t[i],s=r?r(l):l;(a=u(f,s,a,e))>-1;)f!==n&&Ll.call(f,a,1),Ll.call(n,a,1);return n}function nu(n,t){for(var r=n?t.length:0,e=r-1;r--;){
var u=t[r];if(r==e||u!==i){var i=u;Ci(u)?Ll.call(n,u,1):yu(n,u)}}return n}function tu(n,t){return n+Nl(Ql()*(t-n+1))}function ru(n,t,r,e){for(var u=-1,i=Gl(Fl((t-n)/(r||1)),0),o=il(i);i--;)o[e?i:++u]=n,n+=r;return o}function eu(n,t){var r="";if(!n||t<1||t>Wn)return r;do t%2&&(r+=n),t=Nl(t/2),t&&(n+=n);while(t);return r}function uu(n,t){return Ls(Vi(n,t,La),n+"")}function iu(n){return Ir(ra(n))}function ou(n,t){var r=ra(n);return Xi(r,Mr(t,0,r.length))}function fu(n,t,r,e){if(!fc(n))return n;t=ku(t,n);
for(var u=-1,i=t.length,o=i-1,f=n;null!=f&&++u<i;){var c=no(t[u]),a=r;if("__proto__"===c||"constructor"===c||"prototype"===c)return n;if(u!=o){var l=f[c];a=e?e(l,c,f):X,a===X&&(a=fc(l)?l:Ci(t[u+1])?[]:{})}Sr(f,c,a),f=f[c]}return n}function cu(n){return Xi(ra(n))}function au(n,t,r){var e=-1,u=n.length;t<0&&(t=-t>u?0:u+t),r=r>u?u:r,r<0&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=il(u);++e<u;)i[e]=n[e+t];return i}function lu(n,t){var r;return ys(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function su(n,t,r){
var e=0,u=null==n?e:n.length;if("number"==typeof t&&t===t&&u<=Tn){for(;e<u;){var i=e+u>>>1,o=n[i];null!==o&&!bc(o)&&(r?o<=t:o<t)?e=i+1:u=i}return u}return hu(n,t,La,r)}function hu(n,t,r,e){var u=0,i=null==n?0:n.length;if(0===i)return 0;t=r(t);for(var o=t!==t,f=null===t,c=bc(t),a=t===X;u<i;){var l=Nl((u+i)/2),s=r(n[l]),h=s!==X,p=null===s,_=s===s,v=bc(s);if(o)var g=e||_;else g=a?_&&(e||h):f?_&&h&&(e||!p):c?_&&h&&!p&&(e||!v):!p&&!v&&(e?s<=t:s<t);g?u=l+1:i=l}return Hl(i,Bn)}function pu(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){
var o=n[r],f=t?t(o):o;if(!r||!Gf(f,c)){var c=f;i[u++]=0===o?0:o}}return i}function _u(n){return"number"==typeof n?n:bc(n)?Cn:+n}function vu(n){if("string"==typeof n)return n;if(bh(n))return c(n,vu)+"";if(bc(n))return vs?vs.call(n):"";var t=n+"";return"0"==t&&1/n==-Sn?"-0":t}function gu(n,t,r){var e=-1,u=o,i=n.length,c=!0,a=[],l=a;if(r)c=!1,u=f;else if(i>=tn){var s=t?null:ks(n);if(s)return P(s);c=!1,u=S,l=new yr}else l=t?[]:a;n:for(;++e<i;){var h=n[e],p=t?t(h):h;if(h=r||0!==h?h:0,c&&p===p){for(var _=l.length;_--;)if(l[_]===p)continue n;
t&&l.push(p),a.push(h)}else u(l,p,r)||(l!==a&&l.push(p),a.push(h))}return a}function yu(n,t){return t=ku(t,n),n=Gi(n,t),null==n||delete n[no(jo(t))]}function du(n,t,r,e){return fu(n,t,r(_e(n,t)),e)}function bu(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?au(n,e?0:i,e?i+1:u):au(n,e?i+1:0,e?u:i)}function wu(n,t){var r=n;return r instanceof Ct&&(r=r.value()),l(t,function(n,t){return t.func.apply(t.thisArg,a([n],t.args))},r)}function mu(n,t,r){var e=n.length;if(e<2)return e?gu(n[0]):[];
for(var u=-1,i=il(e);++u<e;)for(var o=n[u],f=-1;++f<e;)f!=u&&(i[u]=Hr(i[u]||o,n[f],t,r));return gu(ee(i,1),t,r)}function xu(n,t,r){for(var e=-1,u=n.length,i=t.length,o={};++e<u;){r(o,n[e],e<i?t[e]:X)}return o}function ju(n){return Jf(n)?n:[]}function Au(n){return"function"==typeof n?n:La}function ku(n,t){return bh(n)?n:Bi(n,t)?[n]:Cs(Ec(n))}function Ou(n,t,r){var e=n.length;return r=r===X?e:r,!t&&r>=e?n:au(n,t,r)}function Iu(n,t){if(t)return n.slice();var r=n.length,e=zl?zl(r):new n.constructor(r);
return n.copy(e),e}function Ru(n){var t=new n.constructor(n.byteLength);return new Rl(t).set(new Rl(n)),t}function zu(n,t){return new n.constructor(t?Ru(n.buffer):n.buffer,n.byteOffset,n.byteLength)}function Eu(n){var t=new n.constructor(n.source,Nt.exec(n));return t.lastIndex=n.lastIndex,t}function Su(n){return _s?ll(_s.call(n)):{}}function Wu(n,t){return new n.constructor(t?Ru(n.buffer):n.buffer,n.byteOffset,n.length)}function Lu(n,t){if(n!==t){var r=n!==X,e=null===n,u=n===n,i=bc(n),o=t!==X,f=null===t,c=t===t,a=bc(t);
if(!f&&!a&&!i&&n>t||i&&o&&c&&!f&&!a||e&&o&&c||!r&&c||!u)return 1;if(!e&&!i&&!a&&n<t||a&&r&&u&&!e&&!i||f&&r&&u||!o&&u||!c)return-1}return 0}function Cu(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,o=u.length,f=r.length;++e<o;){var c=Lu(u[e],i[e]);if(c){if(e>=f)return c;return c*("desc"==r[e]?-1:1)}}return n.index-t.index}function Uu(n,t,r,e){for(var u=-1,i=n.length,o=r.length,f=-1,c=t.length,a=Gl(i-o,0),l=il(c+a),s=!e;++f<c;)l[f]=t[f];for(;++u<o;)(s||u<i)&&(l[r[u]]=n[u]);for(;a--;)l[f++]=n[u++];return l;
}function Bu(n,t,r,e){for(var u=-1,i=n.length,o=-1,f=r.length,c=-1,a=t.length,l=Gl(i-f,0),s=il(l+a),h=!e;++u<l;)s[u]=n[u];for(var p=u;++c<a;)s[p+c]=t[c];for(;++o<f;)(h||u<i)&&(s[p+r[o]]=n[u++]);return s}function Tu(n,t){var r=-1,e=n.length;for(t||(t=il(e));++r<e;)t[r]=n[r];return t}function $u(n,t,r,e){var u=!r;r||(r={});for(var i=-1,o=t.length;++i<o;){var f=t[i],c=e?e(r[f],n[f],f,r,n):X;c===X&&(c=n[f]),u?Br(r,f,c):Sr(r,f,c)}return r}function Du(n,t){return $u(n,Is(n),t)}function Mu(n,t){return $u(n,Rs(n),t);
}function Fu(n,r){return function(e,u){var i=bh(e)?t:Lr,o=r?r():{};return i(e,n,mi(u,2),o)}}function Nu(n){return uu(function(t,r){var e=-1,u=r.length,i=u>1?r[u-1]:X,o=u>2?r[2]:X;for(i=n.length>3&&"function"==typeof i?(u--,i):X,o&&Ui(r[0],r[1],o)&&(i=u<3?X:i,u=1),t=ll(t);++e<u;){var f=r[e];f&&n(t,f,e,i)}return t})}function Pu(n,t){return function(r,e){if(null==r)return r;if(!Hf(r))return n(r,e);for(var u=r.length,i=t?u:-1,o=ll(r);(t?i--:++i<u)&&e(o[i],i,o)!==!1;);return r}}function qu(n){return function(t,r,e){
for(var u=-1,i=ll(t),o=e(t),f=o.length;f--;){var c=o[n?f:++u];if(r(i[c],c,i)===!1)break}return t}}function Zu(n,t,r){function e(){return(this&&this!==re&&this instanceof e?i:n).apply(u?r:this,arguments)}var u=t&_n,i=Gu(n);return e}function Ku(n){return function(t){t=Ec(t);var r=T(t)?G(t):X,e=r?r[0]:t.charAt(0),u=r?Ou(r,1).join(""):t.slice(1);return e[n]()+u}}function Vu(n){return function(t){return l(Ra(ca(t).replace($r,"")),n,"")}}function Gu(n){return function(){var t=arguments;switch(t.length){
case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5:return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=gs(n.prototype),e=n.apply(r,t);return fc(e)?e:r}}function Hu(t,r,e){function u(){for(var o=arguments.length,f=il(o),c=o,a=wi(u);c--;)f[c]=arguments[c];var l=o<3&&f[0]!==a&&f[o-1]!==a?[]:N(f,a);
return o-=l.length,o<e?oi(t,r,Qu,u.placeholder,X,f,l,X,X,e-o):n(this&&this!==re&&this instanceof u?i:t,this,f)}var i=Gu(t);return u}function Ju(n){return function(t,r,e){var u=ll(t);if(!Hf(t)){var i=mi(r,3);t=Pc(t),r=function(n){return i(u[n],n,u)}}var o=n(t,r,e);return o>-1?u[i?t[o]:o]:X}}function Yu(n){return gi(function(t){var r=t.length,e=r,u=Y.prototype.thru;for(n&&t.reverse();e--;){var i=t[e];if("function"!=typeof i)throw new pl(en);if(u&&!o&&"wrapper"==bi(i))var o=new Y([],!0)}for(e=o?e:r;++e<r;){
i=t[e];var f=bi(i),c="wrapper"==f?Os(i):X;o=c&&$i(c[0])&&c[1]==(mn|yn|bn|xn)&&!c[4].length&&1==c[9]?o[bi(c[0])].apply(o,c[3]):1==i.length&&$i(i)?o[f]():o.thru(i)}return function(){var n=arguments,e=n[0];if(o&&1==n.length&&bh(e))return o.plant(e).value();for(var u=0,i=r?t[u].apply(this,n):e;++u<r;)i=t[u].call(this,i);return i}})}function Qu(n,t,r,e,u,i,o,f,c,a){function l(){for(var y=arguments.length,d=il(y),b=y;b--;)d[b]=arguments[b];if(_)var w=wi(l),m=C(d,w);if(e&&(d=Uu(d,e,u,_)),i&&(d=Bu(d,i,o,_)),
y-=m,_&&y<a){return oi(n,t,Qu,l.placeholder,r,d,N(d,w),f,c,a-y)}var x=h?r:this,j=p?x[n]:n;return y=d.length,f?d=Hi(d,f):v&&y>1&&d.reverse(),s&&c<y&&(d.length=c),this&&this!==re&&this instanceof l&&(j=g||Gu(j)),j.apply(x,d)}var s=t&mn,h=t&_n,p=t&vn,_=t&(yn|dn),v=t&jn,g=p?X:Gu(n);return l}function Xu(n,t){return function(r,e){return Oe(r,n,t(e),{})}}function ni(n,t){return function(r,e){var u;if(r===X&&e===X)return t;if(r!==X&&(u=r),e!==X){if(u===X)return e;"string"==typeof r||"string"==typeof e?(r=vu(r),
e=vu(e)):(r=_u(r),e=_u(e)),u=n(r,e)}return u}}function ti(t){return gi(function(r){return r=c(r,z(mi())),uu(function(e){var u=this;return t(r,function(t){return n(t,u,e)})})})}function ri(n,t){t=t===X?" ":vu(t);var r=t.length;if(r<2)return r?eu(t,n):t;var e=eu(t,Fl(n/V(t)));return T(t)?Ou(G(e),0,n).join(""):e.slice(0,n)}function ei(t,r,e,u){function i(){for(var r=-1,c=arguments.length,a=-1,l=u.length,s=il(l+c),h=this&&this!==re&&this instanceof i?f:t;++a<l;)s[a]=u[a];for(;c--;)s[a++]=arguments[++r];
return n(h,o?e:this,s)}var o=r&_n,f=Gu(t);return i}function ui(n){return function(t,r,e){return e&&"number"!=typeof e&&Ui(t,r,e)&&(r=e=X),t=Ac(t),r===X?(r=t,t=0):r=Ac(r),e=e===X?t<r?1:-1:Ac(e),ru(t,r,e,n)}}function ii(n){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=Ic(t),r=Ic(r)),n(t,r)}}function oi(n,t,r,e,u,i,o,f,c,a){var l=t&yn,s=l?o:X,h=l?X:o,p=l?i:X,_=l?X:i;t|=l?bn:wn,t&=~(l?wn:bn),t&gn||(t&=~(_n|vn));var v=[n,t,u,p,s,_,h,f,c,a],g=r.apply(X,v);return $i(n)&&Ss(g,v),g.placeholder=e,
Yi(g,n,t)}function fi(n){var t=al[n];return function(n,r){if(n=Ic(n),r=null==r?0:Hl(kc(r),292),r&&Zl(n)){var e=(Ec(n)+"e").split("e");return e=(Ec(t(e[0]+"e"+(+e[1]+r)))+"e").split("e"),+(e[0]+"e"+(+e[1]-r))}return t(n)}}function ci(n){return function(t){var r=zs(t);return r==Gn?M(t):r==tt?q(t):I(t,n(t))}}function ai(n,t,r,e,u,i,o,f){var c=t&vn;if(!c&&"function"!=typeof n)throw new pl(en);var a=e?e.length:0;if(a||(t&=~(bn|wn),e=u=X),o=o===X?o:Gl(kc(o),0),f=f===X?f:kc(f),a-=u?u.length:0,t&wn){var l=e,s=u;
e=u=X}var h=c?X:Os(n),p=[n,t,r,e,u,l,s,i,o,f];if(h&&qi(p,h),n=p[0],t=p[1],r=p[2],e=p[3],u=p[4],f=p[9]=p[9]===X?c?0:n.length:Gl(p[9]-a,0),!f&&t&(yn|dn)&&(t&=~(yn|dn)),t&&t!=_n)_=t==yn||t==dn?Hu(n,t,f):t!=bn&&t!=(_n|bn)||u.length?Qu.apply(X,p):ei(n,t,r,e);else var _=Zu(n,t,r);return Yi((h?ms:Ss)(_,p),n,t)}function li(n,t,r,e){return n===X||Gf(n,gl[r])&&!bl.call(e,r)?t:n}function si(n,t,r,e,u,i){return fc(n)&&fc(t)&&(i.set(t,n),Ke(n,t,X,si,i),i.delete(t)),n}function hi(n){return gc(n)?X:n}function pi(n,t,r,e,u,i){
var o=r&hn,f=n.length,c=t.length;if(f!=c&&!(o&&c>f))return!1;var a=i.get(n),l=i.get(t);if(a&&l)return a==t&&l==n;var s=-1,p=!0,_=r&pn?new yr:X;for(i.set(n,t),i.set(t,n);++s<f;){var v=n[s],g=t[s];if(e)var y=o?e(g,v,s,t,n,i):e(v,g,s,n,t,i);if(y!==X){if(y)continue;p=!1;break}if(_){if(!h(t,function(n,t){if(!S(_,t)&&(v===n||u(v,n,r,e,i)))return _.push(t)})){p=!1;break}}else if(v!==g&&!u(v,g,r,e,i)){p=!1;break}}return i.delete(n),i.delete(t),p}function _i(n,t,r,e,u,i,o){switch(r){case ct:if(n.byteLength!=t.byteLength||n.byteOffset!=t.byteOffset)return!1;
n=n.buffer,t=t.buffer;case ft:return!(n.byteLength!=t.byteLength||!i(new Rl(n),new Rl(t)));case Nn:case Pn:case Hn:return Gf(+n,+t);case Zn:return n.name==t.name&&n.message==t.message;case nt:case rt:return n==t+"";case Gn:var f=M;case tt:var c=e&hn;if(f||(f=P),n.size!=t.size&&!c)return!1;var a=o.get(n);if(a)return a==t;e|=pn,o.set(n,t);var l=pi(f(n),f(t),e,u,i,o);return o.delete(n),l;case et:if(_s)return _s.call(n)==_s.call(t)}return!1}function vi(n,t,r,e,u,i){var o=r&hn,f=yi(n),c=f.length;if(c!=yi(t).length&&!o)return!1;
for(var a=c;a--;){var l=f[a];if(!(o?l in t:bl.call(t,l)))return!1}var s=i.get(n),h=i.get(t);if(s&&h)return s==t&&h==n;var p=!0;i.set(n,t),i.set(t,n);for(var _=o;++a<c;){l=f[a];var v=n[l],g=t[l];if(e)var y=o?e(g,v,l,t,n,i):e(v,g,l,n,t,i);if(!(y===X?v===g||u(v,g,r,e,i):y)){p=!1;break}_||(_="constructor"==l)}if(p&&!_){var d=n.constructor,b=t.constructor;d!=b&&"constructor"in n&&"constructor"in t&&!("function"==typeof d&&d instanceof d&&"function"==typeof b&&b instanceof b)&&(p=!1)}return i.delete(n),
i.delete(t),p}function gi(n){return Ls(Vi(n,X,_o),n+"")}function yi(n){return de(n,Pc,Is)}function di(n){return de(n,qc,Rs)}function bi(n){for(var t=n.name+"",r=fs[t],e=bl.call(fs,t)?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}function wi(n){return(bl.call(Z,"placeholder")?Z:n).placeholder}function mi(){var n=Z.iteratee||Ca;return n=n===Ca?De:n,arguments.length?n(arguments[0],arguments[1]):n}function xi(n,t){var r=n.__data__;return Ti(t)?r["string"==typeof t?"string":"hash"]:r.map;
}function ji(n){for(var t=Pc(n),r=t.length;r--;){var e=t[r],u=n[e];t[r]=[e,u,Fi(u)]}return t}function Ai(n,t){var r=B(n,t);return Ue(r)?r:X}function ki(n){var t=bl.call(n,Bl),r=n[Bl];try{n[Bl]=X;var e=!0}catch(n){}var u=xl.call(n);return e&&(t?n[Bl]=r:delete n[Bl]),u}function Oi(n,t,r){for(var e=-1,u=r.length;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=Hl(t,n+o);break;case"takeRight":n=Gl(n,t-o)}}return{start:n,end:t}}function Ii(n){var t=n.match(Bt);
return t?t[1].split(Tt):[]}function Ri(n,t,r){t=ku(t,n);for(var e=-1,u=t.length,i=!1;++e<u;){var o=no(t[e]);if(!(i=null!=n&&r(n,o)))break;n=n[o]}return i||++e!=u?i:(u=null==n?0:n.length,!!u&&oc(u)&&Ci(o,u)&&(bh(n)||dh(n)))}function zi(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&bl.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function Ei(n){return"function"!=typeof n.constructor||Mi(n)?{}:gs(El(n))}function Si(n,t,r){var e=n.constructor;switch(t){case ft:return Ru(n);
case Nn:case Pn:return new e(+n);case ct:return zu(n,r);case at:case lt:case st:case ht:case pt:case _t:case vt:case gt:case yt:return Wu(n,r);case Gn:return new e;case Hn:case rt:return new e(n);case nt:return Eu(n);case tt:return new e;case et:return Su(n)}}function Wi(n,t){var r=t.length;if(!r)return n;var e=r-1;return t[e]=(r>1?"& ":"")+t[e],t=t.join(r>2?", ":" "),n.replace(Ut,"{\n/* [wrapped with "+t+"] */\n")}function Li(n){return bh(n)||dh(n)||!!(Cl&&n&&n[Cl])}function Ci(n,t){var r=typeof n;
return t=null==t?Wn:t,!!t&&("number"==r||"symbol"!=r&&Vt.test(n))&&n>-1&&n%1==0&&n<t}function Ui(n,t,r){if(!fc(r))return!1;var e=typeof t;return!!("number"==e?Hf(r)&&Ci(t,r.length):"string"==e&&t in r)&&Gf(r[t],n)}function Bi(n,t){if(bh(n))return!1;var r=typeof n;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=n&&!bc(n))||(zt.test(n)||!Rt.test(n)||null!=t&&n in ll(t))}function Ti(n){var t=typeof n;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==n:null===n}function $i(n){
var t=bi(n),r=Z[t];if("function"!=typeof r||!(t in Ct.prototype))return!1;if(n===r)return!0;var e=Os(r);return!!e&&n===e[0]}function Di(n){return!!ml&&ml in n}function Mi(n){var t=n&&n.constructor;return n===("function"==typeof t&&t.prototype||gl)}function Fi(n){return n===n&&!fc(n)}function Ni(n,t){return function(r){return null!=r&&(r[n]===t&&(t!==X||n in ll(r)))}}function Pi(n){var t=Cf(n,function(n){return r.size===fn&&r.clear(),n}),r=t.cache;return t}function qi(n,t){var r=n[1],e=t[1],u=r|e,i=u<(_n|vn|mn),o=e==mn&&r==yn||e==mn&&r==xn&&n[7].length<=t[8]||e==(mn|xn)&&t[7].length<=t[8]&&r==yn;
if(!i&&!o)return n;e&_n&&(n[2]=t[2],u|=r&_n?0:gn);var f=t[3];if(f){var c=n[3];n[3]=c?Uu(c,f,t[4]):f,n[4]=c?N(n[3],cn):t[4]}return f=t[5],f&&(c=n[5],n[5]=c?Bu(c,f,t[6]):f,n[6]=c?N(n[5],cn):t[6]),f=t[7],f&&(n[7]=f),e&mn&&(n[8]=null==n[8]?t[8]:Hl(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u,n}function Zi(n){var t=[];if(null!=n)for(var r in ll(n))t.push(r);return t}function Ki(n){return xl.call(n)}function Vi(t,r,e){return r=Gl(r===X?t.length-1:r,0),function(){for(var u=arguments,i=-1,o=Gl(u.length-r,0),f=il(o);++i<o;)f[i]=u[r+i];
i=-1;for(var c=il(r+1);++i<r;)c[i]=u[i];return c[r]=e(f),n(t,this,c)}}function Gi(n,t){return t.length<2?n:_e(n,au(t,0,-1))}function Hi(n,t){for(var r=n.length,e=Hl(t.length,r),u=Tu(n);e--;){var i=t[e];n[e]=Ci(i,r)?u[i]:X}return n}function Ji(n,t){if(("constructor"!==t||"function"!=typeof n[t])&&"__proto__"!=t)return n[t]}function Yi(n,t,r){var e=t+"";return Ls(n,Wi(e,ro(Ii(e),r)))}function Qi(n){var t=0,r=0;return function(){var e=Jl(),u=In-(e-r);if(r=e,u>0){if(++t>=On)return arguments[0]}else t=0;
return n.apply(X,arguments)}}function Xi(n,t){var r=-1,e=n.length,u=e-1;for(t=t===X?e:t;++r<t;){var i=tu(r,u),o=n[i];n[i]=n[r],n[r]=o}return n.length=t,n}function no(n){if("string"==typeof n||bc(n))return n;var t=n+"";return"0"==t&&1/n==-Sn?"-0":t}function to(n){if(null!=n){try{return dl.call(n)}catch(n){}try{return n+""}catch(n){}}return""}function ro(n,t){return r($n,function(r){var e="_."+r[0];t&r[1]&&!o(n,e)&&n.push(e)}),n.sort()}function eo(n){if(n instanceof Ct)return n.clone();var t=new Y(n.__wrapped__,n.__chain__);
return t.__actions__=Tu(n.__actions__),t.__index__=n.__index__,t.__values__=n.__values__,t}function uo(n,t,r){t=(r?Ui(n,t,r):t===X)?1:Gl(kc(t),0);var e=null==n?0:n.length;if(!e||t<1)return[];for(var u=0,i=0,o=il(Fl(e/t));u<e;)o[i++]=au(n,u,u+=t);return o}function io(n){for(var t=-1,r=null==n?0:n.length,e=0,u=[];++t<r;){var i=n[t];i&&(u[e++]=i)}return u}function oo(){var n=arguments.length;if(!n)return[];for(var t=il(n-1),r=arguments[0],e=n;e--;)t[e-1]=arguments[e];return a(bh(r)?Tu(r):[r],ee(t,1));
}function fo(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===X?1:kc(t),au(n,t<0?0:t,e)):[]}function co(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===X?1:kc(t),t=e-t,au(n,0,t<0?0:t)):[]}function ao(n,t){return n&&n.length?bu(n,mi(t,3),!0,!0):[]}function lo(n,t){return n&&n.length?bu(n,mi(t,3),!0):[]}function so(n,t,r,e){var u=null==n?0:n.length;return u?(r&&"number"!=typeof r&&Ui(n,t,r)&&(r=0,e=u),ne(n,t,r,e)):[]}function ho(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:kc(r);
return u<0&&(u=Gl(e+u,0)),g(n,mi(t,3),u)}function po(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e-1;return r!==X&&(u=kc(r),u=r<0?Gl(e+u,0):Hl(u,e-1)),g(n,mi(t,3),u,!0)}function _o(n){return(null==n?0:n.length)?ee(n,1):[]}function vo(n){return(null==n?0:n.length)?ee(n,Sn):[]}function go(n,t){return(null==n?0:n.length)?(t=t===X?1:kc(t),ee(n,t)):[]}function yo(n){for(var t=-1,r=null==n?0:n.length,e={};++t<r;){var u=n[t];e[u[0]]=u[1]}return e}function bo(n){return n&&n.length?n[0]:X}function wo(n,t,r){
var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:kc(r);return u<0&&(u=Gl(e+u,0)),y(n,t,u)}function mo(n){return(null==n?0:n.length)?au(n,0,-1):[]}function xo(n,t){return null==n?"":Kl.call(n,t)}function jo(n){var t=null==n?0:n.length;return t?n[t-1]:X}function Ao(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e;return r!==X&&(u=kc(r),u=u<0?Gl(e+u,0):Hl(u,e-1)),t===t?K(n,t,u):g(n,b,u,!0)}function ko(n,t){return n&&n.length?Ge(n,kc(t)):X}function Oo(n,t){return n&&n.length&&t&&t.length?Xe(n,t):n;
}function Io(n,t,r){return n&&n.length&&t&&t.length?Xe(n,t,mi(r,2)):n}function Ro(n,t,r){return n&&n.length&&t&&t.length?Xe(n,t,X,r):n}function zo(n,t){var r=[];if(!n||!n.length)return r;var e=-1,u=[],i=n.length;for(t=mi(t,3);++e<i;){var o=n[e];t(o,e,n)&&(r.push(o),u.push(e))}return nu(n,u),r}function Eo(n){return null==n?n:Xl.call(n)}function So(n,t,r){var e=null==n?0:n.length;return e?(r&&"number"!=typeof r&&Ui(n,t,r)?(t=0,r=e):(t=null==t?0:kc(t),r=r===X?e:kc(r)),au(n,t,r)):[]}function Wo(n,t){
return su(n,t)}function Lo(n,t,r){return hu(n,t,mi(r,2))}function Co(n,t){var r=null==n?0:n.length;if(r){var e=su(n,t);if(e<r&&Gf(n[e],t))return e}return-1}function Uo(n,t){return su(n,t,!0)}function Bo(n,t,r){return hu(n,t,mi(r,2),!0)}function To(n,t){if(null==n?0:n.length){var r=su(n,t,!0)-1;if(Gf(n[r],t))return r}return-1}function $o(n){return n&&n.length?pu(n):[]}function Do(n,t){return n&&n.length?pu(n,mi(t,2)):[]}function Mo(n){var t=null==n?0:n.length;return t?au(n,1,t):[]}function Fo(n,t,r){
return n&&n.length?(t=r||t===X?1:kc(t),au(n,0,t<0?0:t)):[]}function No(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===X?1:kc(t),t=e-t,au(n,t<0?0:t,e)):[]}function Po(n,t){return n&&n.length?bu(n,mi(t,3),!1,!0):[]}function qo(n,t){return n&&n.length?bu(n,mi(t,3)):[]}function Zo(n){return n&&n.length?gu(n):[]}function Ko(n,t){return n&&n.length?gu(n,mi(t,2)):[]}function Vo(n,t){return t="function"==typeof t?t:X,n&&n.length?gu(n,X,t):[]}function Go(n){if(!n||!n.length)return[];var t=0;return n=i(n,function(n){
if(Jf(n))return t=Gl(n.length,t),!0}),O(t,function(t){return c(n,m(t))})}function Ho(t,r){if(!t||!t.length)return[];var e=Go(t);return null==r?e:c(e,function(t){return n(r,X,t)})}function Jo(n,t){return xu(n||[],t||[],Sr)}function Yo(n,t){return xu(n||[],t||[],fu)}function Qo(n){var t=Z(n);return t.__chain__=!0,t}function Xo(n,t){return t(n),n}function nf(n,t){return t(n)}function tf(){return Qo(this)}function rf(){return new Y(this.value(),this.__chain__)}function ef(){this.__values__===X&&(this.__values__=jc(this.value()));
var n=this.__index__>=this.__values__.length;return{done:n,value:n?X:this.__values__[this.__index__++]}}function uf(){return this}function of(n){for(var t,r=this;r instanceof J;){var e=eo(r);e.__index__=0,e.__values__=X,t?u.__wrapped__=e:t=e;var u=e;r=r.__wrapped__}return u.__wrapped__=n,t}function ff(){var n=this.__wrapped__;if(n instanceof Ct){var t=n;return this.__actions__.length&&(t=new Ct(this)),t=t.reverse(),t.__actions__.push({func:nf,args:[Eo],thisArg:X}),new Y(t,this.__chain__)}return this.thru(Eo);
}function cf(){return wu(this.__wrapped__,this.__actions__)}function af(n,t,r){var e=bh(n)?u:Jr;return r&&Ui(n,t,r)&&(t=X),e(n,mi(t,3))}function lf(n,t){return(bh(n)?i:te)(n,mi(t,3))}function sf(n,t){return ee(yf(n,t),1)}function hf(n,t){return ee(yf(n,t),Sn)}function pf(n,t,r){return r=r===X?1:kc(r),ee(yf(n,t),r)}function _f(n,t){return(bh(n)?r:ys)(n,mi(t,3))}function vf(n,t){return(bh(n)?e:ds)(n,mi(t,3))}function gf(n,t,r,e){n=Hf(n)?n:ra(n),r=r&&!e?kc(r):0;var u=n.length;return r<0&&(r=Gl(u+r,0)),
dc(n)?r<=u&&n.indexOf(t,r)>-1:!!u&&y(n,t,r)>-1}function yf(n,t){return(bh(n)?c:Pe)(n,mi(t,3))}function df(n,t,r,e){return null==n?[]:(bh(t)||(t=null==t?[]:[t]),r=e?X:r,bh(r)||(r=null==r?[]:[r]),He(n,t,r))}function bf(n,t,r){var e=bh(n)?l:j,u=arguments.length<3;return e(n,mi(t,4),r,u,ys)}function wf(n,t,r){var e=bh(n)?s:j,u=arguments.length<3;return e(n,mi(t,4),r,u,ds)}function mf(n,t){return(bh(n)?i:te)(n,Uf(mi(t,3)))}function xf(n){return(bh(n)?Ir:iu)(n)}function jf(n,t,r){return t=(r?Ui(n,t,r):t===X)?1:kc(t),
(bh(n)?Rr:ou)(n,t)}function Af(n){return(bh(n)?zr:cu)(n)}function kf(n){if(null==n)return 0;if(Hf(n))return dc(n)?V(n):n.length;var t=zs(n);return t==Gn||t==tt?n.size:Me(n).length}function Of(n,t,r){var e=bh(n)?h:lu;return r&&Ui(n,t,r)&&(t=X),e(n,mi(t,3))}function If(n,t){if("function"!=typeof t)throw new pl(en);return n=kc(n),function(){if(--n<1)return t.apply(this,arguments)}}function Rf(n,t,r){return t=r?X:t,t=n&&null==t?n.length:t,ai(n,mn,X,X,X,X,t)}function zf(n,t){var r;if("function"!=typeof t)throw new pl(en);
return n=kc(n),function(){return--n>0&&(r=t.apply(this,arguments)),n<=1&&(t=X),r}}function Ef(n,t,r){t=r?X:t;var e=ai(n,yn,X,X,X,X,X,t);return e.placeholder=Ef.placeholder,e}function Sf(n,t,r){t=r?X:t;var e=ai(n,dn,X,X,X,X,X,t);return e.placeholder=Sf.placeholder,e}function Wf(n,t,r){function e(t){var r=h,e=p;return h=p=X,d=t,v=n.apply(e,r)}function u(n){return d=n,g=Ws(f,t),b?e(n):v}function i(n){var r=n-y,e=n-d,u=t-r;return w?Hl(u,_-e):u}function o(n){var r=n-y,e=n-d;return y===X||r>=t||r<0||w&&e>=_;
}function f(){var n=fh();return o(n)?c(n):(g=Ws(f,i(n)),X)}function c(n){return g=X,m&&h?e(n):(h=p=X,v)}function a(){g!==X&&As(g),d=0,h=y=p=g=X}function l(){return g===X?v:c(fh())}function s(){var n=fh(),r=o(n);if(h=arguments,p=this,y=n,r){if(g===X)return u(y);if(w)return As(g),g=Ws(f,t),e(y)}return g===X&&(g=Ws(f,t)),v}var h,p,_,v,g,y,d=0,b=!1,w=!1,m=!0;if("function"!=typeof n)throw new pl(en);return t=Ic(t)||0,fc(r)&&(b=!!r.leading,w="maxWait"in r,_=w?Gl(Ic(r.maxWait)||0,t):_,m="trailing"in r?!!r.trailing:m),
s.cancel=a,s.flush=l,s}function Lf(n){return ai(n,jn)}function Cf(n,t){if("function"!=typeof n||null!=t&&"function"!=typeof t)throw new pl(en);var r=function(){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;if(i.has(u))return i.get(u);var o=n.apply(this,e);return r.cache=i.set(u,o)||i,o};return r.cache=new(Cf.Cache||sr),r}function Uf(n){if("function"!=typeof n)throw new pl(en);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:
return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function Bf(n){return zf(2,n)}function Tf(n,t){if("function"!=typeof n)throw new pl(en);return t=t===X?t:kc(t),uu(n,t)}function $f(t,r){if("function"!=typeof t)throw new pl(en);return r=null==r?0:Gl(kc(r),0),uu(function(e){var u=e[r],i=Ou(e,0,r);return u&&a(i,u),n(t,this,i)})}function Df(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new pl(en);return fc(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),
Wf(n,t,{leading:e,maxWait:t,trailing:u})}function Mf(n){return Rf(n,1)}function Ff(n,t){return ph(Au(t),n)}function Nf(){if(!arguments.length)return[];var n=arguments[0];return bh(n)?n:[n]}function Pf(n){return Fr(n,sn)}function qf(n,t){return t="function"==typeof t?t:X,Fr(n,sn,t)}function Zf(n){return Fr(n,an|sn)}function Kf(n,t){return t="function"==typeof t?t:X,Fr(n,an|sn,t)}function Vf(n,t){return null==t||Pr(n,t,Pc(t))}function Gf(n,t){return n===t||n!==n&&t!==t}function Hf(n){return null!=n&&oc(n.length)&&!uc(n);
}function Jf(n){return cc(n)&&Hf(n)}function Yf(n){return n===!0||n===!1||cc(n)&&we(n)==Nn}function Qf(n){return cc(n)&&1===n.nodeType&&!gc(n)}function Xf(n){if(null==n)return!0;if(Hf(n)&&(bh(n)||"string"==typeof n||"function"==typeof n.splice||mh(n)||Oh(n)||dh(n)))return!n.length;var t=zs(n);if(t==Gn||t==tt)return!n.size;if(Mi(n))return!Me(n).length;for(var r in n)if(bl.call(n,r))return!1;return!0}function nc(n,t){return Se(n,t)}function tc(n,t,r){r="function"==typeof r?r:X;var e=r?r(n,t):X;return e===X?Se(n,t,X,r):!!e;
}function rc(n){if(!cc(n))return!1;var t=we(n);return t==Zn||t==qn||"string"==typeof n.message&&"string"==typeof n.name&&!gc(n)}function ec(n){return"number"==typeof n&&Zl(n)}function uc(n){if(!fc(n))return!1;var t=we(n);return t==Kn||t==Vn||t==Fn||t==Xn}function ic(n){return"number"==typeof n&&n==kc(n)}function oc(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=Wn}function fc(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function cc(n){return null!=n&&"object"==typeof n}function ac(n,t){
return n===t||Ce(n,t,ji(t))}function lc(n,t,r){return r="function"==typeof r?r:X,Ce(n,t,ji(t),r)}function sc(n){return vc(n)&&n!=+n}function hc(n){if(Es(n))throw new fl(rn);return Ue(n)}function pc(n){return null===n}function _c(n){return null==n}function vc(n){return"number"==typeof n||cc(n)&&we(n)==Hn}function gc(n){if(!cc(n)||we(n)!=Yn)return!1;var t=El(n);if(null===t)return!0;var r=bl.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&dl.call(r)==jl}function yc(n){
return ic(n)&&n>=-Wn&&n<=Wn}function dc(n){return"string"==typeof n||!bh(n)&&cc(n)&&we(n)==rt}function bc(n){return"symbol"==typeof n||cc(n)&&we(n)==et}function wc(n){return n===X}function mc(n){return cc(n)&&zs(n)==it}function xc(n){return cc(n)&&we(n)==ot}function jc(n){if(!n)return[];if(Hf(n))return dc(n)?G(n):Tu(n);if(Ul&&n[Ul])return D(n[Ul]());var t=zs(n);return(t==Gn?M:t==tt?P:ra)(n)}function Ac(n){if(!n)return 0===n?n:0;if(n=Ic(n),n===Sn||n===-Sn){return(n<0?-1:1)*Ln}return n===n?n:0}function kc(n){
var t=Ac(n),r=t%1;return t===t?r?t-r:t:0}function Oc(n){return n?Mr(kc(n),0,Un):0}function Ic(n){if("number"==typeof n)return n;if(bc(n))return Cn;if(fc(n)){var t="function"==typeof n.valueOf?n.valueOf():n;n=fc(t)?t+"":t}if("string"!=typeof n)return 0===n?n:+n;n=R(n);var r=qt.test(n);return r||Kt.test(n)?Xr(n.slice(2),r?2:8):Pt.test(n)?Cn:+n}function Rc(n){return $u(n,qc(n))}function zc(n){return n?Mr(kc(n),-Wn,Wn):0===n?n:0}function Ec(n){return null==n?"":vu(n)}function Sc(n,t){var r=gs(n);return null==t?r:Cr(r,t);
}function Wc(n,t){return v(n,mi(t,3),ue)}function Lc(n,t){return v(n,mi(t,3),oe)}function Cc(n,t){return null==n?n:bs(n,mi(t,3),qc)}function Uc(n,t){return null==n?n:ws(n,mi(t,3),qc)}function Bc(n,t){return n&&ue(n,mi(t,3))}function Tc(n,t){return n&&oe(n,mi(t,3))}function $c(n){return null==n?[]:fe(n,Pc(n))}function Dc(n){return null==n?[]:fe(n,qc(n))}function Mc(n,t,r){var e=null==n?X:_e(n,t);return e===X?r:e}function Fc(n,t){return null!=n&&Ri(n,t,xe)}function Nc(n,t){return null!=n&&Ri(n,t,je);
}function Pc(n){return Hf(n)?Or(n):Me(n)}function qc(n){return Hf(n)?Or(n,!0):Fe(n)}function Zc(n,t){var r={};return t=mi(t,3),ue(n,function(n,e,u){Br(r,t(n,e,u),n)}),r}function Kc(n,t){var r={};return t=mi(t,3),ue(n,function(n,e,u){Br(r,e,t(n,e,u))}),r}function Vc(n,t){return Gc(n,Uf(mi(t)))}function Gc(n,t){if(null==n)return{};var r=c(di(n),function(n){return[n]});return t=mi(t),Ye(n,r,function(n,r){return t(n,r[0])})}function Hc(n,t,r){t=ku(t,n);var e=-1,u=t.length;for(u||(u=1,n=X);++e<u;){var i=null==n?X:n[no(t[e])];
i===X&&(e=u,i=r),n=uc(i)?i.call(n):i}return n}function Jc(n,t,r){return null==n?n:fu(n,t,r)}function Yc(n,t,r,e){return e="function"==typeof e?e:X,null==n?n:fu(n,t,r,e)}function Qc(n,t,e){var u=bh(n),i=u||mh(n)||Oh(n);if(t=mi(t,4),null==e){var o=n&&n.constructor;e=i?u?new o:[]:fc(n)&&uc(o)?gs(El(n)):{}}return(i?r:ue)(n,function(n,r,u){return t(e,n,r,u)}),e}function Xc(n,t){return null==n||yu(n,t)}function na(n,t,r){return null==n?n:du(n,t,Au(r))}function ta(n,t,r,e){return e="function"==typeof e?e:X,
null==n?n:du(n,t,Au(r),e)}function ra(n){return null==n?[]:E(n,Pc(n))}function ea(n){return null==n?[]:E(n,qc(n))}function ua(n,t,r){return r===X&&(r=t,t=X),r!==X&&(r=Ic(r),r=r===r?r:0),t!==X&&(t=Ic(t),t=t===t?t:0),Mr(Ic(n),t,r)}function ia(n,t,r){return t=Ac(t),r===X?(r=t,t=0):r=Ac(r),n=Ic(n),Ae(n,t,r)}function oa(n,t,r){if(r&&"boolean"!=typeof r&&Ui(n,t,r)&&(t=r=X),r===X&&("boolean"==typeof t?(r=t,t=X):"boolean"==typeof n&&(r=n,n=X)),n===X&&t===X?(n=0,t=1):(n=Ac(n),t===X?(t=n,n=0):t=Ac(t)),n>t){
var e=n;n=t,t=e}if(r||n%1||t%1){var u=Ql();return Hl(n+u*(t-n+Qr("1e-"+((u+"").length-1))),t)}return tu(n,t)}function fa(n){return Qh(Ec(n).toLowerCase())}function ca(n){return n=Ec(n),n&&n.replace(Gt,ve).replace(Dr,"")}function aa(n,t,r){n=Ec(n),t=vu(t);var e=n.length;r=r===X?e:Mr(kc(r),0,e);var u=r;return r-=t.length,r>=0&&n.slice(r,u)==t}function la(n){return n=Ec(n),n&&At.test(n)?n.replace(xt,ge):n}function sa(n){return n=Ec(n),n&&Wt.test(n)?n.replace(St,"\\$&"):n}function ha(n,t,r){n=Ec(n),t=kc(t);
var e=t?V(n):0;if(!t||e>=t)return n;var u=(t-e)/2;return ri(Nl(u),r)+n+ri(Fl(u),r)}function pa(n,t,r){n=Ec(n),t=kc(t);var e=t?V(n):0;return t&&e<t?n+ri(t-e,r):n}function _a(n,t,r){n=Ec(n),t=kc(t);var e=t?V(n):0;return t&&e<t?ri(t-e,r)+n:n}function va(n,t,r){return r||null==t?t=0:t&&(t=+t),Yl(Ec(n).replace(Lt,""),t||0)}function ga(n,t,r){return t=(r?Ui(n,t,r):t===X)?1:kc(t),eu(Ec(n),t)}function ya(){var n=arguments,t=Ec(n[0]);return n.length<3?t:t.replace(n[1],n[2])}function da(n,t,r){return r&&"number"!=typeof r&&Ui(n,t,r)&&(t=r=X),
(r=r===X?Un:r>>>0)?(n=Ec(n),n&&("string"==typeof t||null!=t&&!Ah(t))&&(t=vu(t),!t&&T(n))?Ou(G(n),0,r):n.split(t,r)):[]}function ba(n,t,r){return n=Ec(n),r=null==r?0:Mr(kc(r),0,n.length),t=vu(t),n.slice(r,r+t.length)==t}function wa(n,t,r){var e=Z.templateSettings;r&&Ui(n,t,r)&&(t=X),n=Ec(n),t=Sh({},t,e,li);var u,i,o=Sh({},t.imports,e.imports,li),f=Pc(o),c=E(o,f),a=0,l=t.interpolate||Ht,s="__p += '",h=sl((t.escape||Ht).source+"|"+l.source+"|"+(l===It?Ft:Ht).source+"|"+(t.evaluate||Ht).source+"|$","g"),p="//# sourceURL="+(bl.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Zr+"]")+"\n";
n.replace(h,function(t,r,e,o,f,c){return e||(e=o),s+=n.slice(a,c).replace(Jt,U),r&&(u=!0,s+="' +\n__e("+r+") +\n'"),f&&(i=!0,s+="';\n"+f+";\n__p += '"),e&&(s+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),a=c+t.length,t}),s+="';\n";var _=bl.call(t,"variable")&&t.variable;if(_){if(Dt.test(_))throw new fl(un)}else s="with (obj) {\n"+s+"\n}\n";s=(i?s.replace(dt,""):s).replace(bt,"$1").replace(wt,"$1;"),s="function("+(_||"obj")+") {\n"+(_?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(u?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+s+"return __p\n}";
var v=Xh(function(){return cl(f,p+"return "+s).apply(X,c)});if(v.source=s,rc(v))throw v;return v}function ma(n){return Ec(n).toLowerCase()}function xa(n){return Ec(n).toUpperCase()}function ja(n,t,r){if(n=Ec(n),n&&(r||t===X))return R(n);if(!n||!(t=vu(t)))return n;var e=G(n),u=G(t);return Ou(e,W(e,u),L(e,u)+1).join("")}function Aa(n,t,r){if(n=Ec(n),n&&(r||t===X))return n.slice(0,H(n)+1);if(!n||!(t=vu(t)))return n;var e=G(n);return Ou(e,0,L(e,G(t))+1).join("")}function ka(n,t,r){if(n=Ec(n),n&&(r||t===X))return n.replace(Lt,"");
if(!n||!(t=vu(t)))return n;var e=G(n);return Ou(e,W(e,G(t))).join("")}function Oa(n,t){var r=An,e=kn;if(fc(t)){var u="separator"in t?t.separator:u;r="length"in t?kc(t.length):r,e="omission"in t?vu(t.omission):e}n=Ec(n);var i=n.length;if(T(n)){var o=G(n);i=o.length}if(r>=i)return n;var f=r-V(e);if(f<1)return e;var c=o?Ou(o,0,f).join(""):n.slice(0,f);if(u===X)return c+e;if(o&&(f+=c.length-f),Ah(u)){if(n.slice(f).search(u)){var a,l=c;for(u.global||(u=sl(u.source,Ec(Nt.exec(u))+"g")),u.lastIndex=0;a=u.exec(l);)var s=a.index;
c=c.slice(0,s===X?f:s)}}else if(n.indexOf(vu(u),f)!=f){var h=c.lastIndexOf(u);h>-1&&(c=c.slice(0,h))}return c+e}function Ia(n){return n=Ec(n),n&&jt.test(n)?n.replace(mt,ye):n}function Ra(n,t,r){return n=Ec(n),t=r?X:t,t===X?$(n)?Q(n):_(n):n.match(t)||[]}function za(t){var r=null==t?0:t.length,e=mi();return t=r?c(t,function(n){if("function"!=typeof n[1])throw new pl(en);return[e(n[0]),n[1]]}):[],uu(function(e){for(var u=-1;++u<r;){var i=t[u];if(n(i[0],this,e))return n(i[1],this,e)}})}function Ea(n){
return Nr(Fr(n,an))}function Sa(n){return function(){return n}}function Wa(n,t){return null==n||n!==n?t:n}function La(n){return n}function Ca(n){return De("function"==typeof n?n:Fr(n,an))}function Ua(n){return qe(Fr(n,an))}function Ba(n,t){return Ze(n,Fr(t,an))}function Ta(n,t,e){var u=Pc(t),i=fe(t,u);null!=e||fc(t)&&(i.length||!u.length)||(e=t,t=n,n=this,i=fe(t,Pc(t)));var o=!(fc(e)&&"chain"in e&&!e.chain),f=uc(n);return r(i,function(r){var e=t[r];n[r]=e,f&&(n.prototype[r]=function(){var t=this.__chain__;
if(o||t){var r=n(this.__wrapped__);return(r.__actions__=Tu(this.__actions__)).push({func:e,args:arguments,thisArg:n}),r.__chain__=t,r}return e.apply(n,a([this.value()],arguments))})}),n}function $a(){return re._===this&&(re._=Al),this}function Da(){}function Ma(n){return n=kc(n),uu(function(t){return Ge(t,n)})}function Fa(n){return Bi(n)?m(no(n)):Qe(n)}function Na(n){return function(t){return null==n?X:_e(n,t)}}function Pa(){return[]}function qa(){return!1}function Za(){return{}}function Ka(){return"";
}function Va(){return!0}function Ga(n,t){if(n=kc(n),n<1||n>Wn)return[];var r=Un,e=Hl(n,Un);t=mi(t),n-=Un;for(var u=O(e,t);++r<n;)t(r);return u}function Ha(n){return bh(n)?c(n,no):bc(n)?[n]:Tu(Cs(Ec(n)))}function Ja(n){var t=++wl;return Ec(n)+t}function Ya(n){return n&&n.length?Yr(n,La,me):X}function Qa(n,t){return n&&n.length?Yr(n,mi(t,2),me):X}function Xa(n){return w(n,La)}function nl(n,t){return w(n,mi(t,2))}function tl(n){return n&&n.length?Yr(n,La,Ne):X}function rl(n,t){return n&&n.length?Yr(n,mi(t,2),Ne):X;
}function el(n){return n&&n.length?k(n,La):0}function ul(n,t){return n&&n.length?k(n,mi(t,2)):0}x=null==x?re:be.defaults(re.Object(),x,be.pick(re,qr));var il=x.Array,ol=x.Date,fl=x.Error,cl=x.Function,al=x.Math,ll=x.Object,sl=x.RegExp,hl=x.String,pl=x.TypeError,_l=il.prototype,vl=cl.prototype,gl=ll.prototype,yl=x["__core-js_shared__"],dl=vl.toString,bl=gl.hasOwnProperty,wl=0,ml=function(){var n=/[^.]+$/.exec(yl&&yl.keys&&yl.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""}(),xl=gl.toString,jl=dl.call(ll),Al=re._,kl=sl("^"+dl.call(bl).replace(St,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ol=ie?x.Buffer:X,Il=x.Symbol,Rl=x.Uint8Array,zl=Ol?Ol.allocUnsafe:X,El=F(ll.getPrototypeOf,ll),Sl=ll.create,Wl=gl.propertyIsEnumerable,Ll=_l.splice,Cl=Il?Il.isConcatSpreadable:X,Ul=Il?Il.iterator:X,Bl=Il?Il.toStringTag:X,Tl=function(){
try{var n=Ai(ll,"defineProperty");return n({},"",{}),n}catch(n){}}(),$l=x.clearTimeout!==re.clearTimeout&&x.clearTimeout,Dl=ol&&ol.now!==re.Date.now&&ol.now,Ml=x.setTimeout!==re.setTimeout&&x.setTimeout,Fl=al.ceil,Nl=al.floor,Pl=ll.getOwnPropertySymbols,ql=Ol?Ol.isBuffer:X,Zl=x.isFinite,Kl=_l.join,Vl=F(ll.keys,ll),Gl=al.max,Hl=al.min,Jl=ol.now,Yl=x.parseInt,Ql=al.random,Xl=_l.reverse,ns=Ai(x,"DataView"),ts=Ai(x,"Map"),rs=Ai(x,"Promise"),es=Ai(x,"Set"),us=Ai(x,"WeakMap"),is=Ai(ll,"create"),os=us&&new us,fs={},cs=to(ns),as=to(ts),ls=to(rs),ss=to(es),hs=to(us),ps=Il?Il.prototype:X,_s=ps?ps.valueOf:X,vs=ps?ps.toString:X,gs=function(){
function n(){}return function(t){if(!fc(t))return{};if(Sl)return Sl(t);n.prototype=t;var r=new n;return n.prototype=X,r}}();Z.templateSettings={escape:kt,evaluate:Ot,interpolate:It,variable:"",imports:{_:Z}},Z.prototype=J.prototype,Z.prototype.constructor=Z,Y.prototype=gs(J.prototype),Y.prototype.constructor=Y,Ct.prototype=gs(J.prototype),Ct.prototype.constructor=Ct,Xt.prototype.clear=nr,Xt.prototype.delete=tr,Xt.prototype.get=rr,Xt.prototype.has=er,Xt.prototype.set=ur,ir.prototype.clear=or,ir.prototype.delete=fr,
ir.prototype.get=cr,ir.prototype.has=ar,ir.prototype.set=lr,sr.prototype.clear=hr,sr.prototype.delete=pr,sr.prototype.get=_r,sr.prototype.has=vr,sr.prototype.set=gr,yr.prototype.add=yr.prototype.push=dr,yr.prototype.has=br,wr.prototype.clear=mr,wr.prototype.delete=xr,wr.prototype.get=jr,wr.prototype.has=Ar,wr.prototype.set=kr;var ys=Pu(ue),ds=Pu(oe,!0),bs=qu(),ws=qu(!0),ms=os?function(n,t){return os.set(n,t),n}:La,xs=Tl?function(n,t){return Tl(n,"toString",{configurable:!0,enumerable:!1,value:Sa(t),
writable:!0})}:La,js=uu,As=$l||function(n){return re.clearTimeout(n)},ks=es&&1/P(new es([,-0]))[1]==Sn?function(n){return new es(n)}:Da,Os=os?function(n){return os.get(n)}:Da,Is=Pl?function(n){return null==n?[]:(n=ll(n),i(Pl(n),function(t){return Wl.call(n,t)}))}:Pa,Rs=Pl?function(n){for(var t=[];n;)a(t,Is(n)),n=El(n);return t}:Pa,zs=we;(ns&&zs(new ns(new ArrayBuffer(1)))!=ct||ts&&zs(new ts)!=Gn||rs&&zs(rs.resolve())!=Qn||es&&zs(new es)!=tt||us&&zs(new us)!=it)&&(zs=function(n){var t=we(n),r=t==Yn?n.constructor:X,e=r?to(r):"";
if(e)switch(e){case cs:return ct;case as:return Gn;case ls:return Qn;case ss:return tt;case hs:return it}return t});var Es=yl?uc:qa,Ss=Qi(ms),Ws=Ml||function(n,t){return re.setTimeout(n,t)},Ls=Qi(xs),Cs=Pi(function(n){var t=[];return 46===n.charCodeAt(0)&&t.push(""),n.replace(Et,function(n,r,e,u){t.push(e?u.replace(Mt,"$1"):r||n)}),t}),Us=uu(function(n,t){return Jf(n)?Hr(n,ee(t,1,Jf,!0)):[]}),Bs=uu(function(n,t){var r=jo(t);return Jf(r)&&(r=X),Jf(n)?Hr(n,ee(t,1,Jf,!0),mi(r,2)):[]}),Ts=uu(function(n,t){
var r=jo(t);return Jf(r)&&(r=X),Jf(n)?Hr(n,ee(t,1,Jf,!0),X,r):[]}),$s=uu(function(n){var t=c(n,ju);return t.length&&t[0]===n[0]?ke(t):[]}),Ds=uu(function(n){var t=jo(n),r=c(n,ju);return t===jo(r)?t=X:r.pop(),r.length&&r[0]===n[0]?ke(r,mi(t,2)):[]}),Ms=uu(function(n){var t=jo(n),r=c(n,ju);return t="function"==typeof t?t:X,t&&r.pop(),r.length&&r[0]===n[0]?ke(r,X,t):[]}),Fs=uu(Oo),Ns=gi(function(n,t){var r=null==n?0:n.length,e=Tr(n,t);return nu(n,c(t,function(n){return Ci(n,r)?+n:n}).sort(Lu)),e}),Ps=uu(function(n){
return gu(ee(n,1,Jf,!0))}),qs=uu(function(n){var t=jo(n);return Jf(t)&&(t=X),gu(ee(n,1,Jf,!0),mi(t,2))}),Zs=uu(function(n){var t=jo(n);return t="function"==typeof t?t:X,gu(ee(n,1,Jf,!0),X,t)}),Ks=uu(function(n,t){return Jf(n)?Hr(n,t):[]}),Vs=uu(function(n){return mu(i(n,Jf))}),Gs=uu(function(n){var t=jo(n);return Jf(t)&&(t=X),mu(i(n,Jf),mi(t,2))}),Hs=uu(function(n){var t=jo(n);return t="function"==typeof t?t:X,mu(i(n,Jf),X,t)}),Js=uu(Go),Ys=uu(function(n){var t=n.length,r=t>1?n[t-1]:X;return r="function"==typeof r?(n.pop(),
r):X,Ho(n,r)}),Qs=gi(function(n){var t=n.length,r=t?n[0]:0,e=this.__wrapped__,u=function(t){return Tr(t,n)};return!(t>1||this.__actions__.length)&&e instanceof Ct&&Ci(r)?(e=e.slice(r,+r+(t?1:0)),e.__actions__.push({func:nf,args:[u],thisArg:X}),new Y(e,this.__chain__).thru(function(n){return t&&!n.length&&n.push(X),n})):this.thru(u)}),Xs=Fu(function(n,t,r){bl.call(n,r)?++n[r]:Br(n,r,1)}),nh=Ju(ho),th=Ju(po),rh=Fu(function(n,t,r){bl.call(n,r)?n[r].push(t):Br(n,r,[t])}),eh=uu(function(t,r,e){var u=-1,i="function"==typeof r,o=Hf(t)?il(t.length):[];
return ys(t,function(t){o[++u]=i?n(r,t,e):Ie(t,r,e)}),o}),uh=Fu(function(n,t,r){Br(n,r,t)}),ih=Fu(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),oh=uu(function(n,t){if(null==n)return[];var r=t.length;return r>1&&Ui(n,t[0],t[1])?t=[]:r>2&&Ui(t[0],t[1],t[2])&&(t=[t[0]]),He(n,ee(t,1),[])}),fh=Dl||function(){return re.Date.now()},ch=uu(function(n,t,r){var e=_n;if(r.length){var u=N(r,wi(ch));e|=bn}return ai(n,e,t,r,u)}),ah=uu(function(n,t,r){var e=_n|vn;if(r.length){var u=N(r,wi(ah));e|=bn;
}return ai(t,e,n,r,u)}),lh=uu(function(n,t){return Gr(n,1,t)}),sh=uu(function(n,t,r){return Gr(n,Ic(t)||0,r)});Cf.Cache=sr;var hh=js(function(t,r){r=1==r.length&&bh(r[0])?c(r[0],z(mi())):c(ee(r,1),z(mi()));var e=r.length;return uu(function(u){for(var i=-1,o=Hl(u.length,e);++i<o;)u[i]=r[i].call(this,u[i]);return n(t,this,u)})}),ph=uu(function(n,t){return ai(n,bn,X,t,N(t,wi(ph)))}),_h=uu(function(n,t){return ai(n,wn,X,t,N(t,wi(_h)))}),vh=gi(function(n,t){return ai(n,xn,X,X,X,t)}),gh=ii(me),yh=ii(function(n,t){
return n>=t}),dh=Re(function(){return arguments}())?Re:function(n){return cc(n)&&bl.call(n,"callee")&&!Wl.call(n,"callee")},bh=il.isArray,wh=ce?z(ce):ze,mh=ql||qa,xh=ae?z(ae):Ee,jh=le?z(le):Le,Ah=se?z(se):Be,kh=he?z(he):Te,Oh=pe?z(pe):$e,Ih=ii(Ne),Rh=ii(function(n,t){return n<=t}),zh=Nu(function(n,t){if(Mi(t)||Hf(t))return $u(t,Pc(t),n),X;for(var r in t)bl.call(t,r)&&Sr(n,r,t[r])}),Eh=Nu(function(n,t){$u(t,qc(t),n)}),Sh=Nu(function(n,t,r,e){$u(t,qc(t),n,e)}),Wh=Nu(function(n,t,r,e){$u(t,Pc(t),n,e);
}),Lh=gi(Tr),Ch=uu(function(n,t){n=ll(n);var r=-1,e=t.length,u=e>2?t[2]:X;for(u&&Ui(t[0],t[1],u)&&(e=1);++r<e;)for(var i=t[r],o=qc(i),f=-1,c=o.length;++f<c;){var a=o[f],l=n[a];(l===X||Gf(l,gl[a])&&!bl.call(n,a))&&(n[a]=i[a])}return n}),Uh=uu(function(t){return t.push(X,si),n(Mh,X,t)}),Bh=Xu(function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=xl.call(t)),n[t]=r},Sa(La)),Th=Xu(function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=xl.call(t)),bl.call(n,t)?n[t].push(r):n[t]=[r]},mi),$h=uu(Ie),Dh=Nu(function(n,t,r){
Ke(n,t,r)}),Mh=Nu(function(n,t,r,e){Ke(n,t,r,e)}),Fh=gi(function(n,t){var r={};if(null==n)return r;var e=!1;t=c(t,function(t){return t=ku(t,n),e||(e=t.length>1),t}),$u(n,di(n),r),e&&(r=Fr(r,an|ln|sn,hi));for(var u=t.length;u--;)yu(r,t[u]);return r}),Nh=gi(function(n,t){return null==n?{}:Je(n,t)}),Ph=ci(Pc),qh=ci(qc),Zh=Vu(function(n,t,r){return t=t.toLowerCase(),n+(r?fa(t):t)}),Kh=Vu(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Vh=Vu(function(n,t,r){return n+(r?" ":"")+t.toLowerCase()}),Gh=Ku("toLowerCase"),Hh=Vu(function(n,t,r){
return n+(r?"_":"")+t.toLowerCase()}),Jh=Vu(function(n,t,r){return n+(r?" ":"")+Qh(t)}),Yh=Vu(function(n,t,r){return n+(r?" ":"")+t.toUpperCase()}),Qh=Ku("toUpperCase"),Xh=uu(function(t,r){try{return n(t,X,r)}catch(n){return rc(n)?n:new fl(n)}}),np=gi(function(n,t){return r(t,function(t){t=no(t),Br(n,t,ch(n[t],n))}),n}),tp=Yu(),rp=Yu(!0),ep=uu(function(n,t){return function(r){return Ie(r,n,t)}}),up=uu(function(n,t){return function(r){return Ie(n,r,t)}}),ip=ti(c),op=ti(u),fp=ti(h),cp=ui(),ap=ui(!0),lp=ni(function(n,t){
return n+t},0),sp=fi("ceil"),hp=ni(function(n,t){return n/t},1),pp=fi("floor"),_p=ni(function(n,t){return n*t},1),vp=fi("round"),gp=ni(function(n,t){return n-t},0);return Z.after=If,Z.ary=Rf,Z.assign=zh,Z.assignIn=Eh,Z.assignInWith=Sh,Z.assignWith=Wh,Z.at=Lh,Z.before=zf,Z.bind=ch,Z.bindAll=np,Z.bindKey=ah,Z.castArray=Nf,Z.chain=Qo,Z.chunk=uo,Z.compact=io,Z.concat=oo,Z.cond=za,Z.conforms=Ea,Z.constant=Sa,Z.countBy=Xs,Z.create=Sc,Z.curry=Ef,Z.curryRight=Sf,Z.debounce=Wf,Z.defaults=Ch,Z.defaultsDeep=Uh,
Z.defer=lh,Z.delay=sh,Z.difference=Us,Z.differenceBy=Bs,Z.differenceWith=Ts,Z.drop=fo,Z.dropRight=co,Z.dropRightWhile=ao,Z.dropWhile=lo,Z.fill=so,Z.filter=lf,Z.flatMap=sf,Z.flatMapDeep=hf,Z.flatMapDepth=pf,Z.flatten=_o,Z.flattenDeep=vo,Z.flattenDepth=go,Z.flip=Lf,Z.flow=tp,Z.flowRight=rp,Z.fromPairs=yo,Z.functions=$c,Z.functionsIn=Dc,Z.groupBy=rh,Z.initial=mo,Z.intersection=$s,Z.intersectionBy=Ds,Z.intersectionWith=Ms,Z.invert=Bh,Z.invertBy=Th,Z.invokeMap=eh,Z.iteratee=Ca,Z.keyBy=uh,Z.keys=Pc,Z.keysIn=qc,
Z.map=yf,Z.mapKeys=Zc,Z.mapValues=Kc,Z.matches=Ua,Z.matchesProperty=Ba,Z.memoize=Cf,Z.merge=Dh,Z.mergeWith=Mh,Z.method=ep,Z.methodOf=up,Z.mixin=Ta,Z.negate=Uf,Z.nthArg=Ma,Z.omit=Fh,Z.omitBy=Vc,Z.once=Bf,Z.orderBy=df,Z.over=ip,Z.overArgs=hh,Z.overEvery=op,Z.overSome=fp,Z.partial=ph,Z.partialRight=_h,Z.partition=ih,Z.pick=Nh,Z.pickBy=Gc,Z.property=Fa,Z.propertyOf=Na,Z.pull=Fs,Z.pullAll=Oo,Z.pullAllBy=Io,Z.pullAllWith=Ro,Z.pullAt=Ns,Z.range=cp,Z.rangeRight=ap,Z.rearg=vh,Z.reject=mf,Z.remove=zo,Z.rest=Tf,
Z.reverse=Eo,Z.sampleSize=jf,Z.set=Jc,Z.setWith=Yc,Z.shuffle=Af,Z.slice=So,Z.sortBy=oh,Z.sortedUniq=$o,Z.sortedUniqBy=Do,Z.split=da,Z.spread=$f,Z.tail=Mo,Z.take=Fo,Z.takeRight=No,Z.takeRightWhile=Po,Z.takeWhile=qo,Z.tap=Xo,Z.throttle=Df,Z.thru=nf,Z.toArray=jc,Z.toPairs=Ph,Z.toPairsIn=qh,Z.toPath=Ha,Z.toPlainObject=Rc,Z.transform=Qc,Z.unary=Mf,Z.union=Ps,Z.unionBy=qs,Z.unionWith=Zs,Z.uniq=Zo,Z.uniqBy=Ko,Z.uniqWith=Vo,Z.unset=Xc,Z.unzip=Go,Z.unzipWith=Ho,Z.update=na,Z.updateWith=ta,Z.values=ra,Z.valuesIn=ea,
Z.without=Ks,Z.words=Ra,Z.wrap=Ff,Z.xor=Vs,Z.xorBy=Gs,Z.xorWith=Hs,Z.zip=Js,Z.zipObject=Jo,Z.zipObjectDeep=Yo,Z.zipWith=Ys,Z.entries=Ph,Z.entriesIn=qh,Z.extend=Eh,Z.extendWith=Sh,Ta(Z,Z),Z.add=lp,Z.attempt=Xh,Z.camelCase=Zh,Z.capitalize=fa,Z.ceil=sp,Z.clamp=ua,Z.clone=Pf,Z.cloneDeep=Zf,Z.cloneDeepWith=Kf,Z.cloneWith=qf,Z.conformsTo=Vf,Z.deburr=ca,Z.defaultTo=Wa,Z.divide=hp,Z.endsWith=aa,Z.eq=Gf,Z.escape=la,Z.escapeRegExp=sa,Z.every=af,Z.find=nh,Z.findIndex=ho,Z.findKey=Wc,Z.findLast=th,Z.findLastIndex=po,
Z.findLastKey=Lc,Z.floor=pp,Z.forEach=_f,Z.forEachRight=vf,Z.forIn=Cc,Z.forInRight=Uc,Z.forOwn=Bc,Z.forOwnRight=Tc,Z.get=Mc,Z.gt=gh,Z.gte=yh,Z.has=Fc,Z.hasIn=Nc,Z.head=bo,Z.identity=La,Z.includes=gf,Z.indexOf=wo,Z.inRange=ia,Z.invoke=$h,Z.isArguments=dh,Z.isArray=bh,Z.isArrayBuffer=wh,Z.isArrayLike=Hf,Z.isArrayLikeObject=Jf,Z.isBoolean=Yf,Z.isBuffer=mh,Z.isDate=xh,Z.isElement=Qf,Z.isEmpty=Xf,Z.isEqual=nc,Z.isEqualWith=tc,Z.isError=rc,Z.isFinite=ec,Z.isFunction=uc,Z.isInteger=ic,Z.isLength=oc,Z.isMap=jh,
Z.isMatch=ac,Z.isMatchWith=lc,Z.isNaN=sc,Z.isNative=hc,Z.isNil=_c,Z.isNull=pc,Z.isNumber=vc,Z.isObject=fc,Z.isObjectLike=cc,Z.isPlainObject=gc,Z.isRegExp=Ah,Z.isSafeInteger=yc,Z.isSet=kh,Z.isString=dc,Z.isSymbol=bc,Z.isTypedArray=Oh,Z.isUndefined=wc,Z.isWeakMap=mc,Z.isWeakSet=xc,Z.join=xo,Z.kebabCase=Kh,Z.last=jo,Z.lastIndexOf=Ao,Z.lowerCase=Vh,Z.lowerFirst=Gh,Z.lt=Ih,Z.lte=Rh,Z.max=Ya,Z.maxBy=Qa,Z.mean=Xa,Z.meanBy=nl,Z.min=tl,Z.minBy=rl,Z.stubArray=Pa,Z.stubFalse=qa,Z.stubObject=Za,Z.stubString=Ka,
Z.stubTrue=Va,Z.multiply=_p,Z.nth=ko,Z.noConflict=$a,Z.noop=Da,Z.now=fh,Z.pad=ha,Z.padEnd=pa,Z.padStart=_a,Z.parseInt=va,Z.random=oa,Z.reduce=bf,Z.reduceRight=wf,Z.repeat=ga,Z.replace=ya,Z.result=Hc,Z.round=vp,Z.runInContext=p,Z.sample=xf,Z.size=kf,Z.snakeCase=Hh,Z.some=Of,Z.sortedIndex=Wo,Z.sortedIndexBy=Lo,Z.sortedIndexOf=Co,Z.sortedLastIndex=Uo,Z.sortedLastIndexBy=Bo,Z.sortedLastIndexOf=To,Z.startCase=Jh,Z.startsWith=ba,Z.subtract=gp,Z.sum=el,Z.sumBy=ul,Z.template=wa,Z.times=Ga,Z.toFinite=Ac,Z.toInteger=kc,
Z.toLength=Oc,Z.toLower=ma,Z.toNumber=Ic,Z.toSafeInteger=zc,Z.toString=Ec,Z.toUpper=xa,Z.trim=ja,Z.trimEnd=Aa,Z.trimStart=ka,Z.truncate=Oa,Z.unescape=Ia,Z.uniqueId=Ja,Z.upperCase=Yh,Z.upperFirst=Qh,Z.each=_f,Z.eachRight=vf,Z.first=bo,Ta(Z,function(){var n={};return ue(Z,function(t,r){bl.call(Z.prototype,r)||(n[r]=t)}),n}(),{chain:!1}),Z.VERSION=nn,r(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){Z[n].placeholder=Z}),r(["drop","take"],function(n,t){Ct.prototype[n]=function(r){
r=r===X?1:Gl(kc(r),0);var e=this.__filtered__&&!t?new Ct(this):this.clone();return e.__filtered__?e.__takeCount__=Hl(r,e.__takeCount__):e.__views__.push({size:Hl(r,Un),type:n+(e.__dir__<0?"Right":"")}),e},Ct.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),r(["filter","map","takeWhile"],function(n,t){var r=t+1,e=r==Rn||r==En;Ct.prototype[n]=function(n){var t=this.clone();return t.__iteratees__.push({iteratee:mi(n,3),type:r}),t.__filtered__=t.__filtered__||e,t}}),r(["head","last"],function(n,t){
var r="take"+(t?"Right":"");Ct.prototype[n]=function(){return this[r](1).value()[0]}}),r(["initial","tail"],function(n,t){var r="drop"+(t?"":"Right");Ct.prototype[n]=function(){return this.__filtered__?new Ct(this):this[r](1)}}),Ct.prototype.compact=function(){return this.filter(La)},Ct.prototype.find=function(n){return this.filter(n).head()},Ct.prototype.findLast=function(n){return this.reverse().find(n)},Ct.prototype.invokeMap=uu(function(n,t){return"function"==typeof n?new Ct(this):this.map(function(r){
return Ie(r,n,t)})}),Ct.prototype.reject=function(n){return this.filter(Uf(mi(n)))},Ct.prototype.slice=function(n,t){n=kc(n);var r=this;return r.__filtered__&&(n>0||t<0)?new Ct(r):(n<0?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==X&&(t=kc(t),r=t<0?r.dropRight(-t):r.take(t-n)),r)},Ct.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},Ct.prototype.toArray=function(){return this.take(Un)},ue(Ct.prototype,function(n,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),e=/^(?:head|last)$/.test(t),u=Z[e?"take"+("last"==t?"Right":""):t],i=e||/^find/.test(t);
u&&(Z.prototype[t]=function(){var t=this.__wrapped__,o=e?[1]:arguments,f=t instanceof Ct,c=o[0],l=f||bh(t),s=function(n){var t=u.apply(Z,a([n],o));return e&&h?t[0]:t};l&&r&&"function"==typeof c&&1!=c.length&&(f=l=!1);var h=this.__chain__,p=!!this.__actions__.length,_=i&&!h,v=f&&!p;if(!i&&l){t=v?t:new Ct(this);var g=n.apply(t,o);return g.__actions__.push({func:nf,args:[s],thisArg:X}),new Y(g,h)}return _&&v?n.apply(this,o):(g=this.thru(s),_?e?g.value()[0]:g.value():g)})}),r(["pop","push","shift","sort","splice","unshift"],function(n){
var t=_l[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);Z.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(bh(u)?u:[],n)}return this[r](function(r){return t.apply(bh(r)?r:[],n)})}}),ue(Ct.prototype,function(n,t){var r=Z[t];if(r){var e=r.name+"";bl.call(fs,e)||(fs[e]=[]),fs[e].push({name:t,func:r})}}),fs[Qu(X,vn).name]=[{name:"wrapper",func:X}],Ct.prototype.clone=$t,Ct.prototype.reverse=Yt,Ct.prototype.value=Qt,Z.prototype.at=Qs,
Z.prototype.chain=tf,Z.prototype.commit=rf,Z.prototype.next=ef,Z.prototype.plant=of,Z.prototype.reverse=ff,Z.prototype.toJSON=Z.prototype.valueOf=Z.prototype.value=cf,Z.prototype.first=Z.prototype.head,Ul&&(Z.prototype[Ul]=uf),Z},be=de();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(re._=be,define(function(){return be})):ue?((ue.exports=be)._=be,ee._=be):re._=be}).call(this);
/***/ }),
/***/ 47426:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/*!
* mime-db
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2022 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
*/
module.exports = __nccwpck_require__(53765)
/***/ }),
/***/ 43583:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
/*!
* mime-types
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module dependencies.
* @private
*/
var db = __nccwpck_require__(47426)
var extname = (__nccwpck_require__(71017).extname)
/**
* Module variables.
* @private
*/
var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
var TEXT_TYPE_REGEXP = /^text\//i
/**
* Module exports.
* @public
*/
exports.charset = charset
exports.charsets = { lookup: charset }
exports.contentType = contentType
exports.extension = extension
exports.extensions = Object.create(null)
exports.lookup = lookup
exports.types = Object.create(null)
// Populate the extensions/types maps
populateMaps(exports.extensions, exports.types)
/**
* Get the default charset for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function charset (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
var mime = match && db[match[1].toLowerCase()]
if (mime && mime.charset) {
return mime.charset
}
// default text/* to utf-8
if (match && TEXT_TYPE_REGEXP.test(match[1])) {
return 'UTF-8'
}
return false
}
/**
* Create a full Content-Type header given a MIME type or extension.
*
* @param {string} str
* @return {boolean|string}
*/
function contentType (str) {
// TODO: should this even be in this module?
if (!str || typeof str !== 'string') {
return false
}
var mime = str.indexOf('/') === -1
? exports.lookup(str)
: str
if (!mime) {
return false
}
// TODO: use content-type or other module
if (mime.indexOf('charset') === -1) {
var charset = exports.charset(mime)
if (charset) mime += '; charset=' + charset.toLowerCase()
}
return mime
}
/**
* Get the default extension for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function extension (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
// get extensions
var exts = match && exports.extensions[match[1].toLowerCase()]
if (!exts || !exts.length) {
return false
}
return exts[0]
}
/**
* Lookup the MIME type for a file path/extension.
*
* @param {string} path
* @return {boolean|string}
*/
function lookup (path) {
if (!path || typeof path !== 'string') {
return false
}
// get the extension ("ext" or ".ext" or full path)
var extension = extname('x.' + path)
.toLowerCase()
.substr(1)
if (!extension) {
return false
}
return exports.types[extension] || false
}
/**
* Populate the extensions and types maps.
* @private
*/
function populateMaps (extensions, types) {
// source preference (least -> most)
var preference = ['nginx', 'apache', undefined, 'iana']
Object.keys(db).forEach(function forEachMimeType (type) {
var mime = db[type]
var exts = mime.extensions
if (!exts || !exts.length) {
return
}
// mime -> extensions
extensions[type] = exts
// extension -> mime
for (var i = 0; i < exts.length; i++) {
var extension = exts[i]
if (types[extension]) {
var from = preference.indexOf(db[types[extension]].source)
var to = preference.indexOf(mime.source)
if (types[extension] !== 'application/octet-stream' &&
(from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
// skip the remapping
continue
}
}
// set the extension -> mime
types[extension] = type
}
})
}
/***/ }),
/***/ 80900:
/***/ ((module) => {
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
/***/ }),
/***/ 39660:
/***/ ((module) => {
"use strict";
const refs = {
exit: [],
beforeExit: []
}
const functions = {
exit: onExit,
beforeExit: onBeforeExit
}
let registry
function ensureRegistry () {
if (registry === undefined) {
registry = new FinalizationRegistry(clear)
}
}
function install (event) {
if (refs[event].length > 0) {
return
}
process.on(event, functions[event])
}
function uninstall (event) {
if (refs[event].length > 0) {
return
}
process.removeListener(event, functions[event])
if (refs.exit.length === 0 && refs.beforeExit.length === 0) {
registry = undefined
}
}
function onExit () {
callRefs('exit')
}
function onBeforeExit () {
callRefs('beforeExit')
}
function callRefs (event) {
for (const ref of refs[event]) {
const obj = ref.deref()
const fn = ref.fn
// This should always happen, however GC is
// undeterministic so it might not happen.
/* istanbul ignore else */
if (obj !== undefined) {
fn(obj, event)
}
}
refs[event] = []
}
function clear (ref) {
for (const event of ['exit', 'beforeExit']) {
const index = refs[event].indexOf(ref)
refs[event].splice(index, index + 1)
uninstall(event)
}
}
function _register (event, obj, fn) {
if (obj === undefined) {
throw new Error('the object can\'t be undefined')
}
install(event)
const ref = new WeakRef(obj)
ref.fn = fn
ensureRegistry()
registry.register(obj, ref)
refs[event].push(ref)
}
function register (obj, fn) {
_register('exit', obj, fn)
}
function registerBeforeExit (obj, fn) {
_register('beforeExit', obj, fn)
}
function unregister (obj) {
if (registry === undefined) {
return
}
registry.unregister(obj)
for (const event of ['exit', 'beforeExit']) {
refs[event] = refs[event].filter((ref) => {
const _obj = ref.deref()
return _obj && _obj !== obj
})
uninstall(event)
}
}
module.exports = {
register,
registerBeforeExit,
unregister
}
/***/ }),
/***/ 1223:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var wrappy = __nccwpck_require__(62940)
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
Object.defineProperty(Function.prototype, 'onceStrict', {
value: function () {
return onceStrict(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
function onceStrict (fn) {
var f = function () {
if (f.called)
throw new Error(f.onceError)
f.called = true
return f.value = fn.apply(this, arguments)
}
var name = fn.name || 'Function wrapped with `once`'
f.onceError = name + " shouldn't be called more than once"
f.called = false
return f
}
/***/ }),
/***/ 80140:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/*!
* proxy-addr
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
* @public
*/
module.exports = proxyaddr
module.exports.all = alladdrs
module.exports.compile = compile
/**
* Module dependencies.
* @private
*/
var forwarded = __nccwpck_require__(46868)
var ipaddr = __nccwpck_require__(37263)
/**
* Variables.
* @private
*/
var DIGIT_REGEXP = /^[0-9]+$/
var isip = ipaddr.isValid
var parseip = ipaddr.parse
/**
* Pre-defined IP ranges.
* @private
*/
var IP_RANGES = {
linklocal: ['169.254.0.0/16', 'fe80::/10'],
loopback: ['127.0.0.1/8', '::1/128'],
uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']
}
/**
* Get all addresses in the request, optionally stopping
* at the first untrusted.
*
* @param {Object} request
* @param {Function|Array|String} [trust]
* @public
*/
function alladdrs (req, trust) {
// get addresses
var addrs = forwarded(req)
if (!trust) {
// Return all addresses
return addrs
}
if (typeof trust !== 'function') {
trust = compile(trust)
}
for (var i = 0; i < addrs.length - 1; i++) {
if (trust(addrs[i], i)) continue
addrs.length = i + 1
}
return addrs
}
/**
* Compile argument into trust function.
*
* @param {Array|String} val
* @private
*/
function compile (val) {
if (!val) {
throw new TypeError('argument is required')
}
var trust
if (typeof val === 'string') {
trust = [val]
} else if (Array.isArray(val)) {
trust = val.slice()
} else {
throw new TypeError('unsupported trust argument')
}
for (var i = 0; i < trust.length; i++) {
val = trust[i]
if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) {
continue
}
// Splice in pre-defined range
val = IP_RANGES[val]
trust.splice.apply(trust, [i, 1].concat(val))
i += val.length - 1
}
return compileTrust(compileRangeSubnets(trust))
}
/**
* Compile `arr` elements into range subnets.
*
* @param {Array} arr
* @private
*/
function compileRangeSubnets (arr) {
var rangeSubnets = new Array(arr.length)
for (var i = 0; i < arr.length; i++) {
rangeSubnets[i] = parseipNotation(arr[i])
}
return rangeSubnets
}
/**
* Compile range subnet array into trust function.
*
* @param {Array} rangeSubnets
* @private
*/
function compileTrust (rangeSubnets) {
// Return optimized function based on length
var len = rangeSubnets.length
return len === 0
? trustNone
: len === 1
? trustSingle(rangeSubnets[0])
: trustMulti(rangeSubnets)
}
/**
* Parse IP notation string into range subnet.
*
* @param {String} note
* @private
*/
function parseipNotation (note) {
var pos = note.lastIndexOf('/')
var str = pos !== -1
? note.substring(0, pos)
: note
if (!isip(str)) {
throw new TypeError('invalid IP address: ' + str)
}
var ip = parseip(str)
if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
// Store as IPv4
ip = ip.toIPv4Address()
}
var max = ip.kind() === 'ipv6'
? 128
: 32
var range = pos !== -1
? note.substring(pos + 1, note.length)
: null
if (range === null) {
range = max
} else if (DIGIT_REGEXP.test(range)) {
range = parseInt(range, 10)
} else if (ip.kind() === 'ipv4' && isip(range)) {
range = parseNetmask(range)
} else {
range = null
}
if (range <= 0 || range > max) {
throw new TypeError('invalid range on address: ' + note)
}
return [ip, range]
}
/**
* Parse netmask string into CIDR range.
*
* @param {String} netmask
* @private
*/
function parseNetmask (netmask) {
var ip = parseip(netmask)
var kind = ip.kind()
return kind === 'ipv4'
? ip.prefixLengthFromSubnetMask()
: null
}
/**
* Determine address of proxied request.
*
* @param {Object} request
* @param {Function|Array|String} trust
* @public
*/
function proxyaddr (req, trust) {
if (!req) {
throw new TypeError('req argument is required')
}
if (!trust) {
throw new TypeError('trust argument is required')
}
var addrs = alladdrs(req, trust)
var addr = addrs[addrs.length - 1]
return addr
}
/**
* Static trust function to trust nothing.
*
* @private
*/
function trustNone () {
return false
}
/**
* Compile trust function for multiple subnets.
*
* @param {Array} subnets
* @private
*/
function trustMulti (subnets) {
return function trust (addr) {
if (!isip(addr)) return false
var ip = parseip(addr)
var ipconv
var kind = ip.kind()
for (var i = 0; i < subnets.length; i++) {
var subnet = subnets[i]
var subnetip = subnet[0]
var subnetkind = subnetip.kind()
var subnetrange = subnet[1]
var trusted = ip
if (kind !== subnetkind) {
if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) {
// Incompatible IP addresses
continue
}
if (!ipconv) {
// Convert IP to match subnet IP kind
ipconv = subnetkind === 'ipv4'
? ip.toIPv4Address()
: ip.toIPv4MappedAddress()
}
trusted = ipconv
}
if (trusted.match(subnetip, subnetrange)) {
return true
}
}
return false
}
}
/**
* Compile trust function for single subnet.
*
* @param {Object} subnet
* @private
*/
function trustSingle (subnet) {
var subnetip = subnet[0]
var subnetkind = subnetip.kind()
var subnetisipv4 = subnetkind === 'ipv4'
var subnetrange = subnet[1]
return function trust (addr) {
if (!isip(addr)) return false
var ip = parseip(addr)
var kind = ip.kind()
if (kind !== subnetkind) {
if (subnetisipv4 && !ip.isIPv4MappedAddress()) {
// Incompatible IP addresses
return false
}
// Convert IP to match subnet IP kind
ip = subnetisipv4
? ip.toIPv4Address()
: ip.toIPv4MappedAddress()
}
return ip.match(subnetip, subnetrange)
}
}
/***/ }),
/***/ 63329:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var parseUrl = (__nccwpck_require__(57310).parse);
var DEFAULT_PORTS = {
ftp: 21,
gopher: 70,
http: 80,
https: 443,
ws: 80,
wss: 443,
};
var stringEndsWith = String.prototype.endsWith || function(s) {
return s.length <= this.length &&
this.indexOf(s, this.length - s.length) !== -1;
};
/**
* @param {string|object} url - The URL, or the result from url.parse.
* @return {string} The URL of the proxy that should handle the request to the
* given URL. If no proxy is set, this will be an empty string.
*/
function getProxyForUrl(url) {
var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {};
var proto = parsedUrl.protocol;
var hostname = parsedUrl.host;
var port = parsedUrl.port;
if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
return ''; // Don't proxy URLs without a valid scheme or host.
}
proto = proto.split(':', 1)[0];
// Stripping ports in this way instead of using parsedUrl.hostname to make
// sure that the brackets around IPv6 addresses are kept.
hostname = hostname.replace(/:\d*$/, '');
port = parseInt(port) || DEFAULT_PORTS[proto] || 0;
if (!shouldProxy(hostname, port)) {
return ''; // Don't proxy URLs that match NO_PROXY.
}
var proxy =
getEnv('npm_config_' + proto + '_proxy') ||
getEnv(proto + '_proxy') ||
getEnv('npm_config_proxy') ||
getEnv('all_proxy');
if (proxy && proxy.indexOf('://') === -1) {
// Missing scheme in proxy, default to the requested URL's scheme.
proxy = proto + '://' + proxy;
}
return proxy;
}
/**
* Determines whether a given URL should be proxied.
*
* @param {string} hostname - The host name of the URL.
* @param {number} port - The effective port of the URL.
* @returns {boolean} Whether the given URL should be proxied.
* @private
*/
function shouldProxy(hostname, port) {
var NO_PROXY =
(getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase();
if (!NO_PROXY) {
return true; // Always proxy if NO_PROXY is not set.
}
if (NO_PROXY === '*') {
return false; // Never proxy if wildcard is set.
}
return NO_PROXY.split(/[,\s]/).every(function(proxy) {
if (!proxy) {
return true; // Skip zero-length hosts.
}
var parsedProxy = proxy.match(/^(.+):(\d+)$/);
var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
if (parsedProxyPort && parsedProxyPort !== port) {
return true; // Skip if ports don't match.
}
if (!/^[.*]/.test(parsedProxyHostname)) {
// No wildcards, so stop proxying if there is an exact match.
return hostname !== parsedProxyHostname;
}
if (parsedProxyHostname.charAt(0) === '*') {
// Remove leading wildcard.
parsedProxyHostname = parsedProxyHostname.slice(1);
}
// Stop proxying if the hostname ends with the no_proxy host.
return !stringEndsWith.call(hostname, parsedProxyHostname);
});
}
/**
* Get the value for an environment variable.
*
* @param {string} key - The name of the environment variable.
* @return {string} The value of the environment variable.
* @private
*/
function getEnv(key) {
return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
}
exports.getProxyForUrl = getProxyForUrl;
/***/ }),
/***/ 5933:
/***/ ((module) => {
"use strict";
function tryStringify (o) {
try { return JSON.stringify(o) } catch(e) { return '"[Circular]"' }
}
module.exports = format
function format(f, args, opts) {
var ss = (opts && opts.stringify) || tryStringify
var offset = 1
if (typeof f === 'object' && f !== null) {
var len = args.length + offset
if (len === 1) return f
var objects = new Array(len)
objects[0] = ss(f)
for (var index = 1; index < len; index++) {
objects[index] = ss(args[index])
}
return objects.join(' ')
}
if (typeof f !== 'string') {
return f
}
var argLen = args.length
if (argLen === 0) return f
var str = ''
var a = 1 - offset
var lastPos = -1
var flen = (f && f.length) || 0
for (var i = 0; i < flen;) {
if (f.charCodeAt(i) === 37 && i + 1 < flen) {
lastPos = lastPos > -1 ? lastPos : 0
switch (f.charCodeAt(i + 1)) {
case 100: // 'd'
case 102: // 'f'
if (a >= argLen)
break
if (args[a] == null) break
if (lastPos < i)
str += f.slice(lastPos, i)
str += Number(args[a])
lastPos = i + 2
i++
break
case 105: // 'i'
if (a >= argLen)
break
if (args[a] == null) break
if (lastPos < i)
str += f.slice(lastPos, i)
str += Math.floor(Number(args[a]))
lastPos = i + 2
i++
break
case 79: // 'O'
case 111: // 'o'
case 106: // 'j'
if (a >= argLen)
break
if (args[a] === undefined) break
if (lastPos < i)
str += f.slice(lastPos, i)
var type = typeof args[a]
if (type === 'string') {
str += '\'' + args[a] + '\''
lastPos = i + 2
i++
break
}
if (type === 'function') {
str += args[a].name || '<anonymous>'
lastPos = i + 2
i++
break
}
str += ss(args[a])
lastPos = i + 2
i++
break
case 115: // 's'
if (a >= argLen)
break
if (lastPos < i)
str += f.slice(lastPos, i)
str += String(args[a])
lastPos = i + 2
i++
break
case 37: // '%'
if (lastPos < i)
str += f.slice(lastPos, i)
str += '%'
lastPos = i + 2
i++
a--
break
}
++a
}
++i
}
if (lastPos === -1)
return f
else if (lastPos < flen) {
str += f.slice(lastPos)
}
return str
}
/***/ }),
/***/ 7703:
/***/ (function(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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.types = void 0;
/* istanbul ignore file */
const types_1 = __nccwpck_require__(19345);
Object.defineProperty(exports, "types", ({ enumerable: true, get: function () { return types_1.types; } }));
__exportStar(__nccwpck_require__(90391), exports);
__exportStar(__nccwpck_require__(35524), exports);
const tokenizer_1 = __nccwpck_require__(90391);
const reconstruct_1 = __nccwpck_require__(35524);
__exportStar(__nccwpck_require__(19345), exports);
exports["default"] = tokenizer_1.tokenizer;
module.exports = tokenizer_1.tokenizer;
module.exports.types = types_1.types;
module.exports.reconstruct = reconstruct_1.reconstruct;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 35524:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reconstruct = void 0;
const types_1 = __nccwpck_require__(19345);
const write_set_tokens_1 = __nccwpck_require__(79036);
const reduceStack = (stack) => stack.map(exports.reconstruct).join('');
const createAlternate = (token) => {
if ('options' in token) {
return token.options.map(reduceStack).join('|');
}
else if ('stack' in token) {
return reduceStack(token.stack);
}
else {
throw new Error(`options or stack must be Root or Group token`);
}
};
exports.reconstruct = (token) => {
switch (token.type) {
case types_1.types.ROOT:
return createAlternate(token);
case types_1.types.CHAR: {
const c = String.fromCharCode(token.value);
// Note that the escaping for characters inside classes is handled
// in the write-set-tokens module so '-' and ']' are not escaped here
return (/[[\\{}$^.|?*+()]/.test(c) ? '\\' : '') + c;
}
case types_1.types.POSITION:
if (token.value === '^' || token.value === '$') {
return token.value;
}
else {
return `\\${token.value}`;
}
case types_1.types.REFERENCE:
return `\\${token.value}`;
case types_1.types.SET:
return write_set_tokens_1.writeSetTokens(token);
case types_1.types.GROUP: {
// Check token.remember
const prefix = token.remember ? '' :
token.followedBy ? '?=' :
token.notFollowedBy ? '?!' :
'?:';
return `(${prefix}${createAlternate(token)})`;
}
case types_1.types.REPETITION: {
const { min, max } = token;
let endWith;
if (min === 0 && max === 1) {
endWith = '?';
}
else if (min === 1 && max === Infinity) {
endWith = '+';
}
else if (min === 0 && max === Infinity) {
endWith = '*';
}
else if (max === Infinity) {
endWith = `{${min},}`;
}
else if (min === max) {
endWith = `{${min}}`;
}
else {
endWith = `{${min},${max}}`;
}
return `${exports.reconstruct(token.value)}${endWith}`;
}
case types_1.types.RANGE:
return `${write_set_tokens_1.setChar(token.from)}-${write_set_tokens_1.setChar(token.to)}`;
default:
throw new Error(`Invalid token type ${token}`);
}
};
//# sourceMappingURL=reconstruct.js.map
/***/ }),
/***/ 89294:
/***/ (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;
});
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.NOTANYCHAR = exports.WHITESPACE = exports.WORDS = exports.INTS = void 0;
const Sets = __importStar(__nccwpck_require__(78401));
const types_1 = __nccwpck_require__(19345);
function setToLookup(tokens) {
let lookup = {};
let len = 0;
for (const token of tokens) {
if (token.type === types_1.types.CHAR) {
lookup[token.value] = true;
}
// Note this is in an if statement because
// the SetTokens type is (Char | Range | Set)[]
// so a type error is thrown if it is not.
// If the SetTokens type is modified the if statement
// can be removed
if (token.type === types_1.types.RANGE) {
lookup[`${token.from}-${token.to}`] = true;
}
len += 1;
}
return {
lookup: () => (Object.assign({}, lookup)),
len,
};
}
exports.INTS = setToLookup(Sets.ints().set);
exports.WORDS = setToLookup(Sets.words().set);
exports.WHITESPACE = setToLookup(Sets.whitespace().set);
exports.NOTANYCHAR = setToLookup(Sets.anyChar().set);
//# sourceMappingURL=sets-lookup.js.map
/***/ }),
/***/ 78401:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.anyChar = exports.notWhitespace = exports.whitespace = exports.notInts = exports.ints = exports.notWords = exports.words = void 0;
const types_1 = __nccwpck_require__(19345);
const INTS = () => [{ type: types_1.types.RANGE, from: 48, to: 57 }];
const WORDS = () => [
{ type: types_1.types.CHAR, value: 95 },
{ type: types_1.types.RANGE, from: 97, to: 122 },
{ type: types_1.types.RANGE, from: 65, to: 90 },
{ type: types_1.types.RANGE, from: 48, to: 57 },
];
const WHITESPACE = () => [
{ type: types_1.types.CHAR, value: 9 },
{ type: types_1.types.CHAR, value: 10 },
{ type: types_1.types.CHAR, value: 11 },
{ type: types_1.types.CHAR, value: 12 },
{ type: types_1.types.CHAR, value: 13 },
{ type: types_1.types.CHAR, value: 32 },
{ type: types_1.types.CHAR, value: 160 },
{ type: types_1.types.CHAR, value: 5760 },
{ type: types_1.types.RANGE, from: 8192, to: 8202 },
{ type: types_1.types.CHAR, value: 8232 },
{ type: types_1.types.CHAR, value: 8233 },
{ type: types_1.types.CHAR, value: 8239 },
{ type: types_1.types.CHAR, value: 8287 },
{ type: types_1.types.CHAR, value: 12288 },
{ type: types_1.types.CHAR, value: 65279 },
];
const NOTANYCHAR = () => [
{ type: types_1.types.CHAR, value: 10 },
{ type: types_1.types.CHAR, value: 13 },
{ type: types_1.types.CHAR, value: 8232 },
{ type: types_1.types.CHAR, value: 8233 },
];
// Predefined class objects.
exports.words = () => ({ type: types_1.types.SET, set: WORDS(), not: false });
exports.notWords = () => ({ type: types_1.types.SET, set: WORDS(), not: true });
exports.ints = () => ({ type: types_1.types.SET, set: INTS(), not: false });
exports.notInts = () => ({ type: types_1.types.SET, set: INTS(), not: true });
exports.whitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: false });
exports.notWhitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: true });
exports.anyChar = () => ({ type: types_1.types.SET, set: NOTANYCHAR(), not: true });
//# sourceMappingURL=sets.js.map
/***/ }),
/***/ 90391:
/***/ (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;
});
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.tokenizer = void 0;
const util = __importStar(__nccwpck_require__(77638));
const types_1 = __nccwpck_require__(19345);
const sets = __importStar(__nccwpck_require__(78401));
/**
* Tokenizes a regular expression (that is currently a string)
* @param {string} regexpStr String of regular expression to be tokenized
*
* @returns {Root}
*/
exports.tokenizer = (regexpStr) => {
let i = 0, c;
let start = { type: types_1.types.ROOT, stack: [] };
// Keep track of last clause/group and stack.
let lastGroup = start;
let last = start.stack;
let groupStack = [];
let referenceQueue = [];
let groupCount = 0;
const repeatErr = (col) => {
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Nothing to repeat at column ${col - 1}`);
};
// Decode a few escaped characters.
let str = util.strToChars(regexpStr);
// Iterate through each character in string.
while (i < str.length) {
switch (c = str[i++]) {
// Handle escaped characters, inclues a few sets.
case '\\':
if (i === str.length) {
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: \\ at end of pattern`);
}
switch (c = str[i++]) {
case 'b':
last.push({ type: types_1.types.POSITION, value: 'b' });
break;
case 'B':
last.push({ type: types_1.types.POSITION, value: 'B' });
break;
case 'w':
last.push(sets.words());
break;
case 'W':
last.push(sets.notWords());
break;
case 'd':
last.push(sets.ints());
break;
case 'D':
last.push(sets.notInts());
break;
case 's':
last.push(sets.whitespace());
break;
case 'S':
last.push(sets.notWhitespace());
break;
default:
// Check if c is integer.
// In which case it's a reference.
if (/\d/.test(c)) {
let digits = c;
while (i < str.length && /\d/.test(str[i])) {
digits += str[i++];
}
let value = parseInt(digits, 10);
const reference = { type: types_1.types.REFERENCE, value };
last.push(reference);
referenceQueue.push({ reference, stack: last, index: last.length - 1 });
// Escaped character.
}
else {
last.push({ type: types_1.types.CHAR, value: c.charCodeAt(0) });
}
}
break;
// Positionals.
case '^':
last.push({ type: types_1.types.POSITION, value: '^' });
break;
case '$':
last.push({ type: types_1.types.POSITION, value: '$' });
break;
// Handle custom sets.
case '[': {
// Check if this class is 'anti' i.e. [^abc].
let not;
if (str[i] === '^') {
not = true;
i++;
}
else {
not = false;
}
// Get all the characters in class.
let classTokens = util.tokenizeClass(str.slice(i), regexpStr);
// Increase index by length of class.
i += classTokens[1];
last.push({
type: types_1.types.SET,
set: classTokens[0],
not,
});
break;
}
// Class of any character except \n.
case '.':
last.push(sets.anyChar());
break;
// Push group onto stack.
case '(': {
// Create group.
let group = {
type: types_1.types.GROUP,
stack: [],
remember: true,
};
// If if this is a special kind of group.
if (str[i] === '?') {
c = str[i + 1];
i += 2;
// Match if followed by.
if (c === '=') {
group.followedBy = true;
// Match if not followed by.
}
else if (c === '!') {
group.notFollowedBy = true;
}
else if (c !== ':') {
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Invalid group, character '${c}'` +
` after '?' at column ${i - 1}`);
}
group.remember = false;
}
else {
groupCount += 1;
}
// Insert subgroup into current group stack.
last.push(group);
// Remember the current group for when the group closes.
groupStack.push(lastGroup);
// Make this new group the current group.
lastGroup = group;
last = group.stack;
break;
}
// Pop group out of stack.
case ')':
if (groupStack.length === 0) {
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unmatched ) at column ${i - 1}`);
}
lastGroup = groupStack.pop();
// Check if this group has a PIPE.
// To get back the correct last stack.
last = lastGroup.options ?
lastGroup.options[lastGroup.options.length - 1] :
lastGroup.stack;
break;
// Use pipe character to give more choices.
case '|': {
// Create array where options are if this is the first PIPE
// in this clause.
if (!lastGroup.options) {
lastGroup.options = [lastGroup.stack];
delete lastGroup.stack;
}
// Create a new stack and add to options for rest of clause.
let stack = [];
lastGroup.options.push(stack);
last = stack;
break;
}
// Repetition.
// For every repetition, remove last element from last stack
// then insert back a RANGE object.
// This design is chosen because there could be more than
// one repetition symbols in a regex i.e. `a?+{2,3}`.
case '{': {
let rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
if (rs !== null) {
if (last.length === 0) {
repeatErr(i);
}
min = parseInt(rs[1], 10);
max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
i += rs[0].length;
last.push({
type: types_1.types.REPETITION,
min,
max,
value: last.pop(),
});
}
else {
last.push({
type: types_1.types.CHAR,
value: 123,
});
}
break;
}
case '?':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types_1.types.REPETITION,
min: 0,
max: 1,
value: last.pop(),
});
break;
case '+':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types_1.types.REPETITION,
min: 1,
max: Infinity,
value: last.pop(),
});
break;
case '*':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types_1.types.REPETITION,
min: 0,
max: Infinity,
value: last.pop(),
});
break;
// Default is a character that is not `\[](){}?+*^$`.
default:
last.push({
type: types_1.types.CHAR,
value: c.charCodeAt(0),
});
}
}
// Check if any groups have not been closed.
if (groupStack.length !== 0) {
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated group`);
}
updateReferences(referenceQueue, groupCount);
return start;
};
/**
* This is a side effecting function that changes references to chars
* if there are not enough capturing groups to reference
* See: https://github.com/fent/ret.js/pull/39#issuecomment-1006475703
* See: https://github.com/fent/ret.js/issues/38
* @param {(Reference | Char)[]} referenceQueue
* @param {number} groupCount
* @returns {void}
*/
function updateReferences(referenceQueue, groupCount) {
// Note: We go through the queue in reverse order so
// that index we use is correct even if we have to add
// multiple tokens to one stack
for (const elem of referenceQueue.reverse()) {
if (groupCount < elem.reference.value) {
// If there is nothing to reference then turn this into a char token
elem.reference.type = types_1.types.CHAR;
const valueString = elem.reference.value.toString();
elem.reference.value = parseInt(valueString, 8);
// If the number is not octal then we need to create multiple tokens
// https://github.com/fent/ret.js/pull/39#issuecomment-1008229226
if (!/^[0-7]+$/.test(valueString)) {
let i = 0;
while (valueString[i] !== '8' && valueString[i] !== '9') {
i += 1;
}
if (i === 0) {
// Handling case when escaped number starts with 8 or 9
elem.reference.value = valueString.charCodeAt(0);
i += 1;
}
else {
// If the escaped number does not start with 8 or 9, then all
// 0-7 digits before the first 8/9 form the first character code
// see: https://github.com/fent/ret.js/pull/39#discussion_r780747085
elem.reference.value = parseInt(valueString.slice(0, i), 8);
}
if (valueString.length > i) {
const tail = elem.stack.splice(elem.index + 1);
for (const char of valueString.slice(i)) {
elem.stack.push({
type: types_1.types.CHAR,
value: char.charCodeAt(0),
});
}
elem.stack.push(...tail);
}
}
}
}
}
//# sourceMappingURL=tokenizer.js.map
/***/ }),
/***/ 19345:
/***/ (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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__nccwpck_require__(67333), exports);
__exportStar(__nccwpck_require__(7946), exports);
__exportStar(__nccwpck_require__(72347), exports);
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 72347:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=set-lookup.js.map
/***/ }),
/***/ 67333:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=tokens.js.map
/***/ }),
/***/ 7946:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.types = void 0;
var types;
(function (types) {
types[types["ROOT"] = 0] = "ROOT";
types[types["GROUP"] = 1] = "GROUP";
types[types["POSITION"] = 2] = "POSITION";
types[types["SET"] = 3] = "SET";
types[types["RANGE"] = 4] = "RANGE";
types[types["REPETITION"] = 5] = "REPETITION";
types[types["REFERENCE"] = 6] = "REFERENCE";
types[types["CHAR"] = 7] = "CHAR";
})(types = exports.types || (exports.types = {}));
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 77638:
/***/ (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;
});
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.tokenizeClass = exports.strToChars = void 0;
const types_1 = __nccwpck_require__(19345);
const sets = __importStar(__nccwpck_require__(78401));
const CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
/**
* Finds character representations in str and convert all to
* their respective characters.
*
* @param {string} str
* @returns {string}
*/
exports.strToChars = (str) => {
const charsRegex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;
return str.replace(charsRegex, (s, b, lbs, a16, b16, dctrl, eslsh) => {
if (lbs) {
return s;
}
let code = b ? 8 :
a16 ? parseInt(a16, 16) :
b16 ? parseInt(b16, 16) :
dctrl ? CTRL.indexOf(dctrl) : {
0: 0,
t: 9,
n: 10,
v: 11,
f: 12,
r: 13,
}[eslsh];
let c = String.fromCharCode(code);
// Escape special regex characters.
return /[[\]{}^$.|?*+()]/.test(c) ? `\\${c}` : c;
});
};
/**
* Turns class into tokens
* reads str until it encounters a ] not preceeded by a \
*
* @param {string} str
* @param {string} regexpStr
* @returns {Array.<Array.<Object>, number>}
*/
exports.tokenizeClass = (str, regexpStr) => {
var _a, _b, _c, _d, _e, _f, _g;
let tokens = [], rs, c;
const regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;
while ((rs = regexp.exec(str)) !== null) {
const p = (_g = (_f = (_e = (_d = (_c = (_b = (_a = (rs[1] && sets.words())) !== null && _a !== void 0 ? _a : (rs[2] && sets.ints())) !== null && _b !== void 0 ? _b : (rs[3] && sets.whitespace())) !== null && _c !== void 0 ? _c : (rs[4] && sets.notWords())) !== null && _d !== void 0 ? _d : (rs[5] && sets.notInts())) !== null && _e !== void 0 ? _e : (rs[6] && sets.notWhitespace())) !== null && _f !== void 0 ? _f : (rs[7] && {
type: types_1.types.RANGE,
from: (rs[8] || rs[9]).charCodeAt(0),
to: (c = rs[10]).charCodeAt(c.length - 1),
})) !== null && _g !== void 0 ? _g : ((c = rs[16]) && { type: types_1.types.CHAR, value: c.charCodeAt(0) });
if (p) {
tokens.push(p);
}
else {
return [tokens, regexp.lastIndex];
}
}
throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated character class`);
};
//# sourceMappingURL=util.js.map
/***/ }),
/***/ 79036:
/***/ (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;
});
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.writeSetTokens = exports.setChar = void 0;
const types_1 = __nccwpck_require__(19345);
const sets = __importStar(__nccwpck_require__(89294));
/**
* Takes character code and returns character to be displayed in a set
* @param {number} charCode Character code of set element
* @returns {string} The string for the sets character
*/
function setChar(charCode) {
return charCode === 94 ? '\\^' :
charCode === 92 ? '\\\\' :
charCode === 93 ? '\\]' :
charCode === 45 ? '\\-' :
String.fromCharCode(charCode);
}
exports.setChar = setChar;
/**
* Test if a character set matches a 'set-lookup'
* @param {SetTokens} set The set to be tested
* @param {SetLookup} param The predefined 'set-lookup' & the number of elements in the lookup
* @returns {boolean} True if the character set corresponds to the 'set-lookup'
*/
function isSameSet(set, { lookup, len }) {
// If the set and the lookup are not of the same length
// then we immediately know that the lookup will be false
if (len !== set.length) {
return false;
}
const map = lookup();
for (const elem of set) {
if (elem.type === types_1.types.SET) {
return false;
}
const key = elem.type === types_1.types.CHAR ? elem.value : `${elem.from}-${elem.to}`;
if (map[key]) {
map[key] = false;
}
else {
return false;
}
}
return true;
}
/**
* Writes the tokens for a set
* @param {Set} set The set to display
* @param {boolean} isNested Whether the token is nested inside another set token
* @returns {string} The tokens for the set
*/
function writeSetTokens(set, isNested = false) {
if (isSameSet(set.set, sets.INTS)) {
return set.not ? '\\D' : '\\d';
}
if (isSameSet(set.set, sets.WORDS)) {
return set.not ? '\\W' : '\\w';
}
// Notanychar is only relevant when not nested inside another set token
if (set.not && isSameSet(set.set, sets.NOTANYCHAR)) {
return '.';
}
if (isSameSet(set.set, sets.WHITESPACE)) {
return set.not ? '\\S' : '\\s';
}
let tokenString = '';
for (let i = 0; i < set.set.length; i++) {
const subset = set.set[i];
tokenString += writeSetToken(subset);
}
const contents = `${set.not ? '^' : ''}${tokenString}`;
return isNested ? contents : `[${contents}]`;
}
exports.writeSetTokens = writeSetTokens;
/**
* Writes a token within a set
* @param {Range | Char | Set} set The set token to display
* @returns {string} The token as a string
*/
function writeSetToken(set) {
if (set.type === types_1.types.CHAR) {
return setChar(set.value);
}
else if (set.type === types_1.types.RANGE) {
return `${setChar(set.from)}-${setChar(set.to)}`;
}
return writeSetTokens(set, true);
}
//# sourceMappingURL=write-set-tokens.js.map
/***/ }),
/***/ 32113:
/***/ ((module) => {
"use strict";
function reusify (Constructor) {
var head = new Constructor()
var tail = head
function get () {
var current = head
if (current.next) {
head = current.next
} else {
head = new Constructor()
tail = head
}
current.next = null
return current
}
function release (obj) {
tail.next = obj
tail = obj
}
return {
get: get,
release: release
}
}
module.exports = reusify
/***/ }),
/***/ 11868:
/***/ ((module) => {
"use strict";
module.exports = rfdc
function copyBuffer (cur) {
if (cur instanceof Buffer) {
return Buffer.from(cur)
}
return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length)
}
function rfdc (opts) {
opts = opts || {}
if (opts.circles) return rfdcCircles(opts)
const constructorHandlers = new Map()
constructorHandlers.set(Date, (o) => new Date(o))
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)))
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)))
if (opts.constructorHandlers) {
for (const handler of opts.constructorHandlers) {
constructorHandlers.set(handler[0], handler[1])
}
}
let handler = null
return opts.proto ? cloneProto : clone
function cloneArray (a, fn) {
const keys = Object.keys(a)
const a2 = new Array(keys.length)
for (let i = 0; i < keys.length; i++) {
const k = keys[i]
const cur = a[k]
if (typeof cur !== 'object' || cur === null) {
a2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
a2[k] = handler(cur, fn)
} else if (ArrayBuffer.isView(cur)) {
a2[k] = copyBuffer(cur)
} else {
a2[k] = fn(cur)
}
}
return a2
}
function clone (o) {
if (typeof o !== 'object' || o === null) return o
if (Array.isArray(o)) return cloneArray(o, clone)
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
return handler(o, clone)
}
const o2 = {}
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue
const cur = o[k]
if (typeof cur !== 'object' || cur === null) {
o2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
o2[k] = handler(cur, clone)
} else if (ArrayBuffer.isView(cur)) {
o2[k] = copyBuffer(cur)
} else {
o2[k] = clone(cur)
}
}
return o2
}
function cloneProto (o) {
if (typeof o !== 'object' || o === null) return o
if (Array.isArray(o)) return cloneArray(o, cloneProto)
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
return handler(o, cloneProto)
}
const o2 = {}
for (const k in o) {
const cur = o[k]
if (typeof cur !== 'object' || cur === null) {
o2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
o2[k] = handler(cur, cloneProto)
} else if (ArrayBuffer.isView(cur)) {
o2[k] = copyBuffer(cur)
} else {
o2[k] = cloneProto(cur)
}
}
return o2
}
}
function rfdcCircles (opts) {
const refs = []
const refsNew = []
const constructorHandlers = new Map()
constructorHandlers.set(Date, (o) => new Date(o))
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)))
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)))
if (opts.constructorHandlers) {
for (const handler of opts.constructorHandlers) {
constructorHandlers.set(handler[0], handler[1])
}
}
let handler = null
return opts.proto ? cloneProto : clone
function cloneArray (a, fn) {
const keys = Object.keys(a)
const a2 = new Array(keys.length)
for (let i = 0; i < keys.length; i++) {
const k = keys[i]
const cur = a[k]
if (typeof cur !== 'object' || cur === null) {
a2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
a2[k] = handler(cur, fn)
} else if (ArrayBuffer.isView(cur)) {
a2[k] = copyBuffer(cur)
} else {
const index = refs.indexOf(cur)
if (index !== -1) {
a2[k] = refsNew[index]
} else {
a2[k] = fn(cur)
}
}
}
return a2
}
function clone (o) {
if (typeof o !== 'object' || o === null) return o
if (Array.isArray(o)) return cloneArray(o, clone)
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
return handler(o, clone)
}
const o2 = {}
refs.push(o)
refsNew.push(o2)
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue
const cur = o[k]
if (typeof cur !== 'object' || cur === null) {
o2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
o2[k] = handler(cur, clone)
} else if (ArrayBuffer.isView(cur)) {
o2[k] = copyBuffer(cur)
} else {
const i = refs.indexOf(cur)
if (i !== -1) {
o2[k] = refsNew[i]
} else {
o2[k] = clone(cur)
}
}
}
refs.pop()
refsNew.pop()
return o2
}
function cloneProto (o) {
if (typeof o !== 'object' || o === null) return o
if (Array.isArray(o)) return cloneArray(o, cloneProto)
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
return handler(o, cloneProto)
}
const o2 = {}
refs.push(o)
refsNew.push(o2)
for (const k in o) {
const cur = o[k]
if (typeof cur !== 'object' || cur === null) {
o2[k] = cur
} else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
o2[k] = handler(cur, cloneProto)
} else if (ArrayBuffer.isView(cur)) {
o2[k] = copyBuffer(cur)
} else {
const i = refs.indexOf(cur)
if (i !== -1) {
o2[k] = refsNew[i]
} else {
o2[k] = cloneProto(cur)
}
}
}
refs.pop()
refsNew.pop()
return o2
}
}
/***/ }),
/***/ 1752:
/***/ (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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.interval = exports.iif = exports.generate = exports.fromEventPattern = exports.fromEvent = exports.from = exports.forkJoin = exports.empty = exports.defer = exports.connectable = exports.concat = exports.combineLatest = exports.bindNodeCallback = exports.bindCallback = exports.UnsubscriptionError = exports.TimeoutError = exports.SequenceError = exports.ObjectUnsubscribedError = exports.NotFoundError = exports.EmptyError = exports.ArgumentOutOfRangeError = exports.firstValueFrom = exports.lastValueFrom = exports.isObservable = exports.identity = exports.noop = exports.pipe = exports.NotificationKind = exports.Notification = exports.Subscriber = exports.Subscription = exports.Scheduler = exports.VirtualAction = exports.VirtualTimeScheduler = exports.animationFrameScheduler = exports.animationFrame = exports.queueScheduler = exports.queue = exports.asyncScheduler = exports.async = exports.asapScheduler = exports.asap = exports.AsyncSubject = exports.ReplaySubject = exports.BehaviorSubject = exports.Subject = exports.animationFrames = exports.observable = exports.ConnectableObservable = exports.Observable = void 0;
exports.filter = exports.expand = exports.exhaustMap = exports.exhaustAll = exports.exhaust = exports.every = exports.endWith = exports.elementAt = exports.distinctUntilKeyChanged = exports.distinctUntilChanged = exports.distinct = exports.dematerialize = exports.delayWhen = exports.delay = exports.defaultIfEmpty = exports.debounceTime = exports.debounce = exports.count = exports.connect = exports.concatWith = exports.concatMapTo = exports.concatMap = exports.concatAll = exports.combineLatestWith = exports.combineLatestAll = exports.combineAll = exports.catchError = exports.bufferWhen = exports.bufferToggle = exports.bufferTime = exports.bufferCount = exports.buffer = exports.auditTime = exports.audit = exports.config = exports.NEVER = exports.EMPTY = exports.scheduled = exports.zip = exports.using = exports.timer = exports.throwError = exports.range = exports.race = exports.partition = exports.pairs = exports.onErrorResumeNext = exports.of = exports.never = exports.merge = void 0;
exports.switchMap = exports.switchAll = exports.subscribeOn = exports.startWith = exports.skipWhile = exports.skipUntil = exports.skipLast = exports.skip = exports.single = exports.shareReplay = exports.share = exports.sequenceEqual = exports.scan = exports.sampleTime = exports.sample = exports.refCount = exports.retryWhen = exports.retry = exports.repeatWhen = exports.repeat = exports.reduce = exports.raceWith = exports.publishReplay = exports.publishLast = exports.publishBehavior = exports.publish = exports.pluck = exports.pairwise = exports.onErrorResumeNextWith = exports.observeOn = exports.multicast = exports.min = exports.mergeWith = exports.mergeScan = exports.mergeMapTo = exports.mergeMap = exports.flatMap = exports.mergeAll = exports.max = exports.materialize = exports.mapTo = exports.map = exports.last = exports.isEmpty = exports.ignoreElements = exports.groupBy = exports.first = exports.findIndex = exports.find = exports.finalize = void 0;
exports.zipWith = exports.zipAll = exports.withLatestFrom = exports.windowWhen = exports.windowToggle = exports.windowTime = exports.windowCount = exports.window = exports.toArray = exports.timestamp = exports.timeoutWith = exports.timeout = exports.timeInterval = exports.throwIfEmpty = exports.throttleTime = exports.throttle = exports.tap = exports.takeWhile = exports.takeUntil = exports.takeLast = exports.take = exports.switchScan = exports.switchMapTo = void 0;
var Observable_1 = __nccwpck_require__(53014);
Object.defineProperty(exports, "Observable", ({ enumerable: true, get: function () { return Observable_1.Observable; } }));
var ConnectableObservable_1 = __nccwpck_require__(30420);
Object.defineProperty(exports, "ConnectableObservable", ({ enumerable: true, get: function () { return ConnectableObservable_1.ConnectableObservable; } }));
var observable_1 = __nccwpck_require__(17186);
Object.defineProperty(exports, "observable", ({ enumerable: true, get: function () { return observable_1.observable; } }));
var animationFrames_1 = __nccwpck_require__(38197);
Object.defineProperty(exports, "animationFrames", ({ enumerable: true, get: function () { return animationFrames_1.animationFrames; } }));
var Subject_1 = __nccwpck_require__(49944);
Object.defineProperty(exports, "Subject", ({ enumerable: true, get: function () { return Subject_1.Subject; } }));
var BehaviorSubject_1 = __nccwpck_require__(23473);
Object.defineProperty(exports, "BehaviorSubject", ({ enumerable: true, get: function () { return BehaviorSubject_1.BehaviorSubject; } }));
var ReplaySubject_1 = __nccwpck_require__(22351);
Object.defineProperty(exports, "ReplaySubject", ({ enumerable: true, get: function () { return ReplaySubject_1.ReplaySubject; } }));
var AsyncSubject_1 = __nccwpck_require__(9747);
Object.defineProperty(exports, "AsyncSubject", ({ enumerable: true, get: function () { return AsyncSubject_1.AsyncSubject; } }));
var asap_1 = __nccwpck_require__(43905);
Object.defineProperty(exports, "asap", ({ enumerable: true, get: function () { return asap_1.asap; } }));
Object.defineProperty(exports, "asapScheduler", ({ enumerable: true, get: function () { return asap_1.asapScheduler; } }));
var async_1 = __nccwpck_require__(76072);
Object.defineProperty(exports, "async", ({ enumerable: true, get: function () { return async_1.async; } }));
Object.defineProperty(exports, "asyncScheduler", ({ enumerable: true, get: function () { return async_1.asyncScheduler; } }));
var queue_1 = __nccwpck_require__(82059);
Object.defineProperty(exports, "queue", ({ enumerable: true, get: function () { return queue_1.queue; } }));
Object.defineProperty(exports, "queueScheduler", ({ enumerable: true, get: function () { return queue_1.queueScheduler; } }));
var animationFrame_1 = __nccwpck_require__(51359);
Object.defineProperty(exports, "animationFrame", ({ enumerable: true, get: function () { return animationFrame_1.animationFrame; } }));
Object.defineProperty(exports, "animationFrameScheduler", ({ enumerable: true, get: function () { return animationFrame_1.animationFrameScheduler; } }));
var VirtualTimeScheduler_1 = __nccwpck_require__(75348);
Object.defineProperty(exports, "VirtualTimeScheduler", ({ enumerable: true, get: function () { return VirtualTimeScheduler_1.VirtualTimeScheduler; } }));
Object.defineProperty(exports, "VirtualAction", ({ enumerable: true, get: function () { return VirtualTimeScheduler_1.VirtualAction; } }));
var Scheduler_1 = __nccwpck_require__(76243);
Object.defineProperty(exports, "Scheduler", ({ enumerable: true, get: function () { return Scheduler_1.Scheduler; } }));
var Subscription_1 = __nccwpck_require__(79548);
Object.defineProperty(exports, "Subscription", ({ enumerable: true, get: function () { return Subscription_1.Subscription; } }));
var Subscriber_1 = __nccwpck_require__(67121);
Object.defineProperty(exports, "Subscriber", ({ enumerable: true, get: function () { return Subscriber_1.Subscriber; } }));
var Notification_1 = __nccwpck_require__(12241);
Object.defineProperty(exports, "Notification", ({ enumerable: true, get: function () { return Notification_1.Notification; } }));
Object.defineProperty(exports, "NotificationKind", ({ enumerable: true, get: function () { return Notification_1.NotificationKind; } }));
var pipe_1 = __nccwpck_require__(49587);
Object.defineProperty(exports, "pipe", ({ enumerable: true, get: function () { return pipe_1.pipe; } }));
var noop_1 = __nccwpck_require__(11642);
Object.defineProperty(exports, "noop", ({ enumerable: true, get: function () { return noop_1.noop; } }));
var identity_1 = __nccwpck_require__(60283);
Object.defineProperty(exports, "identity", ({ enumerable: true, get: function () { return identity_1.identity; } }));
var isObservable_1 = __nccwpck_require__(72259);
Object.defineProperty(exports, "isObservable", ({ enumerable: true, get: function () { return isObservable_1.isObservable; } }));
var lastValueFrom_1 = __nccwpck_require__(49713);
Object.defineProperty(exports, "lastValueFrom", ({ enumerable: true, get: function () { return lastValueFrom_1.lastValueFrom; } }));
var firstValueFrom_1 = __nccwpck_require__(19369);
Object.defineProperty(exports, "firstValueFrom", ({ enumerable: true, get: function () { return firstValueFrom_1.firstValueFrom; } }));
var ArgumentOutOfRangeError_1 = __nccwpck_require__(49796);
Object.defineProperty(exports, "ArgumentOutOfRangeError", ({ enumerable: true, get: function () { return ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; } }));
var EmptyError_1 = __nccwpck_require__(99391);
Object.defineProperty(exports, "EmptyError", ({ enumerable: true, get: function () { return EmptyError_1.EmptyError; } }));
var NotFoundError_1 = __nccwpck_require__(74431);
Object.defineProperty(exports, "NotFoundError", ({ enumerable: true, get: function () { return NotFoundError_1.NotFoundError; } }));
var ObjectUnsubscribedError_1 = __nccwpck_require__(95266);
Object.defineProperty(exports, "ObjectUnsubscribedError", ({ enumerable: true, get: function () { return ObjectUnsubscribedError_1.ObjectUnsubscribedError; } }));
var SequenceError_1 = __nccwpck_require__(49048);
Object.defineProperty(exports, "SequenceError", ({ enumerable: true, get: function () { return SequenceError_1.SequenceError; } }));
var timeout_1 = __nccwpck_require__(12051);
Object.defineProperty(exports, "TimeoutError", ({ enumerable: true, get: function () { return timeout_1.TimeoutError; } }));
var UnsubscriptionError_1 = __nccwpck_require__(56776);
Object.defineProperty(exports, "UnsubscriptionError", ({ enumerable: true, get: function () { return UnsubscriptionError_1.UnsubscriptionError; } }));
var bindCallback_1 = __nccwpck_require__(16949);
Object.defineProperty(exports, "bindCallback", ({ enumerable: true, get: function () { return bindCallback_1.bindCallback; } }));
var bindNodeCallback_1 = __nccwpck_require__(51150);
Object.defineProperty(exports, "bindNodeCallback", ({ enumerable: true, get: function () { return bindNodeCallback_1.bindNodeCallback; } }));
var combineLatest_1 = __nccwpck_require__(46843);
Object.defineProperty(exports, "combineLatest", ({ enumerable: true, get: function () { return combineLatest_1.combineLatest; } }));
var concat_1 = __nccwpck_require__(4675);
Object.defineProperty(exports, "concat", ({ enumerable: true, get: function () { return concat_1.concat; } }));
var connectable_1 = __nccwpck_require__(13152);
Object.defineProperty(exports, "connectable", ({ enumerable: true, get: function () { return connectable_1.connectable; } }));
var defer_1 = __nccwpck_require__(27672);
Object.defineProperty(exports, "defer", ({ enumerable: true, get: function () { return defer_1.defer; } }));
var empty_1 = __nccwpck_require__(70437);
Object.defineProperty(exports, "empty", ({ enumerable: true, get: function () { return empty_1.empty; } }));
var forkJoin_1 = __nccwpck_require__(47358);
Object.defineProperty(exports, "forkJoin", ({ enumerable: true, get: function () { return forkJoin_1.forkJoin; } }));
var from_1 = __nccwpck_require__(18309);
Object.defineProperty(exports, "from", ({ enumerable: true, get: function () { return from_1.from; } }));
var fromEvent_1 = __nccwpck_require__(93238);
Object.defineProperty(exports, "fromEvent", ({ enumerable: true, get: function () { return fromEvent_1.fromEvent; } }));
var fromEventPattern_1 = __nccwpck_require__(65680);
Object.defineProperty(exports, "fromEventPattern", ({ enumerable: true, get: function () { return fromEventPattern_1.fromEventPattern; } }));
var generate_1 = __nccwpck_require__(52668);
Object.defineProperty(exports, "generate", ({ enumerable: true, get: function () { return generate_1.generate; } }));
var iif_1 = __nccwpck_require__(26514);
Object.defineProperty(exports, "iif", ({ enumerable: true, get: function () { return iif_1.iif; } }));
var interval_1 = __nccwpck_require__(20029);
Object.defineProperty(exports, "interval", ({ enumerable: true, get: function () { return interval_1.interval; } }));
var merge_1 = __nccwpck_require__(75122);
Object.defineProperty(exports, "merge", ({ enumerable: true, get: function () { return merge_1.merge; } }));
var never_1 = __nccwpck_require__(6228);
Object.defineProperty(exports, "never", ({ enumerable: true, get: function () { return never_1.never; } }));
var of_1 = __nccwpck_require__(72163);
Object.defineProperty(exports, "of", ({ enumerable: true, get: function () { return of_1.of; } }));
var onErrorResumeNext_1 = __nccwpck_require__(16089);
Object.defineProperty(exports, "onErrorResumeNext", ({ enumerable: true, get: function () { return onErrorResumeNext_1.onErrorResumeNext; } }));
var pairs_1 = __nccwpck_require__(30505);
Object.defineProperty(exports, "pairs", ({ enumerable: true, get: function () { return pairs_1.pairs; } }));
var partition_1 = __nccwpck_require__(15506);
Object.defineProperty(exports, "partition", ({ enumerable: true, get: function () { return partition_1.partition; } }));
var race_1 = __nccwpck_require__(16940);
Object.defineProperty(exports, "race", ({ enumerable: true, get: function () { return race_1.race; } }));
var range_1 = __nccwpck_require__(88538);
Object.defineProperty(exports, "range", ({ enumerable: true, get: function () { return range_1.range; } }));
var throwError_1 = __nccwpck_require__(66381);
Object.defineProperty(exports, "throwError", ({ enumerable: true, get: function () { return throwError_1.throwError; } }));
var timer_1 = __nccwpck_require__(59757);
Object.defineProperty(exports, "timer", ({ enumerable: true, get: function () { return timer_1.timer; } }));
var using_1 = __nccwpck_require__(8445);
Object.defineProperty(exports, "using", ({ enumerable: true, get: function () { return using_1.using; } }));
var zip_1 = __nccwpck_require__(62504);
Object.defineProperty(exports, "zip", ({ enumerable: true, get: function () { return zip_1.zip; } }));
var scheduled_1 = __nccwpck_require__(6151);
Object.defineProperty(exports, "scheduled", ({ enumerable: true, get: function () { return scheduled_1.scheduled; } }));
var empty_2 = __nccwpck_require__(70437);
Object.defineProperty(exports, "EMPTY", ({ enumerable: true, get: function () { return empty_2.EMPTY; } }));
var never_2 = __nccwpck_require__(6228);
Object.defineProperty(exports, "NEVER", ({ enumerable: true, get: function () { return never_2.NEVER; } }));
__exportStar(__nccwpck_require__(36639), exports);
var config_1 = __nccwpck_require__(92233);
Object.defineProperty(exports, "config", ({ enumerable: true, get: function () { return config_1.config; } }));
var audit_1 = __nccwpck_require__(43471);
Object.defineProperty(exports, "audit", ({ enumerable: true, get: function () { return audit_1.audit; } }));
var auditTime_1 = __nccwpck_require__(18780);
Object.defineProperty(exports, "auditTime", ({ enumerable: true, get: function () { return auditTime_1.auditTime; } }));
var buffer_1 = __nccwpck_require__(34253);
Object.defineProperty(exports, "buffer", ({ enumerable: true, get: function () { return buffer_1.buffer; } }));
var bufferCount_1 = __nccwpck_require__(17253);
Object.defineProperty(exports, "bufferCount", ({ enumerable: true, get: function () { return bufferCount_1.bufferCount; } }));
var bufferTime_1 = __nccwpck_require__(73102);
Object.defineProperty(exports, "bufferTime", ({ enumerable: true, get: function () { return bufferTime_1.bufferTime; } }));
var bufferToggle_1 = __nccwpck_require__(83781);
Object.defineProperty(exports, "bufferToggle", ({ enumerable: true, get: function () { return bufferToggle_1.bufferToggle; } }));
var bufferWhen_1 = __nccwpck_require__(82855);
Object.defineProperty(exports, "bufferWhen", ({ enumerable: true, get: function () { return bufferWhen_1.bufferWhen; } }));
var catchError_1 = __nccwpck_require__(37765);
Object.defineProperty(exports, "catchError", ({ enumerable: true, get: function () { return catchError_1.catchError; } }));
var combineAll_1 = __nccwpck_require__(88817);
Object.defineProperty(exports, "combineAll", ({ enumerable: true, get: function () { return combineAll_1.combineAll; } }));
var combineLatestAll_1 = __nccwpck_require__(91063);
Object.defineProperty(exports, "combineLatestAll", ({ enumerable: true, get: function () { return combineLatestAll_1.combineLatestAll; } }));
var combineLatestWith_1 = __nccwpck_require__(19044);
Object.defineProperty(exports, "combineLatestWith", ({ enumerable: true, get: function () { return combineLatestWith_1.combineLatestWith; } }));
var concatAll_1 = __nccwpck_require__(88049);
Object.defineProperty(exports, "concatAll", ({ enumerable: true, get: function () { return concatAll_1.concatAll; } }));
var concatMap_1 = __nccwpck_require__(19130);
Object.defineProperty(exports, "concatMap", ({ enumerable: true, get: function () { return concatMap_1.concatMap; } }));
var concatMapTo_1 = __nccwpck_require__(61596);
Object.defineProperty(exports, "concatMapTo", ({ enumerable: true, get: function () { return concatMapTo_1.concatMapTo; } }));
var concatWith_1 = __nccwpck_require__(97998);
Object.defineProperty(exports, "concatWith", ({ enumerable: true, get: function () { return concatWith_1.concatWith; } }));
var connect_1 = __nccwpck_require__(51101);
Object.defineProperty(exports, "connect", ({ enumerable: true, get: function () { return connect_1.connect; } }));
var count_1 = __nccwpck_require__(36571);
Object.defineProperty(exports, "count", ({ enumerable: true, get: function () { return count_1.count; } }));
var debounce_1 = __nccwpck_require__(19348);
Object.defineProperty(exports, "debounce", ({ enumerable: true, get: function () { return debounce_1.debounce; } }));
var debounceTime_1 = __nccwpck_require__(62379);
Object.defineProperty(exports, "debounceTime", ({ enumerable: true, get: function () { return debounceTime_1.debounceTime; } }));
var defaultIfEmpty_1 = __nccwpck_require__(30621);
Object.defineProperty(exports, "defaultIfEmpty", ({ enumerable: true, get: function () { return defaultIfEmpty_1.defaultIfEmpty; } }));
var delay_1 = __nccwpck_require__(99818);
Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_1.delay; } }));
var delayWhen_1 = __nccwpck_require__(16994);
Object.defineProperty(exports, "delayWhen", ({ enumerable: true, get: function () { return delayWhen_1.delayWhen; } }));
var dematerialize_1 = __nccwpck_require__(95338);
Object.defineProperty(exports, "dematerialize", ({ enumerable: true, get: function () { return dematerialize_1.dematerialize; } }));
var distinct_1 = __nccwpck_require__(52594);
Object.defineProperty(exports, "distinct", ({ enumerable: true, get: function () { return distinct_1.distinct; } }));
var distinctUntilChanged_1 = __nccwpck_require__(20632);
Object.defineProperty(exports, "distinctUntilChanged", ({ enumerable: true, get: function () { return distinctUntilChanged_1.distinctUntilChanged; } }));
var distinctUntilKeyChanged_1 = __nccwpck_require__(13809);
Object.defineProperty(exports, "distinctUntilKeyChanged", ({ enumerable: true, get: function () { return distinctUntilKeyChanged_1.distinctUntilKeyChanged; } }));
var elementAt_1 = __nccwpck_require__(73381);
Object.defineProperty(exports, "elementAt", ({ enumerable: true, get: function () { return elementAt_1.elementAt; } }));
var endWith_1 = __nccwpck_require__(42961);
Object.defineProperty(exports, "endWith", ({ enumerable: true, get: function () { return endWith_1.endWith; } }));
var every_1 = __nccwpck_require__(69559);
Object.defineProperty(exports, "every", ({ enumerable: true, get: function () { return every_1.every; } }));
var exhaust_1 = __nccwpck_require__(75686);
Object.defineProperty(exports, "exhaust", ({ enumerable: true, get: function () { return exhaust_1.exhaust; } }));
var exhaustAll_1 = __nccwpck_require__(79777);
Object.defineProperty(exports, "exhaustAll", ({ enumerable: true, get: function () { return exhaustAll_1.exhaustAll; } }));
var exhaustMap_1 = __nccwpck_require__(21527);
Object.defineProperty(exports, "exhaustMap", ({ enumerable: true, get: function () { return exhaustMap_1.exhaustMap; } }));
var expand_1 = __nccwpck_require__(21585);
Object.defineProperty(exports, "expand", ({ enumerable: true, get: function () { return expand_1.expand; } }));
var filter_1 = __nccwpck_require__(36894);
Object.defineProperty(exports, "filter", ({ enumerable: true, get: function () { return filter_1.filter; } }));
var finalize_1 = __nccwpck_require__(4013);
Object.defineProperty(exports, "finalize", ({ enumerable: true, get: function () { return finalize_1.finalize; } }));
var find_1 = __nccwpck_require__(28981);
Object.defineProperty(exports, "find", ({ enumerable: true, get: function () { return find_1.find; } }));
var findIndex_1 = __nccwpck_require__(92602);
Object.defineProperty(exports, "findIndex", ({ enumerable: true, get: function () { return findIndex_1.findIndex; } }));
var first_1 = __nccwpck_require__(63345);
Object.defineProperty(exports, "first", ({ enumerable: true, get: function () { return first_1.first; } }));
var groupBy_1 = __nccwpck_require__(51650);
Object.defineProperty(exports, "groupBy", ({ enumerable: true, get: function () { return groupBy_1.groupBy; } }));
var ignoreElements_1 = __nccwpck_require__(31062);
Object.defineProperty(exports, "ignoreElements", ({ enumerable: true, get: function () { return ignoreElements_1.ignoreElements; } }));
var isEmpty_1 = __nccwpck_require__(77722);
Object.defineProperty(exports, "isEmpty", ({ enumerable: true, get: function () { return isEmpty_1.isEmpty; } }));
var last_1 = __nccwpck_require__(46831);
Object.defineProperty(exports, "last", ({ enumerable: true, get: function () { return last_1.last; } }));
var map_1 = __nccwpck_require__(5987);
Object.defineProperty(exports, "map", ({ enumerable: true, get: function () { return map_1.map; } }));
var mapTo_1 = __nccwpck_require__(52300);
Object.defineProperty(exports, "mapTo", ({ enumerable: true, get: function () { return mapTo_1.mapTo; } }));
var materialize_1 = __nccwpck_require__(67108);
Object.defineProperty(exports, "materialize", ({ enumerable: true, get: function () { return materialize_1.materialize; } }));
var max_1 = __nccwpck_require__(17314);
Object.defineProperty(exports, "max", ({ enumerable: true, get: function () { return max_1.max; } }));
var mergeAll_1 = __nccwpck_require__(2057);
Object.defineProperty(exports, "mergeAll", ({ enumerable: true, get: function () { return mergeAll_1.mergeAll; } }));
var flatMap_1 = __nccwpck_require__(40186);
Object.defineProperty(exports, "flatMap", ({ enumerable: true, get: function () { return flatMap_1.flatMap; } }));
var mergeMap_1 = __nccwpck_require__(69914);
Object.defineProperty(exports, "mergeMap", ({ enumerable: true, get: function () { return mergeMap_1.mergeMap; } }));
var mergeMapTo_1 = __nccwpck_require__(49151);
Object.defineProperty(exports, "mergeMapTo", ({ enumerable: true, get: function () { return mergeMapTo_1.mergeMapTo; } }));
var mergeScan_1 = __nccwpck_require__(11519);
Object.defineProperty(exports, "mergeScan", ({ enumerable: true, get: function () { return mergeScan_1.mergeScan; } }));
var mergeWith_1 = __nccwpck_require__(22117);
Object.defineProperty(exports, "mergeWith", ({ enumerable: true, get: function () { return mergeWith_1.mergeWith; } }));
var min_1 = __nccwpck_require__(87641);
Object.defineProperty(exports, "min", ({ enumerable: true, get: function () { return min_1.min; } }));
var multicast_1 = __nccwpck_require__(65457);
Object.defineProperty(exports, "multicast", ({ enumerable: true, get: function () { return multicast_1.multicast; } }));
var observeOn_1 = __nccwpck_require__(22451);
Object.defineProperty(exports, "observeOn", ({ enumerable: true, get: function () { return observeOn_1.observeOn; } }));
var onErrorResumeNextWith_1 = __nccwpck_require__(33569);
Object.defineProperty(exports, "onErrorResumeNextWith", ({ enumerable: true, get: function () { return onErrorResumeNextWith_1.onErrorResumeNextWith; } }));
var pairwise_1 = __nccwpck_require__(52206);
Object.defineProperty(exports, "pairwise", ({ enumerable: true, get: function () { return pairwise_1.pairwise; } }));
var pluck_1 = __nccwpck_require__(16073);
Object.defineProperty(exports, "pluck", ({ enumerable: true, get: function () { return pluck_1.pluck; } }));
var publish_1 = __nccwpck_require__(84084);
Object.defineProperty(exports, "publish", ({ enumerable: true, get: function () { return publish_1.publish; } }));
var publishBehavior_1 = __nccwpck_require__(40045);
Object.defineProperty(exports, "publishBehavior", ({ enumerable: true, get: function () { return publishBehavior_1.publishBehavior; } }));
var publishLast_1 = __nccwpck_require__(84149);
Object.defineProperty(exports, "publishLast", ({ enumerable: true, get: function () { return publishLast_1.publishLast; } }));
var publishReplay_1 = __nccwpck_require__(47656);
Object.defineProperty(exports, "publishReplay", ({ enumerable: true, get: function () { return publishReplay_1.publishReplay; } }));
var raceWith_1 = __nccwpck_require__(58008);
Object.defineProperty(exports, "raceWith", ({ enumerable: true, get: function () { return raceWith_1.raceWith; } }));
var reduce_1 = __nccwpck_require__(62087);
Object.defineProperty(exports, "reduce", ({ enumerable: true, get: function () { return reduce_1.reduce; } }));
var repeat_1 = __nccwpck_require__(22418);
Object.defineProperty(exports, "repeat", ({ enumerable: true, get: function () { return repeat_1.repeat; } }));
var repeatWhen_1 = __nccwpck_require__(70754);
Object.defineProperty(exports, "repeatWhen", ({ enumerable: true, get: function () { return repeatWhen_1.repeatWhen; } }));
var retry_1 = __nccwpck_require__(56251);
Object.defineProperty(exports, "retry", ({ enumerable: true, get: function () { return retry_1.retry; } }));
var retryWhen_1 = __nccwpck_require__(69018);
Object.defineProperty(exports, "retryWhen", ({ enumerable: true, get: function () { return retryWhen_1.retryWhen; } }));
var refCount_1 = __nccwpck_require__(2331);
Object.defineProperty(exports, "refCount", ({ enumerable: true, get: function () { return refCount_1.refCount; } }));
var sample_1 = __nccwpck_require__(13774);
Object.defineProperty(exports, "sample", ({ enumerable: true, get: function () { return sample_1.sample; } }));
var sampleTime_1 = __nccwpck_require__(49807);
Object.defineProperty(exports, "sampleTime", ({ enumerable: true, get: function () { return sampleTime_1.sampleTime; } }));
var scan_1 = __nccwpck_require__(25578);
Object.defineProperty(exports, "scan", ({ enumerable: true, get: function () { return scan_1.scan; } }));
var sequenceEqual_1 = __nccwpck_require__(16126);
Object.defineProperty(exports, "sequenceEqual", ({ enumerable: true, get: function () { return sequenceEqual_1.sequenceEqual; } }));
var share_1 = __nccwpck_require__(48960);
Object.defineProperty(exports, "share", ({ enumerable: true, get: function () { return share_1.share; } }));
var shareReplay_1 = __nccwpck_require__(92118);
Object.defineProperty(exports, "shareReplay", ({ enumerable: true, get: function () { return shareReplay_1.shareReplay; } }));
var single_1 = __nccwpck_require__(58441);
Object.defineProperty(exports, "single", ({ enumerable: true, get: function () { return single_1.single; } }));
var skip_1 = __nccwpck_require__(80947);
Object.defineProperty(exports, "skip", ({ enumerable: true, get: function () { return skip_1.skip; } }));
var skipLast_1 = __nccwpck_require__(65865);
Object.defineProperty(exports, "skipLast", ({ enumerable: true, get: function () { return skipLast_1.skipLast; } }));
var skipUntil_1 = __nccwpck_require__(41110);
Object.defineProperty(exports, "skipUntil", ({ enumerable: true, get: function () { return skipUntil_1.skipUntil; } }));
var skipWhile_1 = __nccwpck_require__(92550);
Object.defineProperty(exports, "skipWhile", ({ enumerable: true, get: function () { return skipWhile_1.skipWhile; } }));
var startWith_1 = __nccwpck_require__(25471);
Object.defineProperty(exports, "startWith", ({ enumerable: true, get: function () { return startWith_1.startWith; } }));
var subscribeOn_1 = __nccwpck_require__(7224);
Object.defineProperty(exports, "subscribeOn", ({ enumerable: true, get: function () { return subscribeOn_1.subscribeOn; } }));
var switchAll_1 = __nccwpck_require__(40327);
Object.defineProperty(exports, "switchAll", ({ enumerable: true, get: function () { return switchAll_1.switchAll; } }));
var switchMap_1 = __nccwpck_require__(26704);
Object.defineProperty(exports, "switchMap", ({ enumerable: true, get: function () { return switchMap_1.switchMap; } }));
var switchMapTo_1 = __nccwpck_require__(1713);
Object.defineProperty(exports, "switchMapTo", ({ enumerable: true, get: function () { return switchMapTo_1.switchMapTo; } }));
var switchScan_1 = __nccwpck_require__(13355);
Object.defineProperty(exports, "switchScan", ({ enumerable: true, get: function () { return switchScan_1.switchScan; } }));
var take_1 = __nccwpck_require__(33698);
Object.defineProperty(exports, "take", ({ enumerable: true, get: function () { return take_1.take; } }));
var takeLast_1 = __nccwpck_require__(65041);
Object.defineProperty(exports, "takeLast", ({ enumerable: true, get: function () { return takeLast_1.takeLast; } }));
var takeUntil_1 = __nccwpck_require__(55150);
Object.defineProperty(exports, "takeUntil", ({ enumerable: true, get: function () { return takeUntil_1.takeUntil; } }));
var takeWhile_1 = __nccwpck_require__(76700);
Object.defineProperty(exports, "takeWhile", ({ enumerable: true, get: function () { return takeWhile_1.takeWhile; } }));
var tap_1 = __nccwpck_require__(48845);
Object.defineProperty(exports, "tap", ({ enumerable: true, get: function () { return tap_1.tap; } }));
var throttle_1 = __nccwpck_require__(36713);
Object.defineProperty(exports, "throttle", ({ enumerable: true, get: function () { return throttle_1.throttle; } }));
var throttleTime_1 = __nccwpck_require__(83435);
Object.defineProperty(exports, "throttleTime", ({ enumerable: true, get: function () { return throttleTime_1.throttleTime; } }));
var throwIfEmpty_1 = __nccwpck_require__(91566);
Object.defineProperty(exports, "throwIfEmpty", ({ enumerable: true, get: function () { return throwIfEmpty_1.throwIfEmpty; } }));
var timeInterval_1 = __nccwpck_require__(14643);
Object.defineProperty(exports, "timeInterval", ({ enumerable: true, get: function () { return timeInterval_1.timeInterval; } }));
var timeout_2 = __nccwpck_require__(12051);
Object.defineProperty(exports, "timeout", ({ enumerable: true, get: function () { return timeout_2.timeout; } }));
var timeoutWith_1 = __nccwpck_require__(43540);
Object.defineProperty(exports, "timeoutWith", ({ enumerable: true, get: function () { return timeoutWith_1.timeoutWith; } }));
var timestamp_1 = __nccwpck_require__(75518);
Object.defineProperty(exports, "timestamp", ({ enumerable: true, get: function () { return timestamp_1.timestamp; } }));
var toArray_1 = __nccwpck_require__(35114);
Object.defineProperty(exports, "toArray", ({ enumerable: true, get: function () { return toArray_1.toArray; } }));
var window_1 = __nccwpck_require__(98255);
Object.defineProperty(exports, "window", ({ enumerable: true, get: function () { return window_1.window; } }));
var windowCount_1 = __nccwpck_require__(73144);
Object.defineProperty(exports, "windowCount", ({ enumerable: true, get: function () { return windowCount_1.windowCount; } }));
var windowTime_1 = __nccwpck_require__(2738);
Object.defineProperty(exports, "windowTime", ({ enumerable: true, get: function () { return windowTime_1.windowTime; } }));
var windowToggle_1 = __nccwpck_require__(52741);
Object.defineProperty(exports, "windowToggle", ({ enumerable: true, get: function () { return windowToggle_1.windowToggle; } }));
var windowWhen_1 = __nccwpck_require__(82645);
Object.defineProperty(exports, "windowWhen", ({ enumerable: true, get: function () { return windowWhen_1.windowWhen; } }));
var withLatestFrom_1 = __nccwpck_require__(20501);
Object.defineProperty(exports, "withLatestFrom", ({ enumerable: true, get: function () { return withLatestFrom_1.withLatestFrom; } }));
var zipAll_1 = __nccwpck_require__(92335);
Object.defineProperty(exports, "zipAll", ({ enumerable: true, get: function () { return zipAll_1.zipAll; } }));
var zipWith_1 = __nccwpck_require__(95520);
Object.defineProperty(exports, "zipWith", ({ enumerable: true, get: function () { return zipWith_1.zipWith; } }));
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 9747:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AsyncSubject = void 0;
var Subject_1 = __nccwpck_require__(49944);
var AsyncSubject = (function (_super) {
__extends(AsyncSubject, _super);
function AsyncSubject() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._value = null;
_this._hasValue = false;
_this._isComplete = false;
return _this;
}
AsyncSubject.prototype._checkFinalizedStatuses = function (subscriber) {
var _a = this, hasError = _a.hasError, _hasValue = _a._hasValue, _value = _a._value, thrownError = _a.thrownError, isStopped = _a.isStopped, _isComplete = _a._isComplete;
if (hasError) {
subscriber.error(thrownError);
}
else if (isStopped || _isComplete) {
_hasValue && subscriber.next(_value);
subscriber.complete();
}
};
AsyncSubject.prototype.next = function (value) {
if (!this.isStopped) {
this._value = value;
this._hasValue = true;
}
};
AsyncSubject.prototype.complete = function () {
var _a = this, _hasValue = _a._hasValue, _value = _a._value, _isComplete = _a._isComplete;
if (!_isComplete) {
this._isComplete = true;
_hasValue && _super.prototype.next.call(this, _value);
_super.prototype.complete.call(this);
}
};
return AsyncSubject;
}(Subject_1.Subject));
exports.AsyncSubject = AsyncSubject;
//# sourceMappingURL=AsyncSubject.js.map
/***/ }),
/***/ 23473:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BehaviorSubject = void 0;
var Subject_1 = __nccwpck_require__(49944);
var BehaviorSubject = (function (_super) {
__extends(BehaviorSubject, _super);
function BehaviorSubject(_value) {
var _this = _super.call(this) || this;
_this._value = _value;
return _this;
}
Object.defineProperty(BehaviorSubject.prototype, "value", {
get: function () {
return this.getValue();
},
enumerable: false,
configurable: true
});
BehaviorSubject.prototype._subscribe = function (subscriber) {
var subscription = _super.prototype._subscribe.call(this, subscriber);
!subscription.closed && subscriber.next(this._value);
return subscription;
};
BehaviorSubject.prototype.getValue = function () {
var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
if (hasError) {
throw thrownError;
}
this._throwIfClosed();
return _value;
};
BehaviorSubject.prototype.next = function (value) {
_super.prototype.next.call(this, (this._value = value));
};
return BehaviorSubject;
}(Subject_1.Subject));
exports.BehaviorSubject = BehaviorSubject;
//# sourceMappingURL=BehaviorSubject.js.map
/***/ }),
/***/ 12241:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.observeNotification = exports.Notification = exports.NotificationKind = void 0;
var empty_1 = __nccwpck_require__(70437);
var of_1 = __nccwpck_require__(72163);
var throwError_1 = __nccwpck_require__(66381);
var isFunction_1 = __nccwpck_require__(67206);
var NotificationKind;
(function (NotificationKind) {
NotificationKind["NEXT"] = "N";
NotificationKind["ERROR"] = "E";
NotificationKind["COMPLETE"] = "C";
})(NotificationKind = exports.NotificationKind || (exports.NotificationKind = {}));
var Notification = (function () {
function Notification(kind, value, error) {
this.kind = kind;
this.value = value;
this.error = error;
this.hasValue = kind === 'N';
}
Notification.prototype.observe = function (observer) {
return observeNotification(this, observer);
};
Notification.prototype.do = function (nextHandler, errorHandler, completeHandler) {
var _a = this, kind = _a.kind, value = _a.value, error = _a.error;
return kind === 'N' ? nextHandler === null || nextHandler === void 0 ? void 0 : nextHandler(value) : kind === 'E' ? errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(error) : completeHandler === null || completeHandler === void 0 ? void 0 : completeHandler();
};
Notification.prototype.accept = function (nextOrObserver, error, complete) {
var _a;
return isFunction_1.isFunction((_a = nextOrObserver) === null || _a === void 0 ? void 0 : _a.next)
? this.observe(nextOrObserver)
: this.do(nextOrObserver, error, complete);
};
Notification.prototype.toObservable = function () {
var _a = this, kind = _a.kind, value = _a.value, error = _a.error;
var result = kind === 'N'
?
of_1.of(value)
:
kind === 'E'
?
throwError_1.throwError(function () { return error; })
:
kind === 'C'
?
empty_1.EMPTY
:
0;
if (!result) {
throw new TypeError("Unexpected notification kind " + kind);
}
return result;
};
Notification.createNext = function (value) {
return new Notification('N', value);
};
Notification.createError = function (err) {
return new Notification('E', undefined, err);
};
Notification.createComplete = function () {
return Notification.completeNotification;
};
Notification.completeNotification = new Notification('C');
return Notification;
}());
exports.Notification = Notification;
function observeNotification(notification, observer) {
var _a, _b, _c;
var _d = notification, kind = _d.kind, value = _d.value, error = _d.error;
if (typeof kind !== 'string') {
throw new TypeError('Invalid notification, missing "kind"');
}
kind === 'N' ? (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, value) : kind === 'E' ? (_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, error) : (_c = observer.complete) === null || _c === void 0 ? void 0 : _c.call(observer);
}
exports.observeNotification = observeNotification;
//# sourceMappingURL=Notification.js.map
/***/ }),
/***/ 2500:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createNotification = exports.nextNotification = exports.errorNotification = exports.COMPLETE_NOTIFICATION = void 0;
exports.COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
function errorNotification(error) {
return createNotification('E', undefined, error);
}
exports.errorNotification = errorNotification;
function nextNotification(value) {
return createNotification('N', value, undefined);
}
exports.nextNotification = nextNotification;
function createNotification(kind, value, error) {
return {
kind: kind,
value: value,
error: error,
};
}
exports.createNotification = createNotification;
//# sourceMappingURL=NotificationFactories.js.map
/***/ }),
/***/ 53014:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Observable = void 0;
var Subscriber_1 = __nccwpck_require__(67121);
var Subscription_1 = __nccwpck_require__(79548);
var observable_1 = __nccwpck_require__(17186);
var pipe_1 = __nccwpck_require__(49587);
var config_1 = __nccwpck_require__(92233);
var isFunction_1 = __nccwpck_require__(67206);
var errorContext_1 = __nccwpck_require__(31199);
var Observable = (function () {
function Observable(subscribe) {
if (subscribe) {
this._subscribe = subscribe;
}
}
Observable.prototype.lift = function (operator) {
var observable = new Observable();
observable.source = this;
observable.operator = operator;
return observable;
};
Observable.prototype.subscribe = function (observerOrNext, error, complete) {
var _this = this;
var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new Subscriber_1.SafeSubscriber(observerOrNext, error, complete);
errorContext_1.errorContext(function () {
var _a = _this, operator = _a.operator, source = _a.source;
subscriber.add(operator
?
operator.call(subscriber, source)
: source
?
_this._subscribe(subscriber)
:
_this._trySubscribe(subscriber));
});
return subscriber;
};
Observable.prototype._trySubscribe = function (sink) {
try {
return this._subscribe(sink);
}
catch (err) {
sink.error(err);
}
};
Observable.prototype.forEach = function (next, promiseCtor) {
var _this = this;
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor(function (resolve, reject) {
var subscriber = new Subscriber_1.SafeSubscriber({
next: function (value) {
try {
next(value);
}
catch (err) {
reject(err);
subscriber.unsubscribe();
}
},
error: reject,
complete: resolve,
});
_this.subscribe(subscriber);
});
};
Observable.prototype._subscribe = function (subscriber) {
var _a;
return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
};
Observable.prototype[observable_1.observable] = function () {
return this;
};
Observable.prototype.pipe = function () {
var operations = [];
for (var _i = 0; _i < arguments.length; _i++) {
operations[_i] = arguments[_i];
}
return pipe_1.pipeFromArray(operations)(this);
};
Observable.prototype.toPromise = function (promiseCtor) {
var _this = this;
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor(function (resolve, reject) {
var value;
_this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
});
};
Observable.create = function (subscribe) {
return new Observable(subscribe);
};
return Observable;
}());
exports.Observable = Observable;
function getPromiseCtor(promiseCtor) {
var _a;
return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config_1.config.Promise) !== null && _a !== void 0 ? _a : Promise;
}
function isObserver(value) {
return value && isFunction_1.isFunction(value.next) && isFunction_1.isFunction(value.error) && isFunction_1.isFunction(value.complete);
}
function isSubscriber(value) {
return (value && value instanceof Subscriber_1.Subscriber) || (isObserver(value) && Subscription_1.isSubscription(value));
}
//# sourceMappingURL=Observable.js.map
/***/ }),
/***/ 22351:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReplaySubject = void 0;
var Subject_1 = __nccwpck_require__(49944);
var dateTimestampProvider_1 = __nccwpck_require__(91395);
var ReplaySubject = (function (_super) {
__extends(ReplaySubject, _super);
function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
if (_bufferSize === void 0) { _bufferSize = Infinity; }
if (_windowTime === void 0) { _windowTime = Infinity; }
if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider_1.dateTimestampProvider; }
var _this = _super.call(this) || this;
_this._bufferSize = _bufferSize;
_this._windowTime = _windowTime;
_this._timestampProvider = _timestampProvider;
_this._buffer = [];
_this._infiniteTimeWindow = true;
_this._infiniteTimeWindow = _windowTime === Infinity;
_this._bufferSize = Math.max(1, _bufferSize);
_this._windowTime = Math.max(1, _windowTime);
return _this;
}
ReplaySubject.prototype.next = function (value) {
var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
if (!isStopped) {
_buffer.push(value);
!_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
}
this._trimBuffer();
_super.prototype.next.call(this, value);
};
ReplaySubject.prototype._subscribe = function (subscriber) {
this._throwIfClosed();
this._trimBuffer();
var subscription = this._innerSubscribe(subscriber);
var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
var copy = _buffer.slice();
for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
subscriber.next(copy[i]);
}
this._checkFinalizedStatuses(subscriber);
return subscription;
};
ReplaySubject.prototype._trimBuffer = function () {
var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
_bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
if (!_infiniteTimeWindow) {
var now = _timestampProvider.now();
var last = 0;
for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
last = i;
}
last && _buffer.splice(0, last + 1);
}
};
return ReplaySubject;
}(Subject_1.Subject));
exports.ReplaySubject = ReplaySubject;
//# sourceMappingURL=ReplaySubject.js.map
/***/ }),
/***/ 76243:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Scheduler = void 0;
var dateTimestampProvider_1 = __nccwpck_require__(91395);
var Scheduler = (function () {
function Scheduler(schedulerActionCtor, now) {
if (now === void 0) { now = Scheduler.now; }
this.schedulerActionCtor = schedulerActionCtor;
this.now = now;
}
Scheduler.prototype.schedule = function (work, delay, state) {
if (delay === void 0) { delay = 0; }
return new this.schedulerActionCtor(this, work).schedule(state, delay);
};
Scheduler.now = dateTimestampProvider_1.dateTimestampProvider.now;
return Scheduler;
}());
exports.Scheduler = Scheduler;
//# sourceMappingURL=Scheduler.js.map
/***/ }),
/***/ 49944:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AnonymousSubject = exports.Subject = void 0;
var Observable_1 = __nccwpck_require__(53014);
var Subscription_1 = __nccwpck_require__(79548);
var ObjectUnsubscribedError_1 = __nccwpck_require__(95266);
var arrRemove_1 = __nccwpck_require__(68499);
var errorContext_1 = __nccwpck_require__(31199);
var Subject = (function (_super) {
__extends(Subject, _super);
function Subject() {
var _this = _super.call(this) || this;
_this.closed = false;
_this.currentObservers = null;
_this.observers = [];
_this.isStopped = false;
_this.hasError = false;
_this.thrownError = null;
return _this;
}
Subject.prototype.lift = function (operator) {
var subject = new AnonymousSubject(this, this);
subject.operator = operator;
return subject;
};
Subject.prototype._throwIfClosed = function () {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
};
Subject.prototype.next = function (value) {
var _this = this;
errorContext_1.errorContext(function () {
var e_1, _a;
_this._throwIfClosed();
if (!_this.isStopped) {
if (!_this.currentObservers) {
_this.currentObservers = Array.from(_this.observers);
}
try {
for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
var observer = _c.value;
observer.next(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
});
};
Subject.prototype.error = function (err) {
var _this = this;
errorContext_1.errorContext(function () {
_this._throwIfClosed();
if (!_this.isStopped) {
_this.hasError = _this.isStopped = true;
_this.thrownError = err;
var observers = _this.observers;
while (observers.length) {
observers.shift().error(err);
}
}
});
};
Subject.prototype.complete = function () {
var _this = this;
errorContext_1.errorContext(function () {
_this._throwIfClosed();
if (!_this.isStopped) {
_this.isStopped = true;
var observers = _this.observers;
while (observers.length) {
observers.shift().complete();
}
}
});
};
Subject.prototype.unsubscribe = function () {
this.isStopped = this.closed = true;
this.observers = this.currentObservers = null;
};
Object.defineProperty(Subject.prototype, "observed", {
get: function () {
var _a;
return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
},
enumerable: false,
configurable: true
});
Subject.prototype._trySubscribe = function (subscriber) {
this._throwIfClosed();
return _super.prototype._trySubscribe.call(this, subscriber);
};
Subject.prototype._subscribe = function (subscriber) {
this._throwIfClosed();
this._checkFinalizedStatuses(subscriber);
return this._innerSubscribe(subscriber);
};
Subject.prototype._innerSubscribe = function (subscriber) {
var _this = this;
var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
if (hasError || isStopped) {
return Subscription_1.EMPTY_SUBSCRIPTION;
}
this.currentObservers = null;
observers.push(subscriber);
return new Subscription_1.Subscription(function () {
_this.currentObservers = null;
arrRemove_1.arrRemove(observers, subscriber);
});
};
Subject.prototype._checkFinalizedStatuses = function (subscriber) {
var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
if (hasError) {
subscriber.error(thrownError);
}
else if (isStopped) {
subscriber.complete();
}
};
Subject.prototype.asObservable = function () {
var observable = new Observable_1.Observable();
observable.source = this;
return observable;
};
Subject.create = function (destination, source) {
return new AnonymousSubject(destination, source);
};
return Subject;
}(Observable_1.Observable));
exports.Subject = Subject;
var AnonymousSubject = (function (_super) {
__extends(AnonymousSubject, _super);
function AnonymousSubject(destination, source) {
var _this = _super.call(this) || this;
_this.destination = destination;
_this.source = source;
return _this;
}
AnonymousSubject.prototype.next = function (value) {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
};
AnonymousSubject.prototype.error = function (err) {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
};
AnonymousSubject.prototype.complete = function () {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
};
AnonymousSubject.prototype._subscribe = function (subscriber) {
var _a, _b;
return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : Subscription_1.EMPTY_SUBSCRIPTION;
};
return AnonymousSubject;
}(Subject));
exports.AnonymousSubject = AnonymousSubject;
//# sourceMappingURL=Subject.js.map
/***/ }),
/***/ 67121:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EMPTY_OBSERVER = exports.SafeSubscriber = exports.Subscriber = void 0;
var isFunction_1 = __nccwpck_require__(67206);
var Subscription_1 = __nccwpck_require__(79548);
var config_1 = __nccwpck_require__(92233);
var reportUnhandledError_1 = __nccwpck_require__(92445);
var noop_1 = __nccwpck_require__(11642);
var NotificationFactories_1 = __nccwpck_require__(2500);
var timeoutProvider_1 = __nccwpck_require__(1613);
var errorContext_1 = __nccwpck_require__(31199);
var Subscriber = (function (_super) {
__extends(Subscriber, _super);
function Subscriber(destination) {
var _this = _super.call(this) || this;
_this.isStopped = false;
if (destination) {
_this.destination = destination;
if (Subscription_1.isSubscription(destination)) {
destination.add(_this);
}
}
else {
_this.destination = exports.EMPTY_OBSERVER;
}
return _this;
}
Subscriber.create = function (next, error, complete) {
return new SafeSubscriber(next, error, complete);
};
Subscriber.prototype.next = function (value) {
if (this.isStopped) {
handleStoppedNotification(NotificationFactories_1.nextNotification(value), this);
}
else {
this._next(value);
}
};
Subscriber.prototype.error = function (err) {
if (this.isStopped) {
handleStoppedNotification(NotificationFactories_1.errorNotification(err), this);
}
else {
this.isStopped = true;
this._error(err);
}
};
Subscriber.prototype.complete = function () {
if (this.isStopped) {
handleStoppedNotification(NotificationFactories_1.COMPLETE_NOTIFICATION, this);
}
else {
this.isStopped = true;
this._complete();
}
};
Subscriber.prototype.unsubscribe = function () {
if (!this.closed) {
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
this.destination = null;
}
};
Subscriber.prototype._next = function (value) {
this.destination.next(value);
};
Subscriber.prototype._error = function (err) {
try {
this.destination.error(err);
}
finally {
this.unsubscribe();
}
};
Subscriber.prototype._complete = function () {
try {
this.destination.complete();
}
finally {
this.unsubscribe();
}
};
return Subscriber;
}(Subscription_1.Subscription));
exports.Subscriber = Subscriber;
var _bind = Function.prototype.bind;
function bind(fn, thisArg) {
return _bind.call(fn, thisArg);
}
var ConsumerObserver = (function () {
function ConsumerObserver(partialObserver) {
this.partialObserver = partialObserver;
}
ConsumerObserver.prototype.next = function (value) {
var partialObserver = this.partialObserver;
if (partialObserver.next) {
try {
partialObserver.next(value);
}
catch (error) {
handleUnhandledError(error);
}
}
};
ConsumerObserver.prototype.error = function (err) {
var partialObserver = this.partialObserver;
if (partialObserver.error) {
try {
partialObserver.error(err);
}
catch (error) {
handleUnhandledError(error);
}
}
else {
handleUnhandledError(err);
}
};
ConsumerObserver.prototype.complete = function () {
var partialObserver = this.partialObserver;
if (partialObserver.complete) {
try {
partialObserver.complete();
}
catch (error) {
handleUnhandledError(error);
}
}
};
return ConsumerObserver;
}());
var SafeSubscriber = (function (_super) {
__extends(SafeSubscriber, _super);
function SafeSubscriber(observerOrNext, error, complete) {
var _this = _super.call(this) || this;
var partialObserver;
if (isFunction_1.isFunction(observerOrNext) || !observerOrNext) {
partialObserver = {
next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
error: error !== null && error !== void 0 ? error : undefined,
complete: complete !== null && complete !== void 0 ? complete : undefined,
};
}
else {
var context_1;
if (_this && config_1.config.useDeprecatedNextContext) {
context_1 = Object.create(observerOrNext);
context_1.unsubscribe = function () { return _this.unsubscribe(); };
partialObserver = {
next: observerOrNext.next && bind(observerOrNext.next, context_1),
error: observerOrNext.error && bind(observerOrNext.error, context_1),
complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
};
}
else {
partialObserver = observerOrNext;
}
}
_this.destination = new ConsumerObserver(partialObserver);
return _this;
}
return SafeSubscriber;
}(Subscriber));
exports.SafeSubscriber = SafeSubscriber;
function handleUnhandledError(error) {
if (config_1.config.useDeprecatedSynchronousErrorHandling) {
errorContext_1.captureError(error);
}
else {
reportUnhandledError_1.reportUnhandledError(error);
}
}
function defaultErrorHandler(err) {
throw err;
}
function handleStoppedNotification(notification, subscriber) {
var onStoppedNotification = config_1.config.onStoppedNotification;
onStoppedNotification && timeoutProvider_1.timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
}
exports.EMPTY_OBSERVER = {
closed: true,
next: noop_1.noop,
error: defaultErrorHandler,
complete: noop_1.noop,
};
//# sourceMappingURL=Subscriber.js.map
/***/ }),
/***/ 79548:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isSubscription = exports.EMPTY_SUBSCRIPTION = exports.Subscription = void 0;
var isFunction_1 = __nccwpck_require__(67206);
var UnsubscriptionError_1 = __nccwpck_require__(56776);
var arrRemove_1 = __nccwpck_require__(68499);
var Subscription = (function () {
function Subscription(initialTeardown) {
this.initialTeardown = initialTeardown;
this.closed = false;
this._parentage = null;
this._finalizers = null;
}
Subscription.prototype.unsubscribe = function () {
var e_1, _a, e_2, _b;
var errors;
if (!this.closed) {
this.closed = true;
var _parentage = this._parentage;
if (_parentage) {
this._parentage = null;
if (Array.isArray(_parentage)) {
try {
for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
var parent_1 = _parentage_1_1.value;
parent_1.remove(this);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
}
finally { if (e_1) throw e_1.error; }
}
}
else {
_parentage.remove(this);
}
}
var initialFinalizer = this.initialTeardown;
if (isFunction_1.isFunction(initialFinalizer)) {
try {
initialFinalizer();
}
catch (e) {
errors = e instanceof UnsubscriptionError_1.UnsubscriptionError ? e.errors : [e];
}
}
var _finalizers = this._finalizers;
if (_finalizers) {
this._finalizers = null;
try {
for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
var finalizer = _finalizers_1_1.value;
try {
execFinalizer(finalizer);
}
catch (err) {
errors = errors !== null && errors !== void 0 ? errors : [];
if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
}
else {
errors.push(err);
}
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
}
finally { if (e_2) throw e_2.error; }
}
}
if (errors) {
throw new UnsubscriptionError_1.UnsubscriptionError(errors);
}
}
};
Subscription.prototype.add = function (teardown) {
var _a;
if (teardown && teardown !== this) {
if (this.closed) {
execFinalizer(teardown);
}
else {
if (teardown instanceof Subscription) {
if (teardown.closed || teardown._hasParent(this)) {
return;
}
teardown._addParent(this);
}
(this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
}
}
};
Subscription.prototype._hasParent = function (parent) {
var _parentage = this._parentage;
return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
};
Subscription.prototype._addParent = function (parent) {
var _parentage = this._parentage;
this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
};
Subscription.prototype._removeParent = function (parent) {
var _parentage = this._parentage;
if (_parentage === parent) {
this._parentage = null;
}
else if (Array.isArray(_parentage)) {
arrRemove_1.arrRemove(_parentage, parent);
}
};
Subscription.prototype.remove = function (teardown) {
var _finalizers = this._finalizers;
_finalizers && arrRemove_1.arrRemove(_finalizers, teardown);
if (teardown instanceof Subscription) {
teardown._removeParent(this);
}
};
Subscription.EMPTY = (function () {
var empty = new Subscription();
empty.closed = true;
return empty;
})();
return Subscription;
}());
exports.Subscription = Subscription;
exports.EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
return (value instanceof Subscription ||
(value && 'closed' in value && isFunction_1.isFunction(value.remove) && isFunction_1.isFunction(value.add) && isFunction_1.isFunction(value.unsubscribe)));
}
exports.isSubscription = isSubscription;
function execFinalizer(finalizer) {
if (isFunction_1.isFunction(finalizer)) {
finalizer();
}
else {
finalizer.unsubscribe();
}
}
//# sourceMappingURL=Subscription.js.map
/***/ }),
/***/ 92233:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.config = void 0;
exports.config = {
onUnhandledError: null,
onStoppedNotification: null,
Promise: undefined,
useDeprecatedSynchronousErrorHandling: false,
useDeprecatedNextContext: false,
};
//# sourceMappingURL=config.js.map
/***/ }),
/***/ 19369:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.firstValueFrom = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
var Subscriber_1 = __nccwpck_require__(67121);
function firstValueFrom(source, config) {
var hasConfig = typeof config === 'object';
return new Promise(function (resolve, reject) {
var subscriber = new Subscriber_1.SafeSubscriber({
next: function (value) {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: function () {
if (hasConfig) {
resolve(config.defaultValue);
}
else {
reject(new EmptyError_1.EmptyError());
}
},
});
source.subscribe(subscriber);
});
}
exports.firstValueFrom = firstValueFrom;
//# sourceMappingURL=firstValueFrom.js.map
/***/ }),
/***/ 49713:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.lastValueFrom = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
function lastValueFrom(source, config) {
var hasConfig = typeof config === 'object';
return new Promise(function (resolve, reject) {
var _hasValue = false;
var _value;
source.subscribe({
next: function (value) {
_value = value;
_hasValue = true;
},
error: reject,
complete: function () {
if (_hasValue) {
resolve(_value);
}
else if (hasConfig) {
resolve(config.defaultValue);
}
else {
reject(new EmptyError_1.EmptyError());
}
},
});
});
}
exports.lastValueFrom = lastValueFrom;
//# sourceMappingURL=lastValueFrom.js.map
/***/ }),
/***/ 30420:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConnectableObservable = void 0;
var Observable_1 = __nccwpck_require__(53014);
var Subscription_1 = __nccwpck_require__(79548);
var refCount_1 = __nccwpck_require__(2331);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var lift_1 = __nccwpck_require__(38669);
var ConnectableObservable = (function (_super) {
__extends(ConnectableObservable, _super);
function ConnectableObservable(source, subjectFactory) {
var _this = _super.call(this) || this;
_this.source = source;
_this.subjectFactory = subjectFactory;
_this._subject = null;
_this._refCount = 0;
_this._connection = null;
if (lift_1.hasLift(source)) {
_this.lift = source.lift;
}
return _this;
}
ConnectableObservable.prototype._subscribe = function (subscriber) {
return this.getSubject().subscribe(subscriber);
};
ConnectableObservable.prototype.getSubject = function () {
var subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject;
};
ConnectableObservable.prototype._teardown = function () {
this._refCount = 0;
var _connection = this._connection;
this._subject = this._connection = null;
_connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();
};
ConnectableObservable.prototype.connect = function () {
var _this = this;
var connection = this._connection;
if (!connection) {
connection = this._connection = new Subscription_1.Subscription();
var subject_1 = this.getSubject();
connection.add(this.source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subject_1, undefined, function () {
_this._teardown();
subject_1.complete();
}, function (err) {
_this._teardown();
subject_1.error(err);
}, function () { return _this._teardown(); })));
if (connection.closed) {
this._connection = null;
connection = Subscription_1.Subscription.EMPTY;
}
}
return connection;
};
ConnectableObservable.prototype.refCount = function () {
return refCount_1.refCount()(this);
};
return ConnectableObservable;
}(Observable_1.Observable));
exports.ConnectableObservable = ConnectableObservable;
//# sourceMappingURL=ConnectableObservable.js.map
/***/ }),
/***/ 16949:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bindCallback = void 0;
var bindCallbackInternals_1 = __nccwpck_require__(30585);
function bindCallback(callbackFunc, resultSelector, scheduler) {
return bindCallbackInternals_1.bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);
}
exports.bindCallback = bindCallback;
//# sourceMappingURL=bindCallback.js.map
/***/ }),
/***/ 30585:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bindCallbackInternals = void 0;
var isScheduler_1 = __nccwpck_require__(84078);
var Observable_1 = __nccwpck_require__(53014);
var subscribeOn_1 = __nccwpck_require__(7224);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var observeOn_1 = __nccwpck_require__(22451);
var AsyncSubject_1 = __nccwpck_require__(9747);
function bindCallbackInternals(isNodeStyle, callbackFunc, resultSelector, scheduler) {
if (resultSelector) {
if (isScheduler_1.isScheduler(resultSelector)) {
scheduler = resultSelector;
}
else {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return bindCallbackInternals(isNodeStyle, callbackFunc, scheduler)
.apply(this, args)
.pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
};
}
}
if (scheduler) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return bindCallbackInternals(isNodeStyle, callbackFunc)
.apply(this, args)
.pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
};
}
return function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var subject = new AsyncSubject_1.AsyncSubject();
var uninitialized = true;
return new Observable_1.Observable(function (subscriber) {
var subs = subject.subscribe(subscriber);
if (uninitialized) {
uninitialized = false;
var isAsync_1 = false;
var isComplete_1 = false;
callbackFunc.apply(_this, __spreadArray(__spreadArray([], __read(args)), [
function () {
var results = [];
for (var _i = 0; _i < arguments.length; _i++) {
results[_i] = arguments[_i];
}
if (isNodeStyle) {
var err = results.shift();
if (err != null) {
subject.error(err);
return;
}
}
subject.next(1 < results.length ? results : results[0]);
isComplete_1 = true;
if (isAsync_1) {
subject.complete();
}
},
]));
if (isComplete_1) {
subject.complete();
}
isAsync_1 = true;
}
return subs;
});
};
}
exports.bindCallbackInternals = bindCallbackInternals;
//# sourceMappingURL=bindCallbackInternals.js.map
/***/ }),
/***/ 51150:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bindNodeCallback = void 0;
var bindCallbackInternals_1 = __nccwpck_require__(30585);
function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
return bindCallbackInternals_1.bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);
}
exports.bindNodeCallback = bindNodeCallback;
//# sourceMappingURL=bindNodeCallback.js.map
/***/ }),
/***/ 46843:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineLatestInit = exports.combineLatest = void 0;
var Observable_1 = __nccwpck_require__(53014);
var argsArgArrayOrObject_1 = __nccwpck_require__(12920);
var from_1 = __nccwpck_require__(18309);
var identity_1 = __nccwpck_require__(60283);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var args_1 = __nccwpck_require__(34890);
var createObject_1 = __nccwpck_require__(57834);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var executeSchedule_1 = __nccwpck_require__(82877);
function combineLatest() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(args);
var resultSelector = args_1.popResultSelector(args);
var _a = argsArgArrayOrObject_1.argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
if (observables.length === 0) {
return from_1.from([], scheduler);
}
var result = new Observable_1.Observable(combineLatestInit(observables, scheduler, keys
?
function (values) { return createObject_1.createObject(keys, values); }
:
identity_1.identity));
return resultSelector ? result.pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector)) : result;
}
exports.combineLatest = combineLatest;
function combineLatestInit(observables, scheduler, valueTransform) {
if (valueTransform === void 0) { valueTransform = identity_1.identity; }
return function (subscriber) {
maybeSchedule(scheduler, function () {
var length = observables.length;
var values = new Array(length);
var active = length;
var remainingFirstValues = length;
var _loop_1 = function (i) {
maybeSchedule(scheduler, function () {
var source = from_1.from(observables[i], scheduler);
var hasFirstValue = false;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
values[i] = value;
if (!hasFirstValue) {
hasFirstValue = true;
remainingFirstValues--;
}
if (!remainingFirstValues) {
subscriber.next(valueTransform(values.slice()));
}
}, function () {
if (!--active) {
subscriber.complete();
}
}));
}, subscriber);
};
for (var i = 0; i < length; i++) {
_loop_1(i);
}
}, subscriber);
};
}
exports.combineLatestInit = combineLatestInit;
function maybeSchedule(scheduler, execute, subscription) {
if (scheduler) {
executeSchedule_1.executeSchedule(subscription, scheduler, execute);
}
else {
execute();
}
}
//# sourceMappingURL=combineLatest.js.map
/***/ }),
/***/ 4675:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concat = void 0;
var concatAll_1 = __nccwpck_require__(88049);
var args_1 = __nccwpck_require__(34890);
var from_1 = __nccwpck_require__(18309);
function concat() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return concatAll_1.concatAll()(from_1.from(args, args_1.popScheduler(args)));
}
exports.concat = concat;
//# sourceMappingURL=concat.js.map
/***/ }),
/***/ 13152:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.connectable = void 0;
var Subject_1 = __nccwpck_require__(49944);
var Observable_1 = __nccwpck_require__(53014);
var defer_1 = __nccwpck_require__(27672);
var DEFAULT_CONFIG = {
connector: function () { return new Subject_1.Subject(); },
resetOnDisconnect: true,
};
function connectable(source, config) {
if (config === void 0) { config = DEFAULT_CONFIG; }
var connection = null;
var connector = config.connector, _a = config.resetOnDisconnect, resetOnDisconnect = _a === void 0 ? true : _a;
var subject = connector();
var result = new Observable_1.Observable(function (subscriber) {
return subject.subscribe(subscriber);
});
result.connect = function () {
if (!connection || connection.closed) {
connection = defer_1.defer(function () { return source; }).subscribe(subject);
if (resetOnDisconnect) {
connection.add(function () { return (subject = connector()); });
}
}
return connection;
};
return result;
}
exports.connectable = connectable;
//# sourceMappingURL=connectable.js.map
/***/ }),
/***/ 27672:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.defer = void 0;
var Observable_1 = __nccwpck_require__(53014);
var innerFrom_1 = __nccwpck_require__(57105);
function defer(observableFactory) {
return new Observable_1.Observable(function (subscriber) {
innerFrom_1.innerFrom(observableFactory()).subscribe(subscriber);
});
}
exports.defer = defer;
//# sourceMappingURL=defer.js.map
/***/ }),
/***/ 38197:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.animationFrames = void 0;
var Observable_1 = __nccwpck_require__(53014);
var performanceTimestampProvider_1 = __nccwpck_require__(70143);
var animationFrameProvider_1 = __nccwpck_require__(62738);
function animationFrames(timestampProvider) {
return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;
}
exports.animationFrames = animationFrames;
function animationFramesFactory(timestampProvider) {
return new Observable_1.Observable(function (subscriber) {
var provider = timestampProvider || performanceTimestampProvider_1.performanceTimestampProvider;
var start = provider.now();
var id = 0;
var run = function () {
if (!subscriber.closed) {
id = animationFrameProvider_1.animationFrameProvider.requestAnimationFrame(function (timestamp) {
id = 0;
var now = provider.now();
subscriber.next({
timestamp: timestampProvider ? now : timestamp,
elapsed: now - start,
});
run();
});
}
};
run();
return function () {
if (id) {
animationFrameProvider_1.animationFrameProvider.cancelAnimationFrame(id);
}
};
});
}
var DEFAULT_ANIMATION_FRAMES = animationFramesFactory();
//# sourceMappingURL=animationFrames.js.map
/***/ }),
/***/ 70437:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.empty = exports.EMPTY = void 0;
var Observable_1 = __nccwpck_require__(53014);
exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); });
function empty(scheduler) {
return scheduler ? emptyScheduled(scheduler) : exports.EMPTY;
}
exports.empty = empty;
function emptyScheduled(scheduler) {
return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
}
//# sourceMappingURL=empty.js.map
/***/ }),
/***/ 47358:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.forkJoin = void 0;
var Observable_1 = __nccwpck_require__(53014);
var argsArgArrayOrObject_1 = __nccwpck_require__(12920);
var innerFrom_1 = __nccwpck_require__(57105);
var args_1 = __nccwpck_require__(34890);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var createObject_1 = __nccwpck_require__(57834);
function forkJoin() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var resultSelector = args_1.popResultSelector(args);
var _a = argsArgArrayOrObject_1.argsArgArrayOrObject(args), sources = _a.args, keys = _a.keys;
var result = new Observable_1.Observable(function (subscriber) {
var length = sources.length;
if (!length) {
subscriber.complete();
return;
}
var values = new Array(length);
var remainingCompletions = length;
var remainingEmissions = length;
var _loop_1 = function (sourceIndex) {
var hasValue = false;
innerFrom_1.innerFrom(sources[sourceIndex]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (!hasValue) {
hasValue = true;
remainingEmissions--;
}
values[sourceIndex] = value;
}, function () { return remainingCompletions--; }, undefined, function () {
if (!remainingCompletions || !hasValue) {
if (!remainingEmissions) {
subscriber.next(keys ? createObject_1.createObject(keys, values) : values);
}
subscriber.complete();
}
}));
};
for (var sourceIndex = 0; sourceIndex < length; sourceIndex++) {
_loop_1(sourceIndex);
}
});
return resultSelector ? result.pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector)) : result;
}
exports.forkJoin = forkJoin;
//# sourceMappingURL=forkJoin.js.map
/***/ }),
/***/ 18309:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.from = void 0;
var scheduled_1 = __nccwpck_require__(6151);
var innerFrom_1 = __nccwpck_require__(57105);
function from(input, scheduler) {
return scheduler ? scheduled_1.scheduled(input, scheduler) : innerFrom_1.innerFrom(input);
}
exports.from = from;
//# sourceMappingURL=from.js.map
/***/ }),
/***/ 93238:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fromEvent = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var Observable_1 = __nccwpck_require__(53014);
var mergeMap_1 = __nccwpck_require__(69914);
var isArrayLike_1 = __nccwpck_require__(24461);
var isFunction_1 = __nccwpck_require__(67206);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var nodeEventEmitterMethods = ['addListener', 'removeListener'];
var eventTargetMethods = ['addEventListener', 'removeEventListener'];
var jqueryMethods = ['on', 'off'];
function fromEvent(target, eventName, options, resultSelector) {
if (isFunction_1.isFunction(options)) {
resultSelector = options;
options = undefined;
}
if (resultSelector) {
return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
}
var _a = __read(isEventTarget(target)
? eventTargetMethods.map(function (methodName) { return function (handler) { return target[methodName](eventName, handler, options); }; })
:
isNodeStyleEventEmitter(target)
? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
: isJQueryStyleEventEmitter(target)
? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
: [], 2), add = _a[0], remove = _a[1];
if (!add) {
if (isArrayLike_1.isArrayLike(target)) {
return mergeMap_1.mergeMap(function (subTarget) { return fromEvent(subTarget, eventName, options); })(innerFrom_1.innerFrom(target));
}
}
if (!add) {
throw new TypeError('Invalid event target');
}
return new Observable_1.Observable(function (subscriber) {
var handler = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return subscriber.next(1 < args.length ? args : args[0]);
};
add(handler);
return function () { return remove(handler); };
});
}
exports.fromEvent = fromEvent;
function toCommonHandlerRegistry(target, eventName) {
return function (methodName) { return function (handler) { return target[methodName](eventName, handler); }; };
}
function isNodeStyleEventEmitter(target) {
return isFunction_1.isFunction(target.addListener) && isFunction_1.isFunction(target.removeListener);
}
function isJQueryStyleEventEmitter(target) {
return isFunction_1.isFunction(target.on) && isFunction_1.isFunction(target.off);
}
function isEventTarget(target) {
return isFunction_1.isFunction(target.addEventListener) && isFunction_1.isFunction(target.removeEventListener);
}
//# sourceMappingURL=fromEvent.js.map
/***/ }),
/***/ 65680:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fromEventPattern = void 0;
var Observable_1 = __nccwpck_require__(53014);
var isFunction_1 = __nccwpck_require__(67206);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
function fromEventPattern(addHandler, removeHandler, resultSelector) {
if (resultSelector) {
return fromEventPattern(addHandler, removeHandler).pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
}
return new Observable_1.Observable(function (subscriber) {
var handler = function () {
var e = [];
for (var _i = 0; _i < arguments.length; _i++) {
e[_i] = arguments[_i];
}
return subscriber.next(e.length === 1 ? e[0] : e);
};
var retValue = addHandler(handler);
return isFunction_1.isFunction(removeHandler) ? function () { return removeHandler(handler, retValue); } : undefined;
});
}
exports.fromEventPattern = fromEventPattern;
//# sourceMappingURL=fromEventPattern.js.map
/***/ }),
/***/ 66513:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fromSubscribable = void 0;
var Observable_1 = __nccwpck_require__(53014);
function fromSubscribable(subscribable) {
return new Observable_1.Observable(function (subscriber) { return subscribable.subscribe(subscriber); });
}
exports.fromSubscribable = fromSubscribable;
//# sourceMappingURL=fromSubscribable.js.map
/***/ }),
/***/ 52668:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.generate = void 0;
var identity_1 = __nccwpck_require__(60283);
var isScheduler_1 = __nccwpck_require__(84078);
var defer_1 = __nccwpck_require__(27672);
var scheduleIterable_1 = __nccwpck_require__(59461);
function generate(initialStateOrOptions, condition, iterate, resultSelectorOrScheduler, scheduler) {
var _a, _b;
var resultSelector;
var initialState;
if (arguments.length === 1) {
(_a = initialStateOrOptions, initialState = _a.initialState, condition = _a.condition, iterate = _a.iterate, _b = _a.resultSelector, resultSelector = _b === void 0 ? identity_1.identity : _b, scheduler = _a.scheduler);
}
else {
initialState = initialStateOrOptions;
if (!resultSelectorOrScheduler || isScheduler_1.isScheduler(resultSelectorOrScheduler)) {
resultSelector = identity_1.identity;
scheduler = resultSelectorOrScheduler;
}
else {
resultSelector = resultSelectorOrScheduler;
}
}
function gen() {
var state;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
state = initialState;
_a.label = 1;
case 1:
if (!(!condition || condition(state))) return [3, 4];
return [4, resultSelector(state)];
case 2:
_a.sent();
_a.label = 3;
case 3:
state = iterate(state);
return [3, 1];
case 4: return [2];
}
});
}
return defer_1.defer((scheduler
?
function () { return scheduleIterable_1.scheduleIterable(gen(), scheduler); }
:
gen));
}
exports.generate = generate;
//# sourceMappingURL=generate.js.map
/***/ }),
/***/ 26514:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.iif = void 0;
var defer_1 = __nccwpck_require__(27672);
function iif(condition, trueResult, falseResult) {
return defer_1.defer(function () { return (condition() ? trueResult : falseResult); });
}
exports.iif = iif;
//# sourceMappingURL=iif.js.map
/***/ }),
/***/ 57105:
/***/ (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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fromReadableStreamLike = exports.fromAsyncIterable = exports.fromIterable = exports.fromPromise = exports.fromArrayLike = exports.fromInteropObservable = exports.innerFrom = void 0;
var isArrayLike_1 = __nccwpck_require__(24461);
var isPromise_1 = __nccwpck_require__(65585);
var Observable_1 = __nccwpck_require__(53014);
var isInteropObservable_1 = __nccwpck_require__(67984);
var isAsyncIterable_1 = __nccwpck_require__(44408);
var throwUnobservableError_1 = __nccwpck_require__(97364);
var isIterable_1 = __nccwpck_require__(94292);
var isReadableStreamLike_1 = __nccwpck_require__(99621);
var isFunction_1 = __nccwpck_require__(67206);
var reportUnhandledError_1 = __nccwpck_require__(92445);
var observable_1 = __nccwpck_require__(17186);
function innerFrom(input) {
if (input instanceof Observable_1.Observable) {
return input;
}
if (input != null) {
if (isInteropObservable_1.isInteropObservable(input)) {
return fromInteropObservable(input);
}
if (isArrayLike_1.isArrayLike(input)) {
return fromArrayLike(input);
}
if (isPromise_1.isPromise(input)) {
return fromPromise(input);
}
if (isAsyncIterable_1.isAsyncIterable(input)) {
return fromAsyncIterable(input);
}
if (isIterable_1.isIterable(input)) {
return fromIterable(input);
}
if (isReadableStreamLike_1.isReadableStreamLike(input)) {
return fromReadableStreamLike(input);
}
}
throw throwUnobservableError_1.createInvalidObservableTypeError(input);
}
exports.innerFrom = innerFrom;
function fromInteropObservable(obj) {
return new Observable_1.Observable(function (subscriber) {
var obs = obj[observable_1.observable]();
if (isFunction_1.isFunction(obs.subscribe)) {
return obs.subscribe(subscriber);
}
throw new TypeError('Provided object does not correctly implement Symbol.observable');
});
}
exports.fromInteropObservable = fromInteropObservable;
function fromArrayLike(array) {
return new Observable_1.Observable(function (subscriber) {
for (var i = 0; i < array.length && !subscriber.closed; i++) {
subscriber.next(array[i]);
}
subscriber.complete();
});
}
exports.fromArrayLike = fromArrayLike;
function fromPromise(promise) {
return new Observable_1.Observable(function (subscriber) {
promise
.then(function (value) {
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
}, function (err) { return subscriber.error(err); })
.then(null, reportUnhandledError_1.reportUnhandledError);
});
}
exports.fromPromise = fromPromise;
function fromIterable(iterable) {
return new Observable_1.Observable(function (subscriber) {
var e_1, _a;
try {
for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
var value = iterable_1_1.value;
subscriber.next(value);
if (subscriber.closed) {
return;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
}
finally { if (e_1) throw e_1.error; }
}
subscriber.complete();
});
}
exports.fromIterable = fromIterable;
function fromAsyncIterable(asyncIterable) {
return new Observable_1.Observable(function (subscriber) {
process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
});
}
exports.fromAsyncIterable = fromAsyncIterable;
function fromReadableStreamLike(readableStream) {
return fromAsyncIterable(isReadableStreamLike_1.readableStreamLikeToAsyncGenerator(readableStream));
}
exports.fromReadableStreamLike = fromReadableStreamLike;
function process(asyncIterable, subscriber) {
var asyncIterable_1, asyncIterable_1_1;
var e_2, _a;
return __awaiter(this, void 0, void 0, function () {
var value, e_2_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 5, 6, 11]);
asyncIterable_1 = __asyncValues(asyncIterable);
_b.label = 1;
case 1: return [4, asyncIterable_1.next()];
case 2:
if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
value = asyncIterable_1_1.value;
subscriber.next(value);
if (subscriber.closed) {
return [2];
}
_b.label = 3;
case 3: return [3, 1];
case 4: return [3, 11];
case 5:
e_2_1 = _b.sent();
e_2 = { error: e_2_1 };
return [3, 11];
case 6:
_b.trys.push([6, , 9, 10]);
if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
return [4, _a.call(asyncIterable_1)];
case 7:
_b.sent();
_b.label = 8;
case 8: return [3, 10];
case 9:
if (e_2) throw e_2.error;
return [7];
case 10: return [7];
case 11:
subscriber.complete();
return [2];
}
});
});
}
//# sourceMappingURL=innerFrom.js.map
/***/ }),
/***/ 20029:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.interval = void 0;
var async_1 = __nccwpck_require__(76072);
var timer_1 = __nccwpck_require__(59757);
function interval(period, scheduler) {
if (period === void 0) { period = 0; }
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
if (period < 0) {
period = 0;
}
return timer_1.timer(period, period, scheduler);
}
exports.interval = interval;
//# sourceMappingURL=interval.js.map
/***/ }),
/***/ 75122:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.merge = void 0;
var mergeAll_1 = __nccwpck_require__(2057);
var innerFrom_1 = __nccwpck_require__(57105);
var empty_1 = __nccwpck_require__(70437);
var args_1 = __nccwpck_require__(34890);
var from_1 = __nccwpck_require__(18309);
function merge() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(args);
var concurrent = args_1.popNumber(args, Infinity);
var sources = args;
return !sources.length
?
empty_1.EMPTY
: sources.length === 1
?
innerFrom_1.innerFrom(sources[0])
:
mergeAll_1.mergeAll(concurrent)(from_1.from(sources, scheduler));
}
exports.merge = merge;
//# sourceMappingURL=merge.js.map
/***/ }),
/***/ 6228:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.never = exports.NEVER = void 0;
var Observable_1 = __nccwpck_require__(53014);
var noop_1 = __nccwpck_require__(11642);
exports.NEVER = new Observable_1.Observable(noop_1.noop);
function never() {
return exports.NEVER;
}
exports.never = never;
//# sourceMappingURL=never.js.map
/***/ }),
/***/ 72163:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.of = void 0;
var args_1 = __nccwpck_require__(34890);
var from_1 = __nccwpck_require__(18309);
function of() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(args);
return from_1.from(args, scheduler);
}
exports.of = of;
//# sourceMappingURL=of.js.map
/***/ }),
/***/ 16089:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.onErrorResumeNext = void 0;
var Observable_1 = __nccwpck_require__(53014);
var argsOrArgArray_1 = __nccwpck_require__(18824);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
var innerFrom_1 = __nccwpck_require__(57105);
function onErrorResumeNext() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
var nextSources = argsOrArgArray_1.argsOrArgArray(sources);
return new Observable_1.Observable(function (subscriber) {
var sourceIndex = 0;
var subscribeNext = function () {
if (sourceIndex < nextSources.length) {
var nextSource = void 0;
try {
nextSource = innerFrom_1.innerFrom(nextSources[sourceIndex++]);
}
catch (err) {
subscribeNext();
return;
}
var innerSubscriber = new OperatorSubscriber_1.OperatorSubscriber(subscriber, undefined, noop_1.noop, noop_1.noop);
nextSource.subscribe(innerSubscriber);
innerSubscriber.add(subscribeNext);
}
else {
subscriber.complete();
}
};
subscribeNext();
});
}
exports.onErrorResumeNext = onErrorResumeNext;
//# sourceMappingURL=onErrorResumeNext.js.map
/***/ }),
/***/ 30505:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pairs = void 0;
var from_1 = __nccwpck_require__(18309);
function pairs(obj, scheduler) {
return from_1.from(Object.entries(obj), scheduler);
}
exports.pairs = pairs;
//# sourceMappingURL=pairs.js.map
/***/ }),
/***/ 15506:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.partition = void 0;
var not_1 = __nccwpck_require__(54338);
var filter_1 = __nccwpck_require__(36894);
var innerFrom_1 = __nccwpck_require__(57105);
function partition(source, predicate, thisArg) {
return [filter_1.filter(predicate, thisArg)(innerFrom_1.innerFrom(source)), filter_1.filter(not_1.not(predicate, thisArg))(innerFrom_1.innerFrom(source))];
}
exports.partition = partition;
//# sourceMappingURL=partition.js.map
/***/ }),
/***/ 16940:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.raceInit = exports.race = void 0;
var Observable_1 = __nccwpck_require__(53014);
var innerFrom_1 = __nccwpck_require__(57105);
var argsOrArgArray_1 = __nccwpck_require__(18824);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function race() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
sources = argsOrArgArray_1.argsOrArgArray(sources);
return sources.length === 1 ? innerFrom_1.innerFrom(sources[0]) : new Observable_1.Observable(raceInit(sources));
}
exports.race = race;
function raceInit(sources) {
return function (subscriber) {
var subscriptions = [];
var _loop_1 = function (i) {
subscriptions.push(innerFrom_1.innerFrom(sources[i]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (subscriptions) {
for (var s = 0; s < subscriptions.length; s++) {
s !== i && subscriptions[s].unsubscribe();
}
subscriptions = null;
}
subscriber.next(value);
})));
};
for (var i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
_loop_1(i);
}
};
}
exports.raceInit = raceInit;
//# sourceMappingURL=race.js.map
/***/ }),
/***/ 88538:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.range = void 0;
var Observable_1 = __nccwpck_require__(53014);
var empty_1 = __nccwpck_require__(70437);
function range(start, count, scheduler) {
if (count == null) {
count = start;
start = 0;
}
if (count <= 0) {
return empty_1.EMPTY;
}
var end = count + start;
return new Observable_1.Observable(scheduler
?
function (subscriber) {
var n = start;
return scheduler.schedule(function () {
if (n < end) {
subscriber.next(n++);
this.schedule();
}
else {
subscriber.complete();
}
});
}
:
function (subscriber) {
var n = start;
while (n < end && !subscriber.closed) {
subscriber.next(n++);
}
subscriber.complete();
});
}
exports.range = range;
//# sourceMappingURL=range.js.map
/***/ }),
/***/ 66381:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.throwError = void 0;
var Observable_1 = __nccwpck_require__(53014);
var isFunction_1 = __nccwpck_require__(67206);
function throwError(errorOrErrorFactory, scheduler) {
var errorFactory = isFunction_1.isFunction(errorOrErrorFactory) ? errorOrErrorFactory : function () { return errorOrErrorFactory; };
var init = function (subscriber) { return subscriber.error(errorFactory()); };
return new Observable_1.Observable(scheduler ? function (subscriber) { return scheduler.schedule(init, 0, subscriber); } : init);
}
exports.throwError = throwError;
//# sourceMappingURL=throwError.js.map
/***/ }),
/***/ 59757:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timer = void 0;
var Observable_1 = __nccwpck_require__(53014);
var async_1 = __nccwpck_require__(76072);
var isScheduler_1 = __nccwpck_require__(84078);
var isDate_1 = __nccwpck_require__(60935);
function timer(dueTime, intervalOrScheduler, scheduler) {
if (dueTime === void 0) { dueTime = 0; }
if (scheduler === void 0) { scheduler = async_1.async; }
var intervalDuration = -1;
if (intervalOrScheduler != null) {
if (isScheduler_1.isScheduler(intervalOrScheduler)) {
scheduler = intervalOrScheduler;
}
else {
intervalDuration = intervalOrScheduler;
}
}
return new Observable_1.Observable(function (subscriber) {
var due = isDate_1.isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
if (due < 0) {
due = 0;
}
var n = 0;
return scheduler.schedule(function () {
if (!subscriber.closed) {
subscriber.next(n++);
if (0 <= intervalDuration) {
this.schedule(undefined, intervalDuration);
}
else {
subscriber.complete();
}
}
}, due);
});
}
exports.timer = timer;
//# sourceMappingURL=timer.js.map
/***/ }),
/***/ 8445:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.using = void 0;
var Observable_1 = __nccwpck_require__(53014);
var innerFrom_1 = __nccwpck_require__(57105);
var empty_1 = __nccwpck_require__(70437);
function using(resourceFactory, observableFactory) {
return new Observable_1.Observable(function (subscriber) {
var resource = resourceFactory();
var result = observableFactory(resource);
var source = result ? innerFrom_1.innerFrom(result) : empty_1.EMPTY;
source.subscribe(subscriber);
return function () {
if (resource) {
resource.unsubscribe();
}
};
});
}
exports.using = using;
//# sourceMappingURL=using.js.map
/***/ }),
/***/ 62504:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.zip = void 0;
var Observable_1 = __nccwpck_require__(53014);
var innerFrom_1 = __nccwpck_require__(57105);
var argsOrArgArray_1 = __nccwpck_require__(18824);
var empty_1 = __nccwpck_require__(70437);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var args_1 = __nccwpck_require__(34890);
function zip() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var resultSelector = args_1.popResultSelector(args);
var sources = argsOrArgArray_1.argsOrArgArray(args);
return sources.length
? new Observable_1.Observable(function (subscriber) {
var buffers = sources.map(function () { return []; });
var completed = sources.map(function () { return false; });
subscriber.add(function () {
buffers = completed = null;
});
var _loop_1 = function (sourceIndex) {
innerFrom_1.innerFrom(sources[sourceIndex]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
buffers[sourceIndex].push(value);
if (buffers.every(function (buffer) { return buffer.length; })) {
var result = buffers.map(function (buffer) { return buffer.shift(); });
subscriber.next(resultSelector ? resultSelector.apply(void 0, __spreadArray([], __read(result))) : result);
if (buffers.some(function (buffer, i) { return !buffer.length && completed[i]; })) {
subscriber.complete();
}
}
}, function () {
completed[sourceIndex] = true;
!buffers[sourceIndex].length && subscriber.complete();
}));
};
for (var sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {
_loop_1(sourceIndex);
}
return function () {
buffers = completed = null;
};
})
: empty_1.EMPTY;
}
exports.zip = zip;
//# sourceMappingURL=zip.js.map
/***/ }),
/***/ 69549:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OperatorSubscriber = exports.createOperatorSubscriber = void 0;
var Subscriber_1 = __nccwpck_require__(67121);
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
exports.createOperatorSubscriber = createOperatorSubscriber;
var OperatorSubscriber = (function (_super) {
__extends(OperatorSubscriber, _super);
function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
var _this = _super.call(this, destination) || this;
_this.onFinalize = onFinalize;
_this.shouldUnsubscribe = shouldUnsubscribe;
_this._next = onNext
? function (value) {
try {
onNext(value);
}
catch (err) {
destination.error(err);
}
}
: _super.prototype._next;
_this._error = onError
? function (err) {
try {
onError(err);
}
catch (err) {
destination.error(err);
}
finally {
this.unsubscribe();
}
}
: _super.prototype._error;
_this._complete = onComplete
? function () {
try {
onComplete();
}
catch (err) {
destination.error(err);
}
finally {
this.unsubscribe();
}
}
: _super.prototype._complete;
return _this;
}
OperatorSubscriber.prototype.unsubscribe = function () {
var _a;
if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
var closed_1 = this.closed;
_super.prototype.unsubscribe.call(this);
!closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
}
};
return OperatorSubscriber;
}(Subscriber_1.Subscriber));
exports.OperatorSubscriber = OperatorSubscriber;
//# sourceMappingURL=OperatorSubscriber.js.map
/***/ }),
/***/ 43471:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.audit = void 0;
var lift_1 = __nccwpck_require__(38669);
var innerFrom_1 = __nccwpck_require__(57105);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function audit(durationSelector) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
var lastValue = null;
var durationSubscriber = null;
var isComplete = false;
var endDuration = function () {
durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
durationSubscriber = null;
if (hasValue) {
hasValue = false;
var value = lastValue;
lastValue = null;
subscriber.next(value);
}
isComplete && subscriber.complete();
};
var cleanupDuration = function () {
durationSubscriber = null;
isComplete && subscriber.complete();
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
hasValue = true;
lastValue = value;
if (!durationSubscriber) {
innerFrom_1.innerFrom(durationSelector(value)).subscribe((durationSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, endDuration, cleanupDuration)));
}
}, function () {
isComplete = true;
(!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();
}));
});
}
exports.audit = audit;
//# sourceMappingURL=audit.js.map
/***/ }),
/***/ 18780:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.auditTime = void 0;
var async_1 = __nccwpck_require__(76072);
var audit_1 = __nccwpck_require__(43471);
var timer_1 = __nccwpck_require__(59757);
function auditTime(duration, scheduler) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
}
exports.auditTime = auditTime;
//# sourceMappingURL=auditTime.js.map
/***/ }),
/***/ 34253:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.buffer = void 0;
var lift_1 = __nccwpck_require__(38669);
var noop_1 = __nccwpck_require__(11642);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function buffer(closingNotifier) {
return lift_1.operate(function (source, subscriber) {
var currentBuffer = [];
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return currentBuffer.push(value); }, function () {
subscriber.next(currentBuffer);
subscriber.complete();
}));
innerFrom_1.innerFrom(closingNotifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
var b = currentBuffer;
currentBuffer = [];
subscriber.next(b);
}, noop_1.noop));
return function () {
currentBuffer = null;
};
});
}
exports.buffer = buffer;
//# sourceMappingURL=buffer.js.map
/***/ }),
/***/ 17253:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bufferCount = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var arrRemove_1 = __nccwpck_require__(68499);
function bufferCount(bufferSize, startBufferEvery) {
if (startBufferEvery === void 0) { startBufferEvery = null; }
startBufferEvery = startBufferEvery !== null && startBufferEvery !== void 0 ? startBufferEvery : bufferSize;
return lift_1.operate(function (source, subscriber) {
var buffers = [];
var count = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var e_1, _a, e_2, _b;
var toEmit = null;
if (count++ % startBufferEvery === 0) {
buffers.push([]);
}
try {
for (var buffers_1 = __values(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
var buffer = buffers_1_1.value;
buffer.push(value);
if (bufferSize <= buffer.length) {
toEmit = toEmit !== null && toEmit !== void 0 ? toEmit : [];
toEmit.push(buffer);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
}
finally { if (e_1) throw e_1.error; }
}
if (toEmit) {
try {
for (var toEmit_1 = __values(toEmit), toEmit_1_1 = toEmit_1.next(); !toEmit_1_1.done; toEmit_1_1 = toEmit_1.next()) {
var buffer = toEmit_1_1.value;
arrRemove_1.arrRemove(buffers, buffer);
subscriber.next(buffer);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (toEmit_1_1 && !toEmit_1_1.done && (_b = toEmit_1.return)) _b.call(toEmit_1);
}
finally { if (e_2) throw e_2.error; }
}
}
}, function () {
var e_3, _a;
try {
for (var buffers_2 = __values(buffers), buffers_2_1 = buffers_2.next(); !buffers_2_1.done; buffers_2_1 = buffers_2.next()) {
var buffer = buffers_2_1.value;
subscriber.next(buffer);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (buffers_2_1 && !buffers_2_1.done && (_a = buffers_2.return)) _a.call(buffers_2);
}
finally { if (e_3) throw e_3.error; }
}
subscriber.complete();
}, undefined, function () {
buffers = null;
}));
});
}
exports.bufferCount = bufferCount;
//# sourceMappingURL=bufferCount.js.map
/***/ }),
/***/ 73102:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bufferTime = void 0;
var Subscription_1 = __nccwpck_require__(79548);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var arrRemove_1 = __nccwpck_require__(68499);
var async_1 = __nccwpck_require__(76072);
var args_1 = __nccwpck_require__(34890);
var executeSchedule_1 = __nccwpck_require__(82877);
function bufferTime(bufferTimeSpan) {
var _a, _b;
var otherArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
otherArgs[_i - 1] = arguments[_i];
}
var scheduler = (_a = args_1.popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : async_1.asyncScheduler;
var bufferCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null;
var maxBufferSize = otherArgs[1] || Infinity;
return lift_1.operate(function (source, subscriber) {
var bufferRecords = [];
var restartOnEmit = false;
var emit = function (record) {
var buffer = record.buffer, subs = record.subs;
subs.unsubscribe();
arrRemove_1.arrRemove(bufferRecords, record);
subscriber.next(buffer);
restartOnEmit && startBuffer();
};
var startBuffer = function () {
if (bufferRecords) {
var subs = new Subscription_1.Subscription();
subscriber.add(subs);
var buffer = [];
var record_1 = {
buffer: buffer,
subs: subs,
};
bufferRecords.push(record_1);
executeSchedule_1.executeSchedule(subs, scheduler, function () { return emit(record_1); }, bufferTimeSpan);
}
};
if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
executeSchedule_1.executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);
}
else {
restartOnEmit = true;
}
startBuffer();
var bufferTimeSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var e_1, _a;
var recordsCopy = bufferRecords.slice();
try {
for (var recordsCopy_1 = __values(recordsCopy), recordsCopy_1_1 = recordsCopy_1.next(); !recordsCopy_1_1.done; recordsCopy_1_1 = recordsCopy_1.next()) {
var record = recordsCopy_1_1.value;
var buffer = record.buffer;
buffer.push(value);
maxBufferSize <= buffer.length && emit(record);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (recordsCopy_1_1 && !recordsCopy_1_1.done && (_a = recordsCopy_1.return)) _a.call(recordsCopy_1);
}
finally { if (e_1) throw e_1.error; }
}
}, function () {
while (bufferRecords === null || bufferRecords === void 0 ? void 0 : bufferRecords.length) {
subscriber.next(bufferRecords.shift().buffer);
}
bufferTimeSubscriber === null || bufferTimeSubscriber === void 0 ? void 0 : bufferTimeSubscriber.unsubscribe();
subscriber.complete();
subscriber.unsubscribe();
}, undefined, function () { return (bufferRecords = null); });
source.subscribe(bufferTimeSubscriber);
});
}
exports.bufferTime = bufferTime;
//# sourceMappingURL=bufferTime.js.map
/***/ }),
/***/ 83781:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bufferToggle = void 0;
var Subscription_1 = __nccwpck_require__(79548);
var lift_1 = __nccwpck_require__(38669);
var innerFrom_1 = __nccwpck_require__(57105);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
var arrRemove_1 = __nccwpck_require__(68499);
function bufferToggle(openings, closingSelector) {
return lift_1.operate(function (source, subscriber) {
var buffers = [];
innerFrom_1.innerFrom(openings).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (openValue) {
var buffer = [];
buffers.push(buffer);
var closingSubscription = new Subscription_1.Subscription();
var emitBuffer = function () {
arrRemove_1.arrRemove(buffers, buffer);
subscriber.next(buffer);
closingSubscription.unsubscribe();
};
closingSubscription.add(innerFrom_1.innerFrom(closingSelector(openValue)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, emitBuffer, noop_1.noop)));
}, noop_1.noop));
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var e_1, _a;
try {
for (var buffers_1 = __values(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
var buffer = buffers_1_1.value;
buffer.push(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
}
finally { if (e_1) throw e_1.error; }
}
}, function () {
while (buffers.length > 0) {
subscriber.next(buffers.shift());
}
subscriber.complete();
}));
});
}
exports.bufferToggle = bufferToggle;
//# sourceMappingURL=bufferToggle.js.map
/***/ }),
/***/ 82855:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.bufferWhen = void 0;
var lift_1 = __nccwpck_require__(38669);
var noop_1 = __nccwpck_require__(11642);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function bufferWhen(closingSelector) {
return lift_1.operate(function (source, subscriber) {
var buffer = null;
var closingSubscriber = null;
var openBuffer = function () {
closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
var b = buffer;
buffer = [];
b && subscriber.next(b);
innerFrom_1.innerFrom(closingSelector()).subscribe((closingSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, openBuffer, noop_1.noop)));
};
openBuffer();
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return buffer === null || buffer === void 0 ? void 0 : buffer.push(value); }, function () {
buffer && subscriber.next(buffer);
subscriber.complete();
}, undefined, function () { return (buffer = closingSubscriber = null); }));
});
}
exports.bufferWhen = bufferWhen;
//# sourceMappingURL=bufferWhen.js.map
/***/ }),
/***/ 37765:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.catchError = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var lift_1 = __nccwpck_require__(38669);
function catchError(selector) {
return lift_1.operate(function (source, subscriber) {
var innerSub = null;
var syncUnsub = false;
var handledResult;
innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
handledResult = innerFrom_1.innerFrom(selector(err, catchError(selector)(source)));
if (innerSub) {
innerSub.unsubscribe();
innerSub = null;
handledResult.subscribe(subscriber);
}
else {
syncUnsub = true;
}
}));
if (syncUnsub) {
innerSub.unsubscribe();
innerSub = null;
handledResult.subscribe(subscriber);
}
});
}
exports.catchError = catchError;
//# sourceMappingURL=catchError.js.map
/***/ }),
/***/ 88817:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineAll = void 0;
var combineLatestAll_1 = __nccwpck_require__(91063);
exports.combineAll = combineLatestAll_1.combineLatestAll;
//# sourceMappingURL=combineAll.js.map
/***/ }),
/***/ 96008:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineLatest = void 0;
var combineLatest_1 = __nccwpck_require__(46843);
var lift_1 = __nccwpck_require__(38669);
var argsOrArgArray_1 = __nccwpck_require__(18824);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var pipe_1 = __nccwpck_require__(49587);
var args_1 = __nccwpck_require__(34890);
function combineLatest() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var resultSelector = args_1.popResultSelector(args);
return resultSelector
? pipe_1.pipe(combineLatest.apply(void 0, __spreadArray([], __read(args))), mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector))
: lift_1.operate(function (source, subscriber) {
combineLatest_1.combineLatestInit(__spreadArray([source], __read(argsOrArgArray_1.argsOrArgArray(args))))(subscriber);
});
}
exports.combineLatest = combineLatest;
//# sourceMappingURL=combineLatest.js.map
/***/ }),
/***/ 91063:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineLatestAll = void 0;
var combineLatest_1 = __nccwpck_require__(46843);
var joinAllInternals_1 = __nccwpck_require__(29341);
function combineLatestAll(project) {
return joinAllInternals_1.joinAllInternals(combineLatest_1.combineLatest, project);
}
exports.combineLatestAll = combineLatestAll;
//# sourceMappingURL=combineLatestAll.js.map
/***/ }),
/***/ 19044:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineLatestWith = void 0;
var combineLatest_1 = __nccwpck_require__(96008);
function combineLatestWith() {
var otherSources = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherSources[_i] = arguments[_i];
}
return combineLatest_1.combineLatest.apply(void 0, __spreadArray([], __read(otherSources)));
}
exports.combineLatestWith = combineLatestWith;
//# sourceMappingURL=combineLatestWith.js.map
/***/ }),
/***/ 18500:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concat = void 0;
var lift_1 = __nccwpck_require__(38669);
var concatAll_1 = __nccwpck_require__(88049);
var args_1 = __nccwpck_require__(34890);
var from_1 = __nccwpck_require__(18309);
function concat() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(args);
return lift_1.operate(function (source, subscriber) {
concatAll_1.concatAll()(from_1.from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber);
});
}
exports.concat = concat;
//# sourceMappingURL=concat.js.map
/***/ }),
/***/ 88049:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concatAll = void 0;
var mergeAll_1 = __nccwpck_require__(2057);
function concatAll() {
return mergeAll_1.mergeAll(1);
}
exports.concatAll = concatAll;
//# sourceMappingURL=concatAll.js.map
/***/ }),
/***/ 19130:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concatMap = void 0;
var mergeMap_1 = __nccwpck_require__(69914);
var isFunction_1 = __nccwpck_require__(67206);
function concatMap(project, resultSelector) {
return isFunction_1.isFunction(resultSelector) ? mergeMap_1.mergeMap(project, resultSelector, 1) : mergeMap_1.mergeMap(project, 1);
}
exports.concatMap = concatMap;
//# sourceMappingURL=concatMap.js.map
/***/ }),
/***/ 61596:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concatMapTo = void 0;
var concatMap_1 = __nccwpck_require__(19130);
var isFunction_1 = __nccwpck_require__(67206);
function concatMapTo(innerObservable, resultSelector) {
return isFunction_1.isFunction(resultSelector) ? concatMap_1.concatMap(function () { return innerObservable; }, resultSelector) : concatMap_1.concatMap(function () { return innerObservable; });
}
exports.concatMapTo = concatMapTo;
//# sourceMappingURL=concatMapTo.js.map
/***/ }),
/***/ 97998:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concatWith = void 0;
var concat_1 = __nccwpck_require__(18500);
function concatWith() {
var otherSources = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherSources[_i] = arguments[_i];
}
return concat_1.concat.apply(void 0, __spreadArray([], __read(otherSources)));
}
exports.concatWith = concatWith;
//# sourceMappingURL=concatWith.js.map
/***/ }),
/***/ 51101:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.connect = void 0;
var Subject_1 = __nccwpck_require__(49944);
var innerFrom_1 = __nccwpck_require__(57105);
var lift_1 = __nccwpck_require__(38669);
var fromSubscribable_1 = __nccwpck_require__(66513);
var DEFAULT_CONFIG = {
connector: function () { return new Subject_1.Subject(); },
};
function connect(selector, config) {
if (config === void 0) { config = DEFAULT_CONFIG; }
var connector = config.connector;
return lift_1.operate(function (source, subscriber) {
var subject = connector();
innerFrom_1.innerFrom(selector(fromSubscribable_1.fromSubscribable(subject))).subscribe(subscriber);
subscriber.add(source.subscribe(subject));
});
}
exports.connect = connect;
//# sourceMappingURL=connect.js.map
/***/ }),
/***/ 36571:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.count = void 0;
var reduce_1 = __nccwpck_require__(62087);
function count(predicate) {
return reduce_1.reduce(function (total, value, i) { return (!predicate || predicate(value, i) ? total + 1 : total); }, 0);
}
exports.count = count;
//# sourceMappingURL=count.js.map
/***/ }),
/***/ 19348:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.debounce = void 0;
var lift_1 = __nccwpck_require__(38669);
var noop_1 = __nccwpck_require__(11642);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function debounce(durationSelector) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
var lastValue = null;
var durationSubscriber = null;
var emit = function () {
durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
durationSubscriber = null;
if (hasValue) {
hasValue = false;
var value = lastValue;
lastValue = null;
subscriber.next(value);
}
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
hasValue = true;
lastValue = value;
durationSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, emit, noop_1.noop);
innerFrom_1.innerFrom(durationSelector(value)).subscribe(durationSubscriber);
}, function () {
emit();
subscriber.complete();
}, undefined, function () {
lastValue = durationSubscriber = null;
}));
});
}
exports.debounce = debounce;
//# sourceMappingURL=debounce.js.map
/***/ }),
/***/ 62379:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.debounceTime = void 0;
var async_1 = __nccwpck_require__(76072);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function debounceTime(dueTime, scheduler) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
return lift_1.operate(function (source, subscriber) {
var activeTask = null;
var lastValue = null;
var lastTime = null;
var emit = function () {
if (activeTask) {
activeTask.unsubscribe();
activeTask = null;
var value = lastValue;
lastValue = null;
subscriber.next(value);
}
};
function emitWhenIdle() {
var targetTime = lastTime + dueTime;
var now = scheduler.now();
if (now < targetTime) {
activeTask = this.schedule(undefined, targetTime - now);
subscriber.add(activeTask);
return;
}
emit();
}
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
lastValue = value;
lastTime = scheduler.now();
if (!activeTask) {
activeTask = scheduler.schedule(emitWhenIdle, dueTime);
subscriber.add(activeTask);
}
}, function () {
emit();
subscriber.complete();
}, undefined, function () {
lastValue = activeTask = null;
}));
});
}
exports.debounceTime = debounceTime;
//# sourceMappingURL=debounceTime.js.map
/***/ }),
/***/ 30621:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.defaultIfEmpty = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function defaultIfEmpty(defaultValue) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
hasValue = true;
subscriber.next(value);
}, function () {
if (!hasValue) {
subscriber.next(defaultValue);
}
subscriber.complete();
}));
});
}
exports.defaultIfEmpty = defaultIfEmpty;
//# sourceMappingURL=defaultIfEmpty.js.map
/***/ }),
/***/ 99818:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.delay = void 0;
var async_1 = __nccwpck_require__(76072);
var delayWhen_1 = __nccwpck_require__(16994);
var timer_1 = __nccwpck_require__(59757);
function delay(due, scheduler) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
var duration = timer_1.timer(due, scheduler);
return delayWhen_1.delayWhen(function () { return duration; });
}
exports.delay = delay;
//# sourceMappingURL=delay.js.map
/***/ }),
/***/ 16994:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.delayWhen = void 0;
var concat_1 = __nccwpck_require__(4675);
var take_1 = __nccwpck_require__(33698);
var ignoreElements_1 = __nccwpck_require__(31062);
var mapTo_1 = __nccwpck_require__(52300);
var mergeMap_1 = __nccwpck_require__(69914);
var innerFrom_1 = __nccwpck_require__(57105);
function delayWhen(delayDurationSelector, subscriptionDelay) {
if (subscriptionDelay) {
return function (source) {
return concat_1.concat(subscriptionDelay.pipe(take_1.take(1), ignoreElements_1.ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));
};
}
return mergeMap_1.mergeMap(function (value, index) { return innerFrom_1.innerFrom(delayDurationSelector(value, index)).pipe(take_1.take(1), mapTo_1.mapTo(value)); });
}
exports.delayWhen = delayWhen;
//# sourceMappingURL=delayWhen.js.map
/***/ }),
/***/ 95338:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.dematerialize = void 0;
var Notification_1 = __nccwpck_require__(12241);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function dematerialize() {
return lift_1.operate(function (source, subscriber) {
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (notification) { return Notification_1.observeNotification(notification, subscriber); }));
});
}
exports.dematerialize = dematerialize;
//# sourceMappingURL=dematerialize.js.map
/***/ }),
/***/ 52594:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.distinct = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
var innerFrom_1 = __nccwpck_require__(57105);
function distinct(keySelector, flushes) {
return lift_1.operate(function (source, subscriber) {
var distinctKeys = new Set();
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var key = keySelector ? keySelector(value) : value;
if (!distinctKeys.has(key)) {
distinctKeys.add(key);
subscriber.next(value);
}
}));
flushes && innerFrom_1.innerFrom(flushes).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () { return distinctKeys.clear(); }, noop_1.noop));
});
}
exports.distinct = distinct;
//# sourceMappingURL=distinct.js.map
/***/ }),
/***/ 20632:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.distinctUntilChanged = void 0;
var identity_1 = __nccwpck_require__(60283);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function distinctUntilChanged(comparator, keySelector) {
if (keySelector === void 0) { keySelector = identity_1.identity; }
comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
return lift_1.operate(function (source, subscriber) {
var previousKey;
var first = true;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var currentKey = keySelector(value);
if (first || !comparator(previousKey, currentKey)) {
first = false;
previousKey = currentKey;
subscriber.next(value);
}
}));
});
}
exports.distinctUntilChanged = distinctUntilChanged;
function defaultCompare(a, b) {
return a === b;
}
//# sourceMappingURL=distinctUntilChanged.js.map
/***/ }),
/***/ 13809:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.distinctUntilKeyChanged = void 0;
var distinctUntilChanged_1 = __nccwpck_require__(20632);
function distinctUntilKeyChanged(key, compare) {
return distinctUntilChanged_1.distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
}
exports.distinctUntilKeyChanged = distinctUntilKeyChanged;
//# sourceMappingURL=distinctUntilKeyChanged.js.map
/***/ }),
/***/ 73381:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.elementAt = void 0;
var ArgumentOutOfRangeError_1 = __nccwpck_require__(49796);
var filter_1 = __nccwpck_require__(36894);
var throwIfEmpty_1 = __nccwpck_require__(91566);
var defaultIfEmpty_1 = __nccwpck_require__(30621);
var take_1 = __nccwpck_require__(33698);
function elementAt(index, defaultValue) {
if (index < 0) {
throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
}
var hasDefaultValue = arguments.length >= 2;
return function (source) {
return source.pipe(filter_1.filter(function (v, i) { return i === index; }), take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); }));
};
}
exports.elementAt = elementAt;
//# sourceMappingURL=elementAt.js.map
/***/ }),
/***/ 42961:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.endWith = void 0;
var concat_1 = __nccwpck_require__(4675);
var of_1 = __nccwpck_require__(72163);
function endWith() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i] = arguments[_i];
}
return function (source) { return concat_1.concat(source, of_1.of.apply(void 0, __spreadArray([], __read(values)))); };
}
exports.endWith = endWith;
//# sourceMappingURL=endWith.js.map
/***/ }),
/***/ 69559:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.every = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function every(predicate, thisArg) {
return lift_1.operate(function (source, subscriber) {
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (!predicate.call(thisArg, value, index++, source)) {
subscriber.next(false);
subscriber.complete();
}
}, function () {
subscriber.next(true);
subscriber.complete();
}));
});
}
exports.every = every;
//# sourceMappingURL=every.js.map
/***/ }),
/***/ 75686:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.exhaust = void 0;
var exhaustAll_1 = __nccwpck_require__(79777);
exports.exhaust = exhaustAll_1.exhaustAll;
//# sourceMappingURL=exhaust.js.map
/***/ }),
/***/ 79777:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.exhaustAll = void 0;
var exhaustMap_1 = __nccwpck_require__(21527);
var identity_1 = __nccwpck_require__(60283);
function exhaustAll() {
return exhaustMap_1.exhaustMap(identity_1.identity);
}
exports.exhaustAll = exhaustAll;
//# sourceMappingURL=exhaustAll.js.map
/***/ }),
/***/ 21527:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.exhaustMap = void 0;
var map_1 = __nccwpck_require__(5987);
var innerFrom_1 = __nccwpck_require__(57105);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function exhaustMap(project, resultSelector) {
if (resultSelector) {
return function (source) {
return source.pipe(exhaustMap(function (a, i) { return innerFrom_1.innerFrom(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); }));
};
}
return lift_1.operate(function (source, subscriber) {
var index = 0;
var innerSub = null;
var isComplete = false;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (outerValue) {
if (!innerSub) {
innerSub = OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, function () {
innerSub = null;
isComplete && subscriber.complete();
});
innerFrom_1.innerFrom(project(outerValue, index++)).subscribe(innerSub);
}
}, function () {
isComplete = true;
!innerSub && subscriber.complete();
}));
});
}
exports.exhaustMap = exhaustMap;
//# sourceMappingURL=exhaustMap.js.map
/***/ }),
/***/ 21585:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.expand = void 0;
var lift_1 = __nccwpck_require__(38669);
var mergeInternals_1 = __nccwpck_require__(48246);
function expand(project, concurrent, scheduler) {
if (concurrent === void 0) { concurrent = Infinity; }
concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;
return lift_1.operate(function (source, subscriber) {
return mergeInternals_1.mergeInternals(source, subscriber, project, concurrent, undefined, true, scheduler);
});
}
exports.expand = expand;
//# sourceMappingURL=expand.js.map
/***/ }),
/***/ 36894:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.filter = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function filter(predicate, thisArg) {
return lift_1.operate(function (source, subscriber) {
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
});
}
exports.filter = filter;
//# sourceMappingURL=filter.js.map
/***/ }),
/***/ 4013:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.finalize = void 0;
var lift_1 = __nccwpck_require__(38669);
function finalize(callback) {
return lift_1.operate(function (source, subscriber) {
try {
source.subscribe(subscriber);
}
finally {
subscriber.add(callback);
}
});
}
exports.finalize = finalize;
//# sourceMappingURL=finalize.js.map
/***/ }),
/***/ 28981:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFind = exports.find = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function find(predicate, thisArg) {
return lift_1.operate(createFind(predicate, thisArg, 'value'));
}
exports.find = find;
function createFind(predicate, thisArg, emit) {
var findIndex = emit === 'index';
return function (source, subscriber) {
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var i = index++;
if (predicate.call(thisArg, value, i, source)) {
subscriber.next(findIndex ? i : value);
subscriber.complete();
}
}, function () {
subscriber.next(findIndex ? -1 : undefined);
subscriber.complete();
}));
};
}
exports.createFind = createFind;
//# sourceMappingURL=find.js.map
/***/ }),
/***/ 92602:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.findIndex = void 0;
var lift_1 = __nccwpck_require__(38669);
var find_1 = __nccwpck_require__(28981);
function findIndex(predicate, thisArg) {
return lift_1.operate(find_1.createFind(predicate, thisArg, 'index'));
}
exports.findIndex = findIndex;
//# sourceMappingURL=findIndex.js.map
/***/ }),
/***/ 63345:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.first = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
var filter_1 = __nccwpck_require__(36894);
var take_1 = __nccwpck_require__(33698);
var defaultIfEmpty_1 = __nccwpck_require__(30621);
var throwIfEmpty_1 = __nccwpck_require__(91566);
var identity_1 = __nccwpck_require__(60283);
function first(predicate, defaultValue) {
var hasDefaultValue = arguments.length >= 2;
return function (source) {
return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); }));
};
}
exports.first = first;
//# sourceMappingURL=first.js.map
/***/ }),
/***/ 40186:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.flatMap = void 0;
var mergeMap_1 = __nccwpck_require__(69914);
exports.flatMap = mergeMap_1.mergeMap;
//# sourceMappingURL=flatMap.js.map
/***/ }),
/***/ 51650:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.groupBy = void 0;
var Observable_1 = __nccwpck_require__(53014);
var innerFrom_1 = __nccwpck_require__(57105);
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function groupBy(keySelector, elementOrOptions, duration, connector) {
return lift_1.operate(function (source, subscriber) {
var element;
if (!elementOrOptions || typeof elementOrOptions === 'function') {
element = elementOrOptions;
}
else {
(duration = elementOrOptions.duration, element = elementOrOptions.element, connector = elementOrOptions.connector);
}
var groups = new Map();
var notify = function (cb) {
groups.forEach(cb);
cb(subscriber);
};
var handleError = function (err) { return notify(function (consumer) { return consumer.error(err); }); };
var activeGroups = 0;
var teardownAttempted = false;
var groupBySourceSubscriber = new OperatorSubscriber_1.OperatorSubscriber(subscriber, function (value) {
try {
var key_1 = keySelector(value);
var group_1 = groups.get(key_1);
if (!group_1) {
groups.set(key_1, (group_1 = connector ? connector() : new Subject_1.Subject()));
var grouped = createGroupedObservable(key_1, group_1);
subscriber.next(grouped);
if (duration) {
var durationSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(group_1, function () {
group_1.complete();
durationSubscriber_1 === null || durationSubscriber_1 === void 0 ? void 0 : durationSubscriber_1.unsubscribe();
}, undefined, undefined, function () { return groups.delete(key_1); });
groupBySourceSubscriber.add(innerFrom_1.innerFrom(duration(grouped)).subscribe(durationSubscriber_1));
}
}
group_1.next(element ? element(value) : value);
}
catch (err) {
handleError(err);
}
}, function () { return notify(function (consumer) { return consumer.complete(); }); }, handleError, function () { return groups.clear(); }, function () {
teardownAttempted = true;
return activeGroups === 0;
});
source.subscribe(groupBySourceSubscriber);
function createGroupedObservable(key, groupSubject) {
var result = new Observable_1.Observable(function (groupSubscriber) {
activeGroups++;
var innerSub = groupSubject.subscribe(groupSubscriber);
return function () {
innerSub.unsubscribe();
--activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();
};
});
result.key = key;
return result;
}
});
}
exports.groupBy = groupBy;
//# sourceMappingURL=groupBy.js.map
/***/ }),
/***/ 31062:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ignoreElements = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
function ignoreElements() {
return lift_1.operate(function (source, subscriber) {
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, noop_1.noop));
});
}
exports.ignoreElements = ignoreElements;
//# sourceMappingURL=ignoreElements.js.map
/***/ }),
/***/ 77722:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isEmpty = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function isEmpty() {
return lift_1.operate(function (source, subscriber) {
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
subscriber.next(false);
subscriber.complete();
}, function () {
subscriber.next(true);
subscriber.complete();
}));
});
}
exports.isEmpty = isEmpty;
//# sourceMappingURL=isEmpty.js.map
/***/ }),
/***/ 29341:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.joinAllInternals = void 0;
var identity_1 = __nccwpck_require__(60283);
var mapOneOrManyArgs_1 = __nccwpck_require__(78934);
var pipe_1 = __nccwpck_require__(49587);
var mergeMap_1 = __nccwpck_require__(69914);
var toArray_1 = __nccwpck_require__(35114);
function joinAllInternals(joinFn, project) {
return pipe_1.pipe(toArray_1.toArray(), mergeMap_1.mergeMap(function (sources) { return joinFn(sources); }), project ? mapOneOrManyArgs_1.mapOneOrManyArgs(project) : identity_1.identity);
}
exports.joinAllInternals = joinAllInternals;
//# sourceMappingURL=joinAllInternals.js.map
/***/ }),
/***/ 46831:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.last = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
var filter_1 = __nccwpck_require__(36894);
var takeLast_1 = __nccwpck_require__(65041);
var throwIfEmpty_1 = __nccwpck_require__(91566);
var defaultIfEmpty_1 = __nccwpck_require__(30621);
var identity_1 = __nccwpck_require__(60283);
function last(predicate, defaultValue) {
var hasDefaultValue = arguments.length >= 2;
return function (source) {
return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, takeLast_1.takeLast(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); }));
};
}
exports.last = last;
//# sourceMappingURL=last.js.map
/***/ }),
/***/ 5987:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.map = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function map(project, thisArg) {
return lift_1.operate(function (source, subscriber) {
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
subscriber.next(project.call(thisArg, value, index++));
}));
});
}
exports.map = map;
//# sourceMappingURL=map.js.map
/***/ }),
/***/ 52300:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mapTo = void 0;
var map_1 = __nccwpck_require__(5987);
function mapTo(value) {
return map_1.map(function () { return value; });
}
exports.mapTo = mapTo;
//# sourceMappingURL=mapTo.js.map
/***/ }),
/***/ 67108:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.materialize = void 0;
var Notification_1 = __nccwpck_require__(12241);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function materialize() {
return lift_1.operate(function (source, subscriber) {
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
subscriber.next(Notification_1.Notification.createNext(value));
}, function () {
subscriber.next(Notification_1.Notification.createComplete());
subscriber.complete();
}, function (err) {
subscriber.next(Notification_1.Notification.createError(err));
subscriber.complete();
}));
});
}
exports.materialize = materialize;
//# sourceMappingURL=materialize.js.map
/***/ }),
/***/ 17314:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.max = void 0;
var reduce_1 = __nccwpck_require__(62087);
var isFunction_1 = __nccwpck_require__(67206);
function max(comparer) {
return reduce_1.reduce(isFunction_1.isFunction(comparer) ? function (x, y) { return (comparer(x, y) > 0 ? x : y); } : function (x, y) { return (x > y ? x : y); });
}
exports.max = max;
//# sourceMappingURL=max.js.map
/***/ }),
/***/ 39510:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.merge = void 0;
var lift_1 = __nccwpck_require__(38669);
var argsOrArgArray_1 = __nccwpck_require__(18824);
var mergeAll_1 = __nccwpck_require__(2057);
var args_1 = __nccwpck_require__(34890);
var from_1 = __nccwpck_require__(18309);
function merge() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(args);
var concurrent = args_1.popNumber(args, Infinity);
args = argsOrArgArray_1.argsOrArgArray(args);
return lift_1.operate(function (source, subscriber) {
mergeAll_1.mergeAll(concurrent)(from_1.from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber);
});
}
exports.merge = merge;
//# sourceMappingURL=merge.js.map
/***/ }),
/***/ 2057:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeAll = void 0;
var mergeMap_1 = __nccwpck_require__(69914);
var identity_1 = __nccwpck_require__(60283);
function mergeAll(concurrent) {
if (concurrent === void 0) { concurrent = Infinity; }
return mergeMap_1.mergeMap(identity_1.identity, concurrent);
}
exports.mergeAll = mergeAll;
//# sourceMappingURL=mergeAll.js.map
/***/ }),
/***/ 48246:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeInternals = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var executeSchedule_1 = __nccwpck_require__(82877);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
var buffer = [];
var active = 0;
var index = 0;
var isComplete = false;
var checkComplete = function () {
if (isComplete && !buffer.length && !active) {
subscriber.complete();
}
};
var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
var doInnerSub = function (value) {
expand && subscriber.next(value);
active++;
var innerComplete = false;
innerFrom_1.innerFrom(project(value, index++)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (innerValue) {
onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
if (expand) {
outerNext(innerValue);
}
else {
subscriber.next(innerValue);
}
}, function () {
innerComplete = true;
}, undefined, function () {
if (innerComplete) {
try {
active--;
var _loop_1 = function () {
var bufferedValue = buffer.shift();
if (innerSubScheduler) {
executeSchedule_1.executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
}
else {
doInnerSub(bufferedValue);
}
};
while (buffer.length && active < concurrent) {
_loop_1();
}
checkComplete();
}
catch (err) {
subscriber.error(err);
}
}
}));
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, outerNext, function () {
isComplete = true;
checkComplete();
}));
return function () {
additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
};
}
exports.mergeInternals = mergeInternals;
//# sourceMappingURL=mergeInternals.js.map
/***/ }),
/***/ 69914:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeMap = void 0;
var map_1 = __nccwpck_require__(5987);
var innerFrom_1 = __nccwpck_require__(57105);
var lift_1 = __nccwpck_require__(38669);
var mergeInternals_1 = __nccwpck_require__(48246);
var isFunction_1 = __nccwpck_require__(67206);
function mergeMap(project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Infinity; }
if (isFunction_1.isFunction(resultSelector)) {
return mergeMap(function (a, i) { return map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom_1.innerFrom(project(a, i))); }, concurrent);
}
else if (typeof resultSelector === 'number') {
concurrent = resultSelector;
}
return lift_1.operate(function (source, subscriber) { return mergeInternals_1.mergeInternals(source, subscriber, project, concurrent); });
}
exports.mergeMap = mergeMap;
//# sourceMappingURL=mergeMap.js.map
/***/ }),
/***/ 49151:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeMapTo = void 0;
var mergeMap_1 = __nccwpck_require__(69914);
var isFunction_1 = __nccwpck_require__(67206);
function mergeMapTo(innerObservable, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Infinity; }
if (isFunction_1.isFunction(resultSelector)) {
return mergeMap_1.mergeMap(function () { return innerObservable; }, resultSelector, concurrent);
}
if (typeof resultSelector === 'number') {
concurrent = resultSelector;
}
return mergeMap_1.mergeMap(function () { return innerObservable; }, concurrent);
}
exports.mergeMapTo = mergeMapTo;
//# sourceMappingURL=mergeMapTo.js.map
/***/ }),
/***/ 11519:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeScan = void 0;
var lift_1 = __nccwpck_require__(38669);
var mergeInternals_1 = __nccwpck_require__(48246);
function mergeScan(accumulator, seed, concurrent) {
if (concurrent === void 0) { concurrent = Infinity; }
return lift_1.operate(function (source, subscriber) {
var state = seed;
return mergeInternals_1.mergeInternals(source, subscriber, function (value, index) { return accumulator(state, value, index); }, concurrent, function (value) {
state = value;
}, false, undefined, function () { return (state = null); });
});
}
exports.mergeScan = mergeScan;
//# sourceMappingURL=mergeScan.js.map
/***/ }),
/***/ 22117:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeWith = void 0;
var merge_1 = __nccwpck_require__(39510);
function mergeWith() {
var otherSources = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherSources[_i] = arguments[_i];
}
return merge_1.merge.apply(void 0, __spreadArray([], __read(otherSources)));
}
exports.mergeWith = mergeWith;
//# sourceMappingURL=mergeWith.js.map
/***/ }),
/***/ 87641:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.min = void 0;
var reduce_1 = __nccwpck_require__(62087);
var isFunction_1 = __nccwpck_require__(67206);
function min(comparer) {
return reduce_1.reduce(isFunction_1.isFunction(comparer) ? function (x, y) { return (comparer(x, y) < 0 ? x : y); } : function (x, y) { return (x < y ? x : y); });
}
exports.min = min;
//# sourceMappingURL=min.js.map
/***/ }),
/***/ 65457:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.multicast = void 0;
var ConnectableObservable_1 = __nccwpck_require__(30420);
var isFunction_1 = __nccwpck_require__(67206);
var connect_1 = __nccwpck_require__(51101);
function multicast(subjectOrSubjectFactory, selector) {
var subjectFactory = isFunction_1.isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : function () { return subjectOrSubjectFactory; };
if (isFunction_1.isFunction(selector)) {
return connect_1.connect(selector, {
connector: subjectFactory,
});
}
return function (source) { return new ConnectableObservable_1.ConnectableObservable(source, subjectFactory); };
}
exports.multicast = multicast;
//# sourceMappingURL=multicast.js.map
/***/ }),
/***/ 22451:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.observeOn = void 0;
var executeSchedule_1 = __nccwpck_require__(82877);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function observeOn(scheduler, delay) {
if (delay === void 0) { delay = 0; }
return lift_1.operate(function (source, subscriber) {
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return executeSchedule_1.executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule_1.executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule_1.executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
});
}
exports.observeOn = observeOn;
//# sourceMappingURL=observeOn.js.map
/***/ }),
/***/ 33569:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.onErrorResumeNext = exports.onErrorResumeNextWith = void 0;
var argsOrArgArray_1 = __nccwpck_require__(18824);
var onErrorResumeNext_1 = __nccwpck_require__(16089);
function onErrorResumeNextWith() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
var nextSources = argsOrArgArray_1.argsOrArgArray(sources);
return function (source) { return onErrorResumeNext_1.onErrorResumeNext.apply(void 0, __spreadArray([source], __read(nextSources))); };
}
exports.onErrorResumeNextWith = onErrorResumeNextWith;
exports.onErrorResumeNext = onErrorResumeNextWith;
//# sourceMappingURL=onErrorResumeNextWith.js.map
/***/ }),
/***/ 52206:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pairwise = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function pairwise() {
return lift_1.operate(function (source, subscriber) {
var prev;
var hasPrev = false;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var p = prev;
prev = value;
hasPrev && subscriber.next([p, value]);
hasPrev = true;
}));
});
}
exports.pairwise = pairwise;
//# sourceMappingURL=pairwise.js.map
/***/ }),
/***/ 55949:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.partition = void 0;
var not_1 = __nccwpck_require__(54338);
var filter_1 = __nccwpck_require__(36894);
function partition(predicate, thisArg) {
return function (source) {
return [filter_1.filter(predicate, thisArg)(source), filter_1.filter(not_1.not(predicate, thisArg))(source)];
};
}
exports.partition = partition;
//# sourceMappingURL=partition.js.map
/***/ }),
/***/ 16073:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pluck = void 0;
var map_1 = __nccwpck_require__(5987);
function pluck() {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
var length = properties.length;
if (length === 0) {
throw new Error('list of properties cannot be empty.');
}
return map_1.map(function (x) {
var currentProp = x;
for (var i = 0; i < length; i++) {
var p = currentProp === null || currentProp === void 0 ? void 0 : currentProp[properties[i]];
if (typeof p !== 'undefined') {
currentProp = p;
}
else {
return undefined;
}
}
return currentProp;
});
}
exports.pluck = pluck;
//# sourceMappingURL=pluck.js.map
/***/ }),
/***/ 84084:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.publish = void 0;
var Subject_1 = __nccwpck_require__(49944);
var multicast_1 = __nccwpck_require__(65457);
var connect_1 = __nccwpck_require__(51101);
function publish(selector) {
return selector ? function (source) { return connect_1.connect(selector)(source); } : function (source) { return multicast_1.multicast(new Subject_1.Subject())(source); };
}
exports.publish = publish;
//# sourceMappingURL=publish.js.map
/***/ }),
/***/ 40045:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.publishBehavior = void 0;
var BehaviorSubject_1 = __nccwpck_require__(23473);
var ConnectableObservable_1 = __nccwpck_require__(30420);
function publishBehavior(initialValue) {
return function (source) {
var subject = new BehaviorSubject_1.BehaviorSubject(initialValue);
return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; });
};
}
exports.publishBehavior = publishBehavior;
//# sourceMappingURL=publishBehavior.js.map
/***/ }),
/***/ 84149:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.publishLast = void 0;
var AsyncSubject_1 = __nccwpck_require__(9747);
var ConnectableObservable_1 = __nccwpck_require__(30420);
function publishLast() {
return function (source) {
var subject = new AsyncSubject_1.AsyncSubject();
return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; });
};
}
exports.publishLast = publishLast;
//# sourceMappingURL=publishLast.js.map
/***/ }),
/***/ 47656:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.publishReplay = void 0;
var ReplaySubject_1 = __nccwpck_require__(22351);
var multicast_1 = __nccwpck_require__(65457);
var isFunction_1 = __nccwpck_require__(67206);
function publishReplay(bufferSize, windowTime, selectorOrScheduler, timestampProvider) {
if (selectorOrScheduler && !isFunction_1.isFunction(selectorOrScheduler)) {
timestampProvider = selectorOrScheduler;
}
var selector = isFunction_1.isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined;
return function (source) { return multicast_1.multicast(new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, timestampProvider), selector)(source); };
}
exports.publishReplay = publishReplay;
//# sourceMappingURL=publishReplay.js.map
/***/ }),
/***/ 85846:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.race = void 0;
var argsOrArgArray_1 = __nccwpck_require__(18824);
var raceWith_1 = __nccwpck_require__(58008);
function race() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return raceWith_1.raceWith.apply(void 0, __spreadArray([], __read(argsOrArgArray_1.argsOrArgArray(args))));
}
exports.race = race;
//# sourceMappingURL=race.js.map
/***/ }),
/***/ 58008:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.raceWith = void 0;
var race_1 = __nccwpck_require__(16940);
var lift_1 = __nccwpck_require__(38669);
var identity_1 = __nccwpck_require__(60283);
function raceWith() {
var otherSources = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherSources[_i] = arguments[_i];
}
return !otherSources.length
? identity_1.identity
: lift_1.operate(function (source, subscriber) {
race_1.raceInit(__spreadArray([source], __read(otherSources)))(subscriber);
});
}
exports.raceWith = raceWith;
//# sourceMappingURL=raceWith.js.map
/***/ }),
/***/ 62087:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reduce = void 0;
var scanInternals_1 = __nccwpck_require__(20998);
var lift_1 = __nccwpck_require__(38669);
function reduce(accumulator, seed) {
return lift_1.operate(scanInternals_1.scanInternals(accumulator, seed, arguments.length >= 2, false, true));
}
exports.reduce = reduce;
//# sourceMappingURL=reduce.js.map
/***/ }),
/***/ 2331:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.refCount = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function refCount() {
return lift_1.operate(function (source, subscriber) {
var connection = null;
source._refCount++;
var refCounter = OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, undefined, undefined, function () {
if (!source || source._refCount <= 0 || 0 < --source._refCount) {
connection = null;
return;
}
var sharedConnection = source._connection;
var conn = connection;
connection = null;
if (sharedConnection && (!conn || sharedConnection === conn)) {
sharedConnection.unsubscribe();
}
subscriber.unsubscribe();
});
source.subscribe(refCounter);
if (!refCounter.closed) {
connection = source.connect();
}
});
}
exports.refCount = refCount;
//# sourceMappingURL=refCount.js.map
/***/ }),
/***/ 22418:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.repeat = void 0;
var empty_1 = __nccwpck_require__(70437);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
var timer_1 = __nccwpck_require__(59757);
function repeat(countOrConfig) {
var _a;
var count = Infinity;
var delay;
if (countOrConfig != null) {
if (typeof countOrConfig === 'object') {
(_a = countOrConfig.count, count = _a === void 0 ? Infinity : _a, delay = countOrConfig.delay);
}
else {
count = countOrConfig;
}
}
return count <= 0
? function () { return empty_1.EMPTY; }
: lift_1.operate(function (source, subscriber) {
var soFar = 0;
var sourceSub;
var resubscribe = function () {
sourceSub === null || sourceSub === void 0 ? void 0 : sourceSub.unsubscribe();
sourceSub = null;
if (delay != null) {
var notifier = typeof delay === 'number' ? timer_1.timer(delay) : innerFrom_1.innerFrom(delay(soFar));
var notifierSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
notifierSubscriber_1.unsubscribe();
subscribeToSource();
});
notifier.subscribe(notifierSubscriber_1);
}
else {
subscribeToSource();
}
};
var subscribeToSource = function () {
var syncUnsub = false;
sourceSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, function () {
if (++soFar < count) {
if (sourceSub) {
resubscribe();
}
else {
syncUnsub = true;
}
}
else {
subscriber.complete();
}
}));
if (syncUnsub) {
resubscribe();
}
};
subscribeToSource();
});
}
exports.repeat = repeat;
//# sourceMappingURL=repeat.js.map
/***/ }),
/***/ 70754:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.repeatWhen = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function repeatWhen(notifier) {
return lift_1.operate(function (source, subscriber) {
var innerSub;
var syncResub = false;
var completions$;
var isNotifierComplete = false;
var isMainComplete = false;
var checkComplete = function () { return isMainComplete && isNotifierComplete && (subscriber.complete(), true); };
var getCompletionSubject = function () {
if (!completions$) {
completions$ = new Subject_1.Subject();
innerFrom_1.innerFrom(notifier(completions$)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
if (innerSub) {
subscribeForRepeatWhen();
}
else {
syncResub = true;
}
}, function () {
isNotifierComplete = true;
checkComplete();
}));
}
return completions$;
};
var subscribeForRepeatWhen = function () {
isMainComplete = false;
innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, function () {
isMainComplete = true;
!checkComplete() && getCompletionSubject().next();
}));
if (syncResub) {
innerSub.unsubscribe();
innerSub = null;
syncResub = false;
subscribeForRepeatWhen();
}
};
subscribeForRepeatWhen();
});
}
exports.repeatWhen = repeatWhen;
//# sourceMappingURL=repeatWhen.js.map
/***/ }),
/***/ 56251:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.retry = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var identity_1 = __nccwpck_require__(60283);
var timer_1 = __nccwpck_require__(59757);
var innerFrom_1 = __nccwpck_require__(57105);
function retry(configOrCount) {
if (configOrCount === void 0) { configOrCount = Infinity; }
var config;
if (configOrCount && typeof configOrCount === 'object') {
config = configOrCount;
}
else {
config = {
count: configOrCount,
};
}
var _a = config.count, count = _a === void 0 ? Infinity : _a, delay = config.delay, _b = config.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
return count <= 0
? identity_1.identity
: lift_1.operate(function (source, subscriber) {
var soFar = 0;
var innerSub;
var subscribeForRetry = function () {
var syncUnsub = false;
innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (resetOnSuccess) {
soFar = 0;
}
subscriber.next(value);
}, undefined, function (err) {
if (soFar++ < count) {
var resub_1 = function () {
if (innerSub) {
innerSub.unsubscribe();
innerSub = null;
subscribeForRetry();
}
else {
syncUnsub = true;
}
};
if (delay != null) {
var notifier = typeof delay === 'number' ? timer_1.timer(delay) : innerFrom_1.innerFrom(delay(err, soFar));
var notifierSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
notifierSubscriber_1.unsubscribe();
resub_1();
}, function () {
subscriber.complete();
});
notifier.subscribe(notifierSubscriber_1);
}
else {
resub_1();
}
}
else {
subscriber.error(err);
}
}));
if (syncUnsub) {
innerSub.unsubscribe();
innerSub = null;
subscribeForRetry();
}
};
subscribeForRetry();
});
}
exports.retry = retry;
//# sourceMappingURL=retry.js.map
/***/ }),
/***/ 69018:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.retryWhen = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function retryWhen(notifier) {
return lift_1.operate(function (source, subscriber) {
var innerSub;
var syncResub = false;
var errors$;
var subscribeForRetryWhen = function () {
innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
if (!errors$) {
errors$ = new Subject_1.Subject();
innerFrom_1.innerFrom(notifier(errors$)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
return innerSub ? subscribeForRetryWhen() : (syncResub = true);
}));
}
if (errors$) {
errors$.next(err);
}
}));
if (syncResub) {
innerSub.unsubscribe();
innerSub = null;
syncResub = false;
subscribeForRetryWhen();
}
};
subscribeForRetryWhen();
});
}
exports.retryWhen = retryWhen;
//# sourceMappingURL=retryWhen.js.map
/***/ }),
/***/ 13774:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sample = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var lift_1 = __nccwpck_require__(38669);
var noop_1 = __nccwpck_require__(11642);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function sample(notifier) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
var lastValue = null;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
hasValue = true;
lastValue = value;
}));
innerFrom_1.innerFrom(notifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
if (hasValue) {
hasValue = false;
var value = lastValue;
lastValue = null;
subscriber.next(value);
}
}, noop_1.noop));
});
}
exports.sample = sample;
//# sourceMappingURL=sample.js.map
/***/ }),
/***/ 49807:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sampleTime = void 0;
var async_1 = __nccwpck_require__(76072);
var sample_1 = __nccwpck_require__(13774);
var interval_1 = __nccwpck_require__(20029);
function sampleTime(period, scheduler) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
return sample_1.sample(interval_1.interval(period, scheduler));
}
exports.sampleTime = sampleTime;
//# sourceMappingURL=sampleTime.js.map
/***/ }),
/***/ 25578:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scan = void 0;
var lift_1 = __nccwpck_require__(38669);
var scanInternals_1 = __nccwpck_require__(20998);
function scan(accumulator, seed) {
return lift_1.operate(scanInternals_1.scanInternals(accumulator, seed, arguments.length >= 2, true));
}
exports.scan = scan;
//# sourceMappingURL=scan.js.map
/***/ }),
/***/ 20998:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scanInternals = void 0;
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
return function (source, subscriber) {
var hasState = hasSeed;
var state = seed;
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var i = index++;
state = hasState
?
accumulator(state, value, i)
:
((hasState = true), value);
emitOnNext && subscriber.next(state);
}, emitBeforeComplete &&
(function () {
hasState && subscriber.next(state);
subscriber.complete();
})));
};
}
exports.scanInternals = scanInternals;
//# sourceMappingURL=scanInternals.js.map
/***/ }),
/***/ 16126:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sequenceEqual = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function sequenceEqual(compareTo, comparator) {
if (comparator === void 0) { comparator = function (a, b) { return a === b; }; }
return lift_1.operate(function (source, subscriber) {
var aState = createState();
var bState = createState();
var emit = function (isEqual) {
subscriber.next(isEqual);
subscriber.complete();
};
var createSubscriber = function (selfState, otherState) {
var sequenceEqualSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (a) {
var buffer = otherState.buffer, complete = otherState.complete;
if (buffer.length === 0) {
complete ? emit(false) : selfState.buffer.push(a);
}
else {
!comparator(a, buffer.shift()) && emit(false);
}
}, function () {
selfState.complete = true;
var complete = otherState.complete, buffer = otherState.buffer;
complete && emit(buffer.length === 0);
sequenceEqualSubscriber === null || sequenceEqualSubscriber === void 0 ? void 0 : sequenceEqualSubscriber.unsubscribe();
});
return sequenceEqualSubscriber;
};
source.subscribe(createSubscriber(aState, bState));
innerFrom_1.innerFrom(compareTo).subscribe(createSubscriber(bState, aState));
});
}
exports.sequenceEqual = sequenceEqual;
function createState() {
return {
buffer: [],
complete: false,
};
}
//# sourceMappingURL=sequenceEqual.js.map
/***/ }),
/***/ 48960:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.share = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var Subject_1 = __nccwpck_require__(49944);
var Subscriber_1 = __nccwpck_require__(67121);
var lift_1 = __nccwpck_require__(38669);
function share(options) {
if (options === void 0) { options = {}; }
var _a = options.connector, connector = _a === void 0 ? function () { return new Subject_1.Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d;
return function (wrapperSource) {
var connection;
var resetConnection;
var subject;
var refCount = 0;
var hasCompleted = false;
var hasErrored = false;
var cancelReset = function () {
resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();
resetConnection = undefined;
};
var reset = function () {
cancelReset();
connection = subject = undefined;
hasCompleted = hasErrored = false;
};
var resetAndUnsubscribe = function () {
var conn = connection;
reset();
conn === null || conn === void 0 ? void 0 : conn.unsubscribe();
};
return lift_1.operate(function (source, subscriber) {
refCount++;
if (!hasErrored && !hasCompleted) {
cancelReset();
}
var dest = (subject = subject !== null && subject !== void 0 ? subject : connector());
subscriber.add(function () {
refCount--;
if (refCount === 0 && !hasErrored && !hasCompleted) {
resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
}
});
dest.subscribe(subscriber);
if (!connection &&
refCount > 0) {
connection = new Subscriber_1.SafeSubscriber({
next: function (value) { return dest.next(value); },
error: function (err) {
hasErrored = true;
cancelReset();
resetConnection = handleReset(reset, resetOnError, err);
dest.error(err);
},
complete: function () {
hasCompleted = true;
cancelReset();
resetConnection = handleReset(reset, resetOnComplete);
dest.complete();
},
});
innerFrom_1.innerFrom(source).subscribe(connection);
}
})(wrapperSource);
};
}
exports.share = share;
function handleReset(reset, on) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (on === true) {
reset();
return;
}
if (on === false) {
return;
}
var onSubscriber = new Subscriber_1.SafeSubscriber({
next: function () {
onSubscriber.unsubscribe();
reset();
},
});
return innerFrom_1.innerFrom(on.apply(void 0, __spreadArray([], __read(args)))).subscribe(onSubscriber);
}
//# sourceMappingURL=share.js.map
/***/ }),
/***/ 92118:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shareReplay = void 0;
var ReplaySubject_1 = __nccwpck_require__(22351);
var share_1 = __nccwpck_require__(48960);
function shareReplay(configOrBufferSize, windowTime, scheduler) {
var _a, _b, _c;
var bufferSize;
var refCount = false;
if (configOrBufferSize && typeof configOrBufferSize === 'object') {
(_a = configOrBufferSize.bufferSize, bufferSize = _a === void 0 ? Infinity : _a, _b = configOrBufferSize.windowTime, windowTime = _b === void 0 ? Infinity : _b, _c = configOrBufferSize.refCount, refCount = _c === void 0 ? false : _c, scheduler = configOrBufferSize.scheduler);
}
else {
bufferSize = (configOrBufferSize !== null && configOrBufferSize !== void 0 ? configOrBufferSize : Infinity);
}
return share_1.share({
connector: function () { return new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler); },
resetOnError: true,
resetOnComplete: false,
resetOnRefCountZero: refCount,
});
}
exports.shareReplay = shareReplay;
//# sourceMappingURL=shareReplay.js.map
/***/ }),
/***/ 58441:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.single = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
var SequenceError_1 = __nccwpck_require__(49048);
var NotFoundError_1 = __nccwpck_require__(74431);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function single(predicate) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
var singleValue;
var seenValue = false;
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
seenValue = true;
if (!predicate || predicate(value, index++, source)) {
hasValue && subscriber.error(new SequenceError_1.SequenceError('Too many matching values'));
hasValue = true;
singleValue = value;
}
}, function () {
if (hasValue) {
subscriber.next(singleValue);
subscriber.complete();
}
else {
subscriber.error(seenValue ? new NotFoundError_1.NotFoundError('No matching values') : new EmptyError_1.EmptyError());
}
}));
});
}
exports.single = single;
//# sourceMappingURL=single.js.map
/***/ }),
/***/ 80947:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.skip = void 0;
var filter_1 = __nccwpck_require__(36894);
function skip(count) {
return filter_1.filter(function (_, index) { return count <= index; });
}
exports.skip = skip;
//# sourceMappingURL=skip.js.map
/***/ }),
/***/ 65865:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.skipLast = void 0;
var identity_1 = __nccwpck_require__(60283);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function skipLast(skipCount) {
return skipCount <= 0
?
identity_1.identity
: lift_1.operate(function (source, subscriber) {
var ring = new Array(skipCount);
var seen = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var valueIndex = seen++;
if (valueIndex < skipCount) {
ring[valueIndex] = value;
}
else {
var index = valueIndex % skipCount;
var oldValue = ring[index];
ring[index] = value;
subscriber.next(oldValue);
}
}));
return function () {
ring = null;
};
});
}
exports.skipLast = skipLast;
//# sourceMappingURL=skipLast.js.map
/***/ }),
/***/ 41110:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.skipUntil = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
var noop_1 = __nccwpck_require__(11642);
function skipUntil(notifier) {
return lift_1.operate(function (source, subscriber) {
var taking = false;
var skipSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
skipSubscriber === null || skipSubscriber === void 0 ? void 0 : skipSubscriber.unsubscribe();
taking = true;
}, noop_1.noop);
innerFrom_1.innerFrom(notifier).subscribe(skipSubscriber);
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return taking && subscriber.next(value); }));
});
}
exports.skipUntil = skipUntil;
//# sourceMappingURL=skipUntil.js.map
/***/ }),
/***/ 92550:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.skipWhile = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function skipWhile(predicate) {
return lift_1.operate(function (source, subscriber) {
var taking = false;
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return (taking || (taking = !predicate(value, index++))) && subscriber.next(value); }));
});
}
exports.skipWhile = skipWhile;
//# sourceMappingURL=skipWhile.js.map
/***/ }),
/***/ 25471:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.startWith = void 0;
var concat_1 = __nccwpck_require__(4675);
var args_1 = __nccwpck_require__(34890);
var lift_1 = __nccwpck_require__(38669);
function startWith() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i] = arguments[_i];
}
var scheduler = args_1.popScheduler(values);
return lift_1.operate(function (source, subscriber) {
(scheduler ? concat_1.concat(values, source, scheduler) : concat_1.concat(values, source)).subscribe(subscriber);
});
}
exports.startWith = startWith;
//# sourceMappingURL=startWith.js.map
/***/ }),
/***/ 7224:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.subscribeOn = void 0;
var lift_1 = __nccwpck_require__(38669);
function subscribeOn(scheduler, delay) {
if (delay === void 0) { delay = 0; }
return lift_1.operate(function (source, subscriber) {
subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
});
}
exports.subscribeOn = subscribeOn;
//# sourceMappingURL=subscribeOn.js.map
/***/ }),
/***/ 40327:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.switchAll = void 0;
var switchMap_1 = __nccwpck_require__(26704);
var identity_1 = __nccwpck_require__(60283);
function switchAll() {
return switchMap_1.switchMap(identity_1.identity);
}
exports.switchAll = switchAll;
//# sourceMappingURL=switchAll.js.map
/***/ }),
/***/ 26704:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.switchMap = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function switchMap(project, resultSelector) {
return lift_1.operate(function (source, subscriber) {
var innerSubscriber = null;
var index = 0;
var isComplete = false;
var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
var innerIndex = 0;
var outerIndex = index++;
innerFrom_1.innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
innerSubscriber = null;
checkComplete();
})));
}, function () {
isComplete = true;
checkComplete();
}));
});
}
exports.switchMap = switchMap;
//# sourceMappingURL=switchMap.js.map
/***/ }),
/***/ 1713:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.switchMapTo = void 0;
var switchMap_1 = __nccwpck_require__(26704);
var isFunction_1 = __nccwpck_require__(67206);
function switchMapTo(innerObservable, resultSelector) {
return isFunction_1.isFunction(resultSelector) ? switchMap_1.switchMap(function () { return innerObservable; }, resultSelector) : switchMap_1.switchMap(function () { return innerObservable; });
}
exports.switchMapTo = switchMapTo;
//# sourceMappingURL=switchMapTo.js.map
/***/ }),
/***/ 13355:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.switchScan = void 0;
var switchMap_1 = __nccwpck_require__(26704);
var lift_1 = __nccwpck_require__(38669);
function switchScan(accumulator, seed) {
return lift_1.operate(function (source, subscriber) {
var state = seed;
switchMap_1.switchMap(function (value, index) { return accumulator(state, value, index); }, function (_, innerValue) { return ((state = innerValue), innerValue); })(source).subscribe(subscriber);
return function () {
state = null;
};
});
}
exports.switchScan = switchScan;
//# sourceMappingURL=switchScan.js.map
/***/ }),
/***/ 33698:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.take = void 0;
var empty_1 = __nccwpck_require__(70437);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function take(count) {
return count <= 0
?
function () { return empty_1.EMPTY; }
: lift_1.operate(function (source, subscriber) {
var seen = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (++seen <= count) {
subscriber.next(value);
if (count <= seen) {
subscriber.complete();
}
}
}));
});
}
exports.take = take;
//# sourceMappingURL=take.js.map
/***/ }),
/***/ 65041:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.takeLast = void 0;
var empty_1 = __nccwpck_require__(70437);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function takeLast(count) {
return count <= 0
? function () { return empty_1.EMPTY; }
: lift_1.operate(function (source, subscriber) {
var buffer = [];
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
buffer.push(value);
count < buffer.length && buffer.shift();
}, function () {
var e_1, _a;
try {
for (var buffer_1 = __values(buffer), buffer_1_1 = buffer_1.next(); !buffer_1_1.done; buffer_1_1 = buffer_1.next()) {
var value = buffer_1_1.value;
subscriber.next(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (buffer_1_1 && !buffer_1_1.done && (_a = buffer_1.return)) _a.call(buffer_1);
}
finally { if (e_1) throw e_1.error; }
}
subscriber.complete();
}, undefined, function () {
buffer = null;
}));
});
}
exports.takeLast = takeLast;
//# sourceMappingURL=takeLast.js.map
/***/ }),
/***/ 55150:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.takeUntil = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
var noop_1 = __nccwpck_require__(11642);
function takeUntil(notifier) {
return lift_1.operate(function (source, subscriber) {
innerFrom_1.innerFrom(notifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () { return subscriber.complete(); }, noop_1.noop));
!subscriber.closed && source.subscribe(subscriber);
});
}
exports.takeUntil = takeUntil;
//# sourceMappingURL=takeUntil.js.map
/***/ }),
/***/ 76700:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.takeWhile = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function takeWhile(predicate, inclusive) {
if (inclusive === void 0) { inclusive = false; }
return lift_1.operate(function (source, subscriber) {
var index = 0;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var result = predicate(value, index++);
(result || inclusive) && subscriber.next(value);
!result && subscriber.complete();
}));
});
}
exports.takeWhile = takeWhile;
//# sourceMappingURL=takeWhile.js.map
/***/ }),
/***/ 48845:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.tap = void 0;
var isFunction_1 = __nccwpck_require__(67206);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var identity_1 = __nccwpck_require__(60283);
function tap(observerOrNext, error, complete) {
var tapObserver = isFunction_1.isFunction(observerOrNext) || error || complete
?
{ next: observerOrNext, error: error, complete: complete }
: observerOrNext;
return tapObserver
? lift_1.operate(function (source, subscriber) {
var _a;
(_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
var isUnsub = true;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var _a;
(_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
subscriber.next(value);
}, function () {
var _a;
isUnsub = false;
(_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
subscriber.complete();
}, function (err) {
var _a;
isUnsub = false;
(_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
subscriber.error(err);
}, function () {
var _a, _b;
if (isUnsub) {
(_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
}
(_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
}));
})
:
identity_1.identity;
}
exports.tap = tap;
//# sourceMappingURL=tap.js.map
/***/ }),
/***/ 36713:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.throttle = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function throttle(durationSelector, config) {
return lift_1.operate(function (source, subscriber) {
var _a = config !== null && config !== void 0 ? config : {}, _b = _a.leading, leading = _b === void 0 ? true : _b, _c = _a.trailing, trailing = _c === void 0 ? false : _c;
var hasValue = false;
var sendValue = null;
var throttled = null;
var isComplete = false;
var endThrottling = function () {
throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
throttled = null;
if (trailing) {
send();
isComplete && subscriber.complete();
}
};
var cleanupThrottling = function () {
throttled = null;
isComplete && subscriber.complete();
};
var startThrottle = function (value) {
return (throttled = innerFrom_1.innerFrom(durationSelector(value)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));
};
var send = function () {
if (hasValue) {
hasValue = false;
var value = sendValue;
sendValue = null;
subscriber.next(value);
!isComplete && startThrottle(value);
}
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
hasValue = true;
sendValue = value;
!(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
}, function () {
isComplete = true;
!(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
}));
});
}
exports.throttle = throttle;
//# sourceMappingURL=throttle.js.map
/***/ }),
/***/ 83435:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.throttleTime = void 0;
var async_1 = __nccwpck_require__(76072);
var throttle_1 = __nccwpck_require__(36713);
var timer_1 = __nccwpck_require__(59757);
function throttleTime(duration, scheduler, config) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
var duration$ = timer_1.timer(duration, scheduler);
return throttle_1.throttle(function () { return duration$; }, config);
}
exports.throttleTime = throttleTime;
//# sourceMappingURL=throttleTime.js.map
/***/ }),
/***/ 91566:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.throwIfEmpty = void 0;
var EmptyError_1 = __nccwpck_require__(99391);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function throwIfEmpty(errorFactory) {
if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
hasValue = true;
subscriber.next(value);
}, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
});
}
exports.throwIfEmpty = throwIfEmpty;
function defaultErrorFactory() {
return new EmptyError_1.EmptyError();
}
//# sourceMappingURL=throwIfEmpty.js.map
/***/ }),
/***/ 14643:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TimeInterval = exports.timeInterval = void 0;
var async_1 = __nccwpck_require__(76072);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function timeInterval(scheduler) {
if (scheduler === void 0) { scheduler = async_1.asyncScheduler; }
return lift_1.operate(function (source, subscriber) {
var last = scheduler.now();
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var now = scheduler.now();
var interval = now - last;
last = now;
subscriber.next(new TimeInterval(value, interval));
}));
});
}
exports.timeInterval = timeInterval;
var TimeInterval = (function () {
function TimeInterval(value, interval) {
this.value = value;
this.interval = interval;
}
return TimeInterval;
}());
exports.TimeInterval = TimeInterval;
//# sourceMappingURL=timeInterval.js.map
/***/ }),
/***/ 12051:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timeout = exports.TimeoutError = void 0;
var async_1 = __nccwpck_require__(76072);
var isDate_1 = __nccwpck_require__(60935);
var lift_1 = __nccwpck_require__(38669);
var innerFrom_1 = __nccwpck_require__(57105);
var createErrorClass_1 = __nccwpck_require__(8858);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var executeSchedule_1 = __nccwpck_require__(82877);
exports.TimeoutError = createErrorClass_1.createErrorClass(function (_super) {
return function TimeoutErrorImpl(info) {
if (info === void 0) { info = null; }
_super(this);
this.message = 'Timeout has occurred';
this.name = 'TimeoutError';
this.info = info;
};
});
function timeout(config, schedulerArg) {
var _a = (isDate_1.isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config), first = _a.first, each = _a.each, _b = _a.with, _with = _b === void 0 ? timeoutErrorFactory : _b, _c = _a.scheduler, scheduler = _c === void 0 ? schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : async_1.asyncScheduler : _c, _d = _a.meta, meta = _d === void 0 ? null : _d;
if (first == null && each == null) {
throw new TypeError('No timeout provided.');
}
return lift_1.operate(function (source, subscriber) {
var originalSourceSubscription;
var timerSubscription;
var lastValue = null;
var seen = 0;
var startTimer = function (delay) {
timerSubscription = executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
try {
originalSourceSubscription.unsubscribe();
innerFrom_1.innerFrom(_with({
meta: meta,
lastValue: lastValue,
seen: seen,
})).subscribe(subscriber);
}
catch (err) {
subscriber.error(err);
}
}, delay);
};
originalSourceSubscription = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
seen++;
subscriber.next((lastValue = value));
each > 0 && startTimer(each);
}, undefined, undefined, function () {
if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
}
lastValue = null;
}));
!seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);
});
}
exports.timeout = timeout;
function timeoutErrorFactory(info) {
throw new exports.TimeoutError(info);
}
//# sourceMappingURL=timeout.js.map
/***/ }),
/***/ 43540:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timeoutWith = void 0;
var async_1 = __nccwpck_require__(76072);
var isDate_1 = __nccwpck_require__(60935);
var timeout_1 = __nccwpck_require__(12051);
function timeoutWith(due, withObservable, scheduler) {
var first;
var each;
var _with;
scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : async_1.async;
if (isDate_1.isValidDate(due)) {
first = due;
}
else if (typeof due === 'number') {
each = due;
}
if (withObservable) {
_with = function () { return withObservable; };
}
else {
throw new TypeError('No observable provided to switch to');
}
if (first == null && each == null) {
throw new TypeError('No timeout provided.');
}
return timeout_1.timeout({
first: first,
each: each,
scheduler: scheduler,
with: _with,
});
}
exports.timeoutWith = timeoutWith;
//# sourceMappingURL=timeoutWith.js.map
/***/ }),
/***/ 75518:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timestamp = void 0;
var dateTimestampProvider_1 = __nccwpck_require__(91395);
var map_1 = __nccwpck_require__(5987);
function timestamp(timestampProvider) {
if (timestampProvider === void 0) { timestampProvider = dateTimestampProvider_1.dateTimestampProvider; }
return map_1.map(function (value) { return ({ value: value, timestamp: timestampProvider.now() }); });
}
exports.timestamp = timestamp;
//# sourceMappingURL=timestamp.js.map
/***/ }),
/***/ 35114:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toArray = void 0;
var reduce_1 = __nccwpck_require__(62087);
var lift_1 = __nccwpck_require__(38669);
var arrReducer = function (arr, value) { return (arr.push(value), arr); };
function toArray() {
return lift_1.operate(function (source, subscriber) {
reduce_1.reduce(arrReducer, [])(source).subscribe(subscriber);
});
}
exports.toArray = toArray;
//# sourceMappingURL=toArray.js.map
/***/ }),
/***/ 98255:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.window = void 0;
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
var innerFrom_1 = __nccwpck_require__(57105);
function window(windowBoundaries) {
return lift_1.operate(function (source, subscriber) {
var windowSubject = new Subject_1.Subject();
subscriber.next(windowSubject.asObservable());
var errorHandler = function (err) {
windowSubject.error(err);
subscriber.error(err);
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.next(value); }, function () {
windowSubject.complete();
subscriber.complete();
}, errorHandler));
innerFrom_1.innerFrom(windowBoundaries).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function () {
windowSubject.complete();
subscriber.next((windowSubject = new Subject_1.Subject()));
}, noop_1.noop, errorHandler));
return function () {
windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.unsubscribe();
windowSubject = null;
};
});
}
exports.window = window;
//# sourceMappingURL=window.js.map
/***/ }),
/***/ 73144:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.windowCount = void 0;
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
function windowCount(windowSize, startWindowEvery) {
if (startWindowEvery === void 0) { startWindowEvery = 0; }
var startEvery = startWindowEvery > 0 ? startWindowEvery : windowSize;
return lift_1.operate(function (source, subscriber) {
var windows = [new Subject_1.Subject()];
var starts = [];
var count = 0;
subscriber.next(windows[0].asObservable());
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var e_1, _a;
try {
for (var windows_1 = __values(windows), windows_1_1 = windows_1.next(); !windows_1_1.done; windows_1_1 = windows_1.next()) {
var window_1 = windows_1_1.value;
window_1.next(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (windows_1_1 && !windows_1_1.done && (_a = windows_1.return)) _a.call(windows_1);
}
finally { if (e_1) throw e_1.error; }
}
var c = count - windowSize + 1;
if (c >= 0 && c % startEvery === 0) {
windows.shift().complete();
}
if (++count % startEvery === 0) {
var window_2 = new Subject_1.Subject();
windows.push(window_2);
subscriber.next(window_2.asObservable());
}
}, function () {
while (windows.length > 0) {
windows.shift().complete();
}
subscriber.complete();
}, function (err) {
while (windows.length > 0) {
windows.shift().error(err);
}
subscriber.error(err);
}, function () {
starts = null;
windows = null;
}));
});
}
exports.windowCount = windowCount;
//# sourceMappingURL=windowCount.js.map
/***/ }),
/***/ 2738:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.windowTime = void 0;
var Subject_1 = __nccwpck_require__(49944);
var async_1 = __nccwpck_require__(76072);
var Subscription_1 = __nccwpck_require__(79548);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var arrRemove_1 = __nccwpck_require__(68499);
var args_1 = __nccwpck_require__(34890);
var executeSchedule_1 = __nccwpck_require__(82877);
function windowTime(windowTimeSpan) {
var _a, _b;
var otherArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
otherArgs[_i - 1] = arguments[_i];
}
var scheduler = (_a = args_1.popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : async_1.asyncScheduler;
var windowCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null;
var maxWindowSize = otherArgs[1] || Infinity;
return lift_1.operate(function (source, subscriber) {
var windowRecords = [];
var restartOnClose = false;
var closeWindow = function (record) {
var window = record.window, subs = record.subs;
window.complete();
subs.unsubscribe();
arrRemove_1.arrRemove(windowRecords, record);
restartOnClose && startWindow();
};
var startWindow = function () {
if (windowRecords) {
var subs = new Subscription_1.Subscription();
subscriber.add(subs);
var window_1 = new Subject_1.Subject();
var record_1 = {
window: window_1,
subs: subs,
seen: 0,
};
windowRecords.push(record_1);
subscriber.next(window_1.asObservable());
executeSchedule_1.executeSchedule(subs, scheduler, function () { return closeWindow(record_1); }, windowTimeSpan);
}
};
if (windowCreationInterval !== null && windowCreationInterval >= 0) {
executeSchedule_1.executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);
}
else {
restartOnClose = true;
}
startWindow();
var loop = function (cb) { return windowRecords.slice().forEach(cb); };
var terminate = function (cb) {
loop(function (_a) {
var window = _a.window;
return cb(window);
});
cb(subscriber);
subscriber.unsubscribe();
};
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
loop(function (record) {
record.window.next(value);
maxWindowSize <= ++record.seen && closeWindow(record);
});
}, function () { return terminate(function (consumer) { return consumer.complete(); }); }, function (err) { return terminate(function (consumer) { return consumer.error(err); }); }));
return function () {
windowRecords = null;
};
});
}
exports.windowTime = windowTime;
//# sourceMappingURL=windowTime.js.map
/***/ }),
/***/ 52741:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.windowToggle = void 0;
var Subject_1 = __nccwpck_require__(49944);
var Subscription_1 = __nccwpck_require__(79548);
var lift_1 = __nccwpck_require__(38669);
var innerFrom_1 = __nccwpck_require__(57105);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var noop_1 = __nccwpck_require__(11642);
var arrRemove_1 = __nccwpck_require__(68499);
function windowToggle(openings, closingSelector) {
return lift_1.operate(function (source, subscriber) {
var windows = [];
var handleError = function (err) {
while (0 < windows.length) {
windows.shift().error(err);
}
subscriber.error(err);
};
innerFrom_1.innerFrom(openings).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (openValue) {
var window = new Subject_1.Subject();
windows.push(window);
var closingSubscription = new Subscription_1.Subscription();
var closeWindow = function () {
arrRemove_1.arrRemove(windows, window);
window.complete();
closingSubscription.unsubscribe();
};
var closingNotifier;
try {
closingNotifier = innerFrom_1.innerFrom(closingSelector(openValue));
}
catch (err) {
handleError(err);
return;
}
subscriber.next(window.asObservable());
closingSubscription.add(closingNotifier.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, closeWindow, noop_1.noop, handleError)));
}, noop_1.noop));
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
var e_1, _a;
var windowsCopy = windows.slice();
try {
for (var windowsCopy_1 = __values(windowsCopy), windowsCopy_1_1 = windowsCopy_1.next(); !windowsCopy_1_1.done; windowsCopy_1_1 = windowsCopy_1.next()) {
var window_1 = windowsCopy_1_1.value;
window_1.next(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (windowsCopy_1_1 && !windowsCopy_1_1.done && (_a = windowsCopy_1.return)) _a.call(windowsCopy_1);
}
finally { if (e_1) throw e_1.error; }
}
}, function () {
while (0 < windows.length) {
windows.shift().complete();
}
subscriber.complete();
}, handleError, function () {
while (0 < windows.length) {
windows.shift().unsubscribe();
}
}));
});
}
exports.windowToggle = windowToggle;
//# sourceMappingURL=windowToggle.js.map
/***/ }),
/***/ 82645:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.windowWhen = void 0;
var Subject_1 = __nccwpck_require__(49944);
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
function windowWhen(closingSelector) {
return lift_1.operate(function (source, subscriber) {
var window;
var closingSubscriber;
var handleError = function (err) {
window.error(err);
subscriber.error(err);
};
var openWindow = function () {
closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
window === null || window === void 0 ? void 0 : window.complete();
window = new Subject_1.Subject();
subscriber.next(window.asObservable());
var closingNotifier;
try {
closingNotifier = innerFrom_1.innerFrom(closingSelector());
}
catch (err) {
handleError(err);
return;
}
closingNotifier.subscribe((closingSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, openWindow, openWindow, handleError)));
};
openWindow();
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) { return window.next(value); }, function () {
window.complete();
subscriber.complete();
}, handleError, function () {
closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
window = null;
}));
});
}
exports.windowWhen = windowWhen;
//# sourceMappingURL=windowWhen.js.map
/***/ }),
/***/ 20501:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.withLatestFrom = void 0;
var lift_1 = __nccwpck_require__(38669);
var OperatorSubscriber_1 = __nccwpck_require__(69549);
var innerFrom_1 = __nccwpck_require__(57105);
var identity_1 = __nccwpck_require__(60283);
var noop_1 = __nccwpck_require__(11642);
var args_1 = __nccwpck_require__(34890);
function withLatestFrom() {
var inputs = [];
for (var _i = 0; _i < arguments.length; _i++) {
inputs[_i] = arguments[_i];
}
var project = args_1.popResultSelector(inputs);
return lift_1.operate(function (source, subscriber) {
var len = inputs.length;
var otherValues = new Array(len);
var hasValue = inputs.map(function () { return false; });
var ready = false;
var _loop_1 = function (i) {
innerFrom_1.innerFrom(inputs[i]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
otherValues[i] = value;
if (!ready && !hasValue[i]) {
hasValue[i] = true;
(ready = hasValue.every(identity_1.identity)) && (hasValue = null);
}
}, noop_1.noop));
};
for (var i = 0; i < len; i++) {
_loop_1(i);
}
source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
if (ready) {
var values = __spreadArray([value], __read(otherValues));
subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values);
}
}));
});
}
exports.withLatestFrom = withLatestFrom;
//# sourceMappingURL=withLatestFrom.js.map
/***/ }),
/***/ 17600:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.zip = void 0;
var zip_1 = __nccwpck_require__(62504);
var lift_1 = __nccwpck_require__(38669);
function zip() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return lift_1.operate(function (source, subscriber) {
zip_1.zip.apply(void 0, __spreadArray([source], __read(sources))).subscribe(subscriber);
});
}
exports.zip = zip;
//# sourceMappingURL=zip.js.map
/***/ }),
/***/ 92335:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.zipAll = void 0;
var zip_1 = __nccwpck_require__(62504);
var joinAllInternals_1 = __nccwpck_require__(29341);
function zipAll(project) {
return joinAllInternals_1.joinAllInternals(zip_1.zip, project);
}
exports.zipAll = zipAll;
//# sourceMappingURL=zipAll.js.map
/***/ }),
/***/ 95520:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.zipWith = void 0;
var zip_1 = __nccwpck_require__(17600);
function zipWith() {
var otherInputs = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherInputs[_i] = arguments[_i];
}
return zip_1.zip.apply(void 0, __spreadArray([], __read(otherInputs)));
}
exports.zipWith = zipWith;
//# sourceMappingURL=zipWith.js.map
/***/ }),
/***/ 11348:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduleArray = void 0;
var Observable_1 = __nccwpck_require__(53014);
function scheduleArray(input, scheduler) {
return new Observable_1.Observable(function (subscriber) {
var i = 0;
return scheduler.schedule(function () {
if (i === input.length) {
subscriber.complete();
}
else {
subscriber.next(input[i++]);
if (!subscriber.closed) {
this.schedule();
}
}
});
});
}
exports.scheduleArray = scheduleArray;
//# sourceMappingURL=scheduleArray.js.map
/***/ }),
/***/ 75347:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduleAsyncIterable = void 0;
var Observable_1 = __nccwpck_require__(53014);
var executeSchedule_1 = __nccwpck_require__(82877);
function scheduleAsyncIterable(input, scheduler) {
if (!input) {
throw new Error('Iterable cannot be null');
}
return new Observable_1.Observable(function (subscriber) {
executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
var iterator = input[Symbol.asyncIterator]();
executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
iterator.next().then(function (result) {
if (result.done) {
subscriber.complete();
}
else {
subscriber.next(result.value);
}
});
}, 0, true);
});
});
}
exports.scheduleAsyncIterable = scheduleAsyncIterable;
//# sourceMappingURL=scheduleAsyncIterable.js.map
/***/ }),
/***/ 59461:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduleIterable = void 0;
var Observable_1 = __nccwpck_require__(53014);
var iterator_1 = __nccwpck_require__(85517);
var isFunction_1 = __nccwpck_require__(67206);
var executeSchedule_1 = __nccwpck_require__(82877);
function scheduleIterable(input, scheduler) {
return new Observable_1.Observable(function (subscriber) {
var iterator;
executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
iterator = input[iterator_1.iterator]();
executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
var _a;
var value;
var done;
try {
(_a = iterator.next(), value = _a.value, done = _a.done);
}
catch (err) {
subscriber.error(err);
return;
}
if (done) {
subscriber.complete();
}
else {
subscriber.next(value);
}
}, 0, true);
});
return function () { return isFunction_1.isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); };
});
}
exports.scheduleIterable = scheduleIterable;
//# sourceMappingURL=scheduleIterable.js.map
/***/ }),
/***/ 17096:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduleObservable = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var observeOn_1 = __nccwpck_require__(22451);
var subscribeOn_1 = __nccwpck_require__(7224);
function scheduleObservable(input, scheduler) {
return innerFrom_1.innerFrom(input).pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
}
exports.scheduleObservable = scheduleObservable;
//# sourceMappingURL=scheduleObservable.js.map
/***/ }),
/***/ 24087:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.schedulePromise = void 0;
var innerFrom_1 = __nccwpck_require__(57105);
var observeOn_1 = __nccwpck_require__(22451);
var subscribeOn_1 = __nccwpck_require__(7224);
function schedulePromise(input, scheduler) {
return innerFrom_1.innerFrom(input).pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
}
exports.schedulePromise = schedulePromise;
//# sourceMappingURL=schedulePromise.js.map
/***/ }),
/***/ 5967:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduleReadableStreamLike = void 0;
var scheduleAsyncIterable_1 = __nccwpck_require__(75347);
var isReadableStreamLike_1 = __nccwpck_require__(99621);
function scheduleReadableStreamLike(input, scheduler) {
return scheduleAsyncIterable_1.scheduleAsyncIterable(isReadableStreamLike_1.readableStreamLikeToAsyncGenerator(input), scheduler);
}
exports.scheduleReadableStreamLike = scheduleReadableStreamLike;
//# sourceMappingURL=scheduleReadableStreamLike.js.map
/***/ }),
/***/ 6151:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scheduled = void 0;
var scheduleObservable_1 = __nccwpck_require__(17096);
var schedulePromise_1 = __nccwpck_require__(24087);
var scheduleArray_1 = __nccwpck_require__(11348);
var scheduleIterable_1 = __nccwpck_require__(59461);
var scheduleAsyncIterable_1 = __nccwpck_require__(75347);
var isInteropObservable_1 = __nccwpck_require__(67984);
var isPromise_1 = __nccwpck_require__(65585);
var isArrayLike_1 = __nccwpck_require__(24461);
var isIterable_1 = __nccwpck_require__(94292);
var isAsyncIterable_1 = __nccwpck_require__(44408);
var throwUnobservableError_1 = __nccwpck_require__(97364);
var isReadableStreamLike_1 = __nccwpck_require__(99621);
var scheduleReadableStreamLike_1 = __nccwpck_require__(5967);
function scheduled(input, scheduler) {
if (input != null) {
if (isInteropObservable_1.isInteropObservable(input)) {
return scheduleObservable_1.scheduleObservable(input, scheduler);
}
if (isArrayLike_1.isArrayLike(input)) {
return scheduleArray_1.scheduleArray(input, scheduler);
}
if (isPromise_1.isPromise(input)) {
return schedulePromise_1.schedulePromise(input, scheduler);
}
if (isAsyncIterable_1.isAsyncIterable(input)) {
return scheduleAsyncIterable_1.scheduleAsyncIterable(input, scheduler);
}
if (isIterable_1.isIterable(input)) {
return scheduleIterable_1.scheduleIterable(input, scheduler);
}
if (isReadableStreamLike_1.isReadableStreamLike(input)) {
return scheduleReadableStreamLike_1.scheduleReadableStreamLike(input, scheduler);
}
}
throw throwUnobservableError_1.createInvalidObservableTypeError(input);
}
exports.scheduled = scheduled;
//# sourceMappingURL=scheduled.js.map
/***/ }),
/***/ 83848:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Action = void 0;
var Subscription_1 = __nccwpck_require__(79548);
var Action = (function (_super) {
__extends(Action, _super);
function Action(scheduler, work) {
return _super.call(this) || this;
}
Action.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
return this;
};
return Action;
}(Subscription_1.Subscription));
exports.Action = Action;
//# sourceMappingURL=Action.js.map
/***/ }),
/***/ 95991:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AnimationFrameAction = void 0;
var AsyncAction_1 = __nccwpck_require__(13280);
var animationFrameProvider_1 = __nccwpck_require__(62738);
var AnimationFrameAction = (function (_super) {
__extends(AnimationFrameAction, _super);
function AnimationFrameAction(scheduler, work) {
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
return _this;
}
AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
if (delay !== null && delay > 0) {
return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
}
scheduler.actions.push(this);
return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider_1.animationFrameProvider.requestAnimationFrame(function () { return scheduler.flush(undefined); }));
};
AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
var _a;
if (delay === void 0) { delay = 0; }
if (delay != null ? delay > 0 : this.delay > 0) {
return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
}
var actions = scheduler.actions;
if (id != null && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) {
animationFrameProvider_1.animationFrameProvider.cancelAnimationFrame(id);
scheduler._scheduled = undefined;
}
return undefined;
};
return AnimationFrameAction;
}(AsyncAction_1.AsyncAction));
exports.AnimationFrameAction = AnimationFrameAction;
//# sourceMappingURL=AnimationFrameAction.js.map
/***/ }),
/***/ 98768:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AnimationFrameScheduler = void 0;
var AsyncScheduler_1 = __nccwpck_require__(61673);
var AnimationFrameScheduler = (function (_super) {
__extends(AnimationFrameScheduler, _super);
function AnimationFrameScheduler() {
return _super !== null && _super.apply(this, arguments) || this;
}
AnimationFrameScheduler.prototype.flush = function (action) {
this._active = true;
var flushId = this._scheduled;
this._scheduled = undefined;
var actions = this.actions;
var error;
action = action || actions.shift();
do {
if ((error = action.execute(action.state, action.delay))) {
break;
}
} while ((action = actions[0]) && action.id === flushId && actions.shift());
this._active = false;
if (error) {
while ((action = actions[0]) && action.id === flushId && actions.shift()) {
action.unsubscribe();
}
throw error;
}
};
return AnimationFrameScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.AnimationFrameScheduler = AnimationFrameScheduler;
//# sourceMappingURL=AnimationFrameScheduler.js.map
/***/ }),
/***/ 12424:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AsapAction = void 0;
var AsyncAction_1 = __nccwpck_require__(13280);
var immediateProvider_1 = __nccwpck_require__(63475);
var AsapAction = (function (_super) {
__extends(AsapAction, _super);
function AsapAction(scheduler, work) {
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
return _this;
}
AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
if (delay !== null && delay > 0) {
return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
}
scheduler.actions.push(this);
return scheduler._scheduled || (scheduler._scheduled = immediateProvider_1.immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));
};
AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
var _a;
if (delay === void 0) { delay = 0; }
if (delay != null ? delay > 0 : this.delay > 0) {
return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
}
var actions = scheduler.actions;
if (id != null && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) {
immediateProvider_1.immediateProvider.clearImmediate(id);
if (scheduler._scheduled === id) {
scheduler._scheduled = undefined;
}
}
return undefined;
};
return AsapAction;
}(AsyncAction_1.AsyncAction));
exports.AsapAction = AsapAction;
//# sourceMappingURL=AsapAction.js.map
/***/ }),
/***/ 76641:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AsapScheduler = void 0;
var AsyncScheduler_1 = __nccwpck_require__(61673);
var AsapScheduler = (function (_super) {
__extends(AsapScheduler, _super);
function AsapScheduler() {
return _super !== null && _super.apply(this, arguments) || this;
}
AsapScheduler.prototype.flush = function (action) {
this._active = true;
var flushId = this._scheduled;
this._scheduled = undefined;
var actions = this.actions;
var error;
action = action || actions.shift();
do {
if ((error = action.execute(action.state, action.delay))) {
break;
}
} while ((action = actions[0]) && action.id === flushId && actions.shift());
this._active = false;
if (error) {
while ((action = actions[0]) && action.id === flushId && actions.shift()) {
action.unsubscribe();
}
throw error;
}
};
return AsapScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.AsapScheduler = AsapScheduler;
//# sourceMappingURL=AsapScheduler.js.map
/***/ }),
/***/ 13280:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AsyncAction = void 0;
var Action_1 = __nccwpck_require__(83848);
var intervalProvider_1 = __nccwpck_require__(55341);
var arrRemove_1 = __nccwpck_require__(68499);
var AsyncAction = (function (_super) {
__extends(AsyncAction, _super);
function AsyncAction(scheduler, work) {
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
_this.pending = false;
return _this;
}
AsyncAction.prototype.schedule = function (state, delay) {
var _a;
if (delay === void 0) { delay = 0; }
if (this.closed) {
return this;
}
this.state = state;
var id = this.id;
var scheduler = this.scheduler;
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, delay);
}
this.pending = true;
this.delay = delay;
this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay);
return this;
};
AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
if (delay === void 0) { delay = 0; }
return intervalProvider_1.intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
};
AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
if (delay != null && this.delay === delay && this.pending === false) {
return id;
}
if (id != null) {
intervalProvider_1.intervalProvider.clearInterval(id);
}
return undefined;
};
AsyncAction.prototype.execute = function (state, delay) {
if (this.closed) {
return new Error('executing a cancelled action');
}
this.pending = false;
var error = this._execute(state, delay);
if (error) {
return error;
}
else if (this.pending === false && this.id != null) {
this.id = this.recycleAsyncId(this.scheduler, this.id, null);
}
};
AsyncAction.prototype._execute = function (state, _delay) {
var errored = false;
var errorValue;
try {
this.work(state);
}
catch (e) {
errored = true;
errorValue = e ? e : new Error('Scheduled action threw falsy error');
}
if (errored) {
this.unsubscribe();
return errorValue;
}
};
AsyncAction.prototype.unsubscribe = function () {
if (!this.closed) {
var _a = this, id = _a.id, scheduler = _a.scheduler;
var actions = scheduler.actions;
this.work = this.state = this.scheduler = null;
this.pending = false;
arrRemove_1.arrRemove(actions, this);
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, null);
}
this.delay = null;
_super.prototype.unsubscribe.call(this);
}
};
return AsyncAction;
}(Action_1.Action));
exports.AsyncAction = AsyncAction;
//# sourceMappingURL=AsyncAction.js.map
/***/ }),
/***/ 61673:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AsyncScheduler = void 0;
var Scheduler_1 = __nccwpck_require__(76243);
var AsyncScheduler = (function (_super) {
__extends(AsyncScheduler, _super);
function AsyncScheduler(SchedulerAction, now) {
if (now === void 0) { now = Scheduler_1.Scheduler.now; }
var _this = _super.call(this, SchedulerAction, now) || this;
_this.actions = [];
_this._active = false;
return _this;
}
AsyncScheduler.prototype.flush = function (action) {
var actions = this.actions;
if (this._active) {
actions.push(action);
return;
}
var error;
this._active = true;
do {
if ((error = action.execute(action.state, action.delay))) {
break;
}
} while ((action = actions.shift()));
this._active = false;
if (error) {
while ((action = actions.shift())) {
action.unsubscribe();
}
throw error;
}
};
return AsyncScheduler;
}(Scheduler_1.Scheduler));
exports.AsyncScheduler = AsyncScheduler;
//# sourceMappingURL=AsyncScheduler.js.map
/***/ }),
/***/ 32161:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.QueueAction = void 0;
var AsyncAction_1 = __nccwpck_require__(13280);
var QueueAction = (function (_super) {
__extends(QueueAction, _super);
function QueueAction(scheduler, work) {
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
return _this;
}
QueueAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (delay > 0) {
return _super.prototype.schedule.call(this, state, delay);
}
this.delay = delay;
this.state = state;
this.scheduler.flush(this);
return this;
};
QueueAction.prototype.execute = function (state, delay) {
return delay > 0 || this.closed ? _super.prototype.execute.call(this, state, delay) : this._execute(state, delay);
};
QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {
return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
}
scheduler.flush(this);
return 0;
};
return QueueAction;
}(AsyncAction_1.AsyncAction));
exports.QueueAction = QueueAction;
//# sourceMappingURL=QueueAction.js.map
/***/ }),
/***/ 48527:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.QueueScheduler = void 0;
var AsyncScheduler_1 = __nccwpck_require__(61673);
var QueueScheduler = (function (_super) {
__extends(QueueScheduler, _super);
function QueueScheduler() {
return _super !== null && _super.apply(this, arguments) || this;
}
return QueueScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.QueueScheduler = QueueScheduler;
//# sourceMappingURL=QueueScheduler.js.map
/***/ }),
/***/ 75348:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VirtualAction = exports.VirtualTimeScheduler = void 0;
var AsyncAction_1 = __nccwpck_require__(13280);
var Subscription_1 = __nccwpck_require__(79548);
var AsyncScheduler_1 = __nccwpck_require__(61673);
var VirtualTimeScheduler = (function (_super) {
__extends(VirtualTimeScheduler, _super);
function VirtualTimeScheduler(schedulerActionCtor, maxFrames) {
if (schedulerActionCtor === void 0) { schedulerActionCtor = VirtualAction; }
if (maxFrames === void 0) { maxFrames = Infinity; }
var _this = _super.call(this, schedulerActionCtor, function () { return _this.frame; }) || this;
_this.maxFrames = maxFrames;
_this.frame = 0;
_this.index = -1;
return _this;
}
VirtualTimeScheduler.prototype.flush = function () {
var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
var error;
var action;
while ((action = actions[0]) && action.delay <= maxFrames) {
actions.shift();
this.frame = action.delay;
if ((error = action.execute(action.state, action.delay))) {
break;
}
}
if (error) {
while ((action = actions.shift())) {
action.unsubscribe();
}
throw error;
}
};
VirtualTimeScheduler.frameTimeFactor = 10;
return VirtualTimeScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.VirtualTimeScheduler = VirtualTimeScheduler;
var VirtualAction = (function (_super) {
__extends(VirtualAction, _super);
function VirtualAction(scheduler, work, index) {
if (index === void 0) { index = (scheduler.index += 1); }
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
_this.index = index;
_this.active = true;
_this.index = scheduler.index = index;
return _this;
}
VirtualAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (Number.isFinite(delay)) {
if (!this.id) {
return _super.prototype.schedule.call(this, state, delay);
}
this.active = false;
var action = new VirtualAction(this.scheduler, this.work);
this.add(action);
return action.schedule(state, delay);
}
else {
return Subscription_1.Subscription.EMPTY;
}
};
VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
this.delay = scheduler.frame + delay;
var actions = scheduler.actions;
actions.push(this);
actions.sort(VirtualAction.sortActions);
return 1;
};
VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
return undefined;
};
VirtualAction.prototype._execute = function (state, delay) {
if (this.active === true) {
return _super.prototype._execute.call(this, state, delay);
}
};
VirtualAction.sortActions = function (a, b) {
if (a.delay === b.delay) {
if (a.index === b.index) {
return 0;
}
else if (a.index > b.index) {
return 1;
}
else {
return -1;
}
}
else if (a.delay > b.delay) {
return 1;
}
else {
return -1;
}
};
return VirtualAction;
}(AsyncAction_1.AsyncAction));
exports.VirtualAction = VirtualAction;
//# sourceMappingURL=VirtualTimeScheduler.js.map
/***/ }),
/***/ 51359:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.animationFrame = exports.animationFrameScheduler = void 0;
var AnimationFrameAction_1 = __nccwpck_require__(95991);
var AnimationFrameScheduler_1 = __nccwpck_require__(98768);
exports.animationFrameScheduler = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
exports.animationFrame = exports.animationFrameScheduler;
//# sourceMappingURL=animationFrame.js.map
/***/ }),
/***/ 62738:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.animationFrameProvider = void 0;
var Subscription_1 = __nccwpck_require__(79548);
exports.animationFrameProvider = {
schedule: function (callback) {
var request = requestAnimationFrame;
var cancel = cancelAnimationFrame;
var delegate = exports.animationFrameProvider.delegate;
if (delegate) {
request = delegate.requestAnimationFrame;
cancel = delegate.cancelAnimationFrame;
}
var handle = request(function (timestamp) {
cancel = undefined;
callback(timestamp);
});
return new Subscription_1.Subscription(function () { return cancel === null || cancel === void 0 ? void 0 : cancel(handle); });
},
requestAnimationFrame: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var delegate = exports.animationFrameProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.requestAnimationFrame) || requestAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
},
cancelAnimationFrame: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var delegate = exports.animationFrameProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.cancelAnimationFrame) || cancelAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
},
delegate: undefined,
};
//# sourceMappingURL=animationFrameProvider.js.map
/***/ }),
/***/ 43905:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.asap = exports.asapScheduler = void 0;
var AsapAction_1 = __nccwpck_require__(12424);
var AsapScheduler_1 = __nccwpck_require__(76641);
exports.asapScheduler = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
exports.asap = exports.asapScheduler;
//# sourceMappingURL=asap.js.map
/***/ }),
/***/ 76072:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.async = exports.asyncScheduler = void 0;
var AsyncAction_1 = __nccwpck_require__(13280);
var AsyncScheduler_1 = __nccwpck_require__(61673);
exports.asyncScheduler = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
exports.async = exports.asyncScheduler;
//# sourceMappingURL=async.js.map
/***/ }),
/***/ 91395:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.dateTimestampProvider = void 0;
exports.dateTimestampProvider = {
now: function () {
return (exports.dateTimestampProvider.delegate || Date).now();
},
delegate: undefined,
};
//# sourceMappingURL=dateTimestampProvider.js.map
/***/ }),
/***/ 63475:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.immediateProvider = void 0;
var Immediate_1 = __nccwpck_require__(73555);
var setImmediate = Immediate_1.Immediate.setImmediate, clearImmediate = Immediate_1.Immediate.clearImmediate;
exports.immediateProvider = {
setImmediate: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var delegate = exports.immediateProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.setImmediate) || setImmediate).apply(void 0, __spreadArray([], __read(args)));
},
clearImmediate: function (handle) {
var delegate = exports.immediateProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearImmediate) || clearImmediate)(handle);
},
delegate: undefined,
};
//# sourceMappingURL=immediateProvider.js.map
/***/ }),
/***/ 55341:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.intervalProvider = void 0;
exports.intervalProvider = {
setInterval: function (handler, timeout) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var delegate = exports.intervalProvider.delegate;
if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
}
return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
},
clearInterval: function (handle) {
var delegate = exports.intervalProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
},
delegate: undefined,
};
//# sourceMappingURL=intervalProvider.js.map
/***/ }),
/***/ 70143:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.performanceTimestampProvider = void 0;
exports.performanceTimestampProvider = {
now: function () {
return (exports.performanceTimestampProvider.delegate || performance).now();
},
delegate: undefined,
};
//# sourceMappingURL=performanceTimestampProvider.js.map
/***/ }),
/***/ 82059:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.queue = exports.queueScheduler = void 0;
var QueueAction_1 = __nccwpck_require__(32161);
var QueueScheduler_1 = __nccwpck_require__(48527);
exports.queueScheduler = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
exports.queue = exports.queueScheduler;
//# sourceMappingURL=queue.js.map
/***/ }),
/***/ 1613:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timeoutProvider = void 0;
exports.timeoutProvider = {
setTimeout: function (handler, timeout) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var delegate = exports.timeoutProvider.delegate;
if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
}
return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
},
clearTimeout: function (handle) {
var delegate = exports.timeoutProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
},
delegate: undefined,
};
//# sourceMappingURL=timeoutProvider.js.map
/***/ }),
/***/ 85517:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.iterator = exports.getSymbolIterator = void 0;
function getSymbolIterator() {
if (typeof Symbol !== 'function' || !Symbol.iterator) {
return '@@iterator';
}
return Symbol.iterator;
}
exports.getSymbolIterator = getSymbolIterator;
exports.iterator = getSymbolIterator();
//# sourceMappingURL=iterator.js.map
/***/ }),
/***/ 17186:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.observable = void 0;
exports.observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
//# sourceMappingURL=observable.js.map
/***/ }),
/***/ 36639:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map
/***/ }),
/***/ 49796:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ArgumentOutOfRangeError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.ArgumentOutOfRangeError = createErrorClass_1.createErrorClass(function (_super) {
return function ArgumentOutOfRangeErrorImpl() {
_super(this);
this.name = 'ArgumentOutOfRangeError';
this.message = 'argument out of range';
};
});
//# sourceMappingURL=ArgumentOutOfRangeError.js.map
/***/ }),
/***/ 99391:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EmptyError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.EmptyError = createErrorClass_1.createErrorClass(function (_super) { return function EmptyErrorImpl() {
_super(this);
this.name = 'EmptyError';
this.message = 'no elements in sequence';
}; });
//# sourceMappingURL=EmptyError.js.map
/***/ }),
/***/ 73555:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TestTools = exports.Immediate = void 0;
var nextHandle = 1;
var resolved;
var activeHandles = {};
function findAndClearHandle(handle) {
if (handle in activeHandles) {
delete activeHandles[handle];
return true;
}
return false;
}
exports.Immediate = {
setImmediate: function (cb) {
var handle = nextHandle++;
activeHandles[handle] = true;
if (!resolved) {
resolved = Promise.resolve();
}
resolved.then(function () { return findAndClearHandle(handle) && cb(); });
return handle;
},
clearImmediate: function (handle) {
findAndClearHandle(handle);
},
};
exports.TestTools = {
pending: function () {
return Object.keys(activeHandles).length;
}
};
//# sourceMappingURL=Immediate.js.map
/***/ }),
/***/ 74431:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NotFoundError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.NotFoundError = createErrorClass_1.createErrorClass(function (_super) {
return function NotFoundErrorImpl(message) {
_super(this);
this.name = 'NotFoundError';
this.message = message;
};
});
//# sourceMappingURL=NotFoundError.js.map
/***/ }),
/***/ 95266:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ObjectUnsubscribedError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.ObjectUnsubscribedError = createErrorClass_1.createErrorClass(function (_super) {
return function ObjectUnsubscribedErrorImpl() {
_super(this);
this.name = 'ObjectUnsubscribedError';
this.message = 'object unsubscribed';
};
});
//# sourceMappingURL=ObjectUnsubscribedError.js.map
/***/ }),
/***/ 49048:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SequenceError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.SequenceError = createErrorClass_1.createErrorClass(function (_super) {
return function SequenceErrorImpl(message) {
_super(this);
this.name = 'SequenceError';
this.message = message;
};
});
//# sourceMappingURL=SequenceError.js.map
/***/ }),
/***/ 56776:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UnsubscriptionError = void 0;
var createErrorClass_1 = __nccwpck_require__(8858);
exports.UnsubscriptionError = createErrorClass_1.createErrorClass(function (_super) {
return function UnsubscriptionErrorImpl(errors) {
_super(this);
this.message = errors
? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
: '';
this.name = 'UnsubscriptionError';
this.errors = errors;
};
});
//# sourceMappingURL=UnsubscriptionError.js.map
/***/ }),
/***/ 34890:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.popNumber = exports.popScheduler = exports.popResultSelector = void 0;
var isFunction_1 = __nccwpck_require__(67206);
var isScheduler_1 = __nccwpck_require__(84078);
function last(arr) {
return arr[arr.length - 1];
}
function popResultSelector(args) {
return isFunction_1.isFunction(last(args)) ? args.pop() : undefined;
}
exports.popResultSelector = popResultSelector;
function popScheduler(args) {
return isScheduler_1.isScheduler(last(args)) ? args.pop() : undefined;
}
exports.popScheduler = popScheduler;
function popNumber(args, defaultValue) {
return typeof last(args) === 'number' ? args.pop() : defaultValue;
}
exports.popNumber = popNumber;
//# sourceMappingURL=args.js.map
/***/ }),
/***/ 12920:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.argsArgArrayOrObject = void 0;
var isArray = Array.isArray;
var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;
function argsArgArrayOrObject(args) {
if (args.length === 1) {
var first_1 = args[0];
if (isArray(first_1)) {
return { args: first_1, keys: null };
}
if (isPOJO(first_1)) {
var keys = getKeys(first_1);
return {
args: keys.map(function (key) { return first_1[key]; }),
keys: keys,
};
}
}
return { args: args, keys: null };
}
exports.argsArgArrayOrObject = argsArgArrayOrObject;
function isPOJO(obj) {
return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;
}
//# sourceMappingURL=argsArgArrayOrObject.js.map
/***/ }),
/***/ 18824:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.argsOrArgArray = void 0;
var isArray = Array.isArray;
function argsOrArgArray(args) {
return args.length === 1 && isArray(args[0]) ? args[0] : args;
}
exports.argsOrArgArray = argsOrArgArray;
//# sourceMappingURL=argsOrArgArray.js.map
/***/ }),
/***/ 68499:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.arrRemove = void 0;
function arrRemove(arr, item) {
if (arr) {
var index = arr.indexOf(item);
0 <= index && arr.splice(index, 1);
}
}
exports.arrRemove = arrRemove;
//# sourceMappingURL=arrRemove.js.map
/***/ }),
/***/ 8858:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createErrorClass = void 0;
function createErrorClass(createImpl) {
var _super = function (instance) {
Error.call(instance);
instance.stack = new Error().stack;
};
var ctorFunc = createImpl(_super);
ctorFunc.prototype = Object.create(Error.prototype);
ctorFunc.prototype.constructor = ctorFunc;
return ctorFunc;
}
exports.createErrorClass = createErrorClass;
//# sourceMappingURL=createErrorClass.js.map
/***/ }),
/***/ 57834:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createObject = void 0;
function createObject(keys, values) {
return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});
}
exports.createObject = createObject;
//# sourceMappingURL=createObject.js.map
/***/ }),
/***/ 31199:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.captureError = exports.errorContext = void 0;
var config_1 = __nccwpck_require__(92233);
var context = null;
function errorContext(cb) {
if (config_1.config.useDeprecatedSynchronousErrorHandling) {
var isRoot = !context;
if (isRoot) {
context = { errorThrown: false, error: null };
}
cb();
if (isRoot) {
var _a = context, errorThrown = _a.errorThrown, error = _a.error;
context = null;
if (errorThrown) {
throw error;
}
}
}
else {
cb();
}
}
exports.errorContext = errorContext;
function captureError(err) {
if (config_1.config.useDeprecatedSynchronousErrorHandling && context) {
context.errorThrown = true;
context.error = err;
}
}
exports.captureError = captureError;
//# sourceMappingURL=errorContext.js.map
/***/ }),
/***/ 82877:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.executeSchedule = void 0;
function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
if (delay === void 0) { delay = 0; }
if (repeat === void 0) { repeat = false; }
var scheduleSubscription = scheduler.schedule(function () {
work();
if (repeat) {
parentSubscription.add(this.schedule(null, delay));
}
else {
this.unsubscribe();
}
}, delay);
parentSubscription.add(scheduleSubscription);
if (!repeat) {
return scheduleSubscription;
}
}
exports.executeSchedule = executeSchedule;
//# sourceMappingURL=executeSchedule.js.map
/***/ }),
/***/ 60283:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.identity = void 0;
function identity(x) {
return x;
}
exports.identity = identity;
//# sourceMappingURL=identity.js.map
/***/ }),
/***/ 24461:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isArrayLike = void 0;
exports.isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
//# sourceMappingURL=isArrayLike.js.map
/***/ }),
/***/ 44408:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isAsyncIterable = void 0;
var isFunction_1 = __nccwpck_require__(67206);
function isAsyncIterable(obj) {
return Symbol.asyncIterator && isFunction_1.isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
}
exports.isAsyncIterable = isAsyncIterable;
//# sourceMappingURL=isAsyncIterable.js.map
/***/ }),
/***/ 60935:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isValidDate = void 0;
function isValidDate(value) {
return value instanceof Date && !isNaN(value);
}
exports.isValidDate = isValidDate;
//# sourceMappingURL=isDate.js.map
/***/ }),
/***/ 67206:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isFunction = void 0;
function isFunction(value) {
return typeof value === 'function';
}
exports.isFunction = isFunction;
//# sourceMappingURL=isFunction.js.map
/***/ }),
/***/ 67984:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isInteropObservable = void 0;
var observable_1 = __nccwpck_require__(17186);
var isFunction_1 = __nccwpck_require__(67206);
function isInteropObservable(input) {
return isFunction_1.isFunction(input[observable_1.observable]);
}
exports.isInteropObservable = isInteropObservable;
//# sourceMappingURL=isInteropObservable.js.map
/***/ }),
/***/ 94292:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isIterable = void 0;
var iterator_1 = __nccwpck_require__(85517);
var isFunction_1 = __nccwpck_require__(67206);
function isIterable(input) {
return isFunction_1.isFunction(input === null || input === void 0 ? void 0 : input[iterator_1.iterator]);
}
exports.isIterable = isIterable;
//# sourceMappingURL=isIterable.js.map
/***/ }),
/***/ 72259:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isObservable = void 0;
var Observable_1 = __nccwpck_require__(53014);
var isFunction_1 = __nccwpck_require__(67206);
function isObservable(obj) {
return !!obj && (obj instanceof Observable_1.Observable || (isFunction_1.isFunction(obj.lift) && isFunction_1.isFunction(obj.subscribe)));
}
exports.isObservable = isObservable;
//# sourceMappingURL=isObservable.js.map
/***/ }),
/***/ 65585:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPromise = void 0;
var isFunction_1 = __nccwpck_require__(67206);
function isPromise(value) {
return isFunction_1.isFunction(value === null || value === void 0 ? void 0 : value.then);
}
exports.isPromise = isPromise;
//# sourceMappingURL=isPromise.js.map
/***/ }),
/***/ 99621:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isReadableStreamLike = exports.readableStreamLikeToAsyncGenerator = void 0;
var isFunction_1 = __nccwpck_require__(67206);
function readableStreamLikeToAsyncGenerator(readableStream) {
return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
var reader, _a, value, done;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
reader = readableStream.getReader();
_b.label = 1;
case 1:
_b.trys.push([1, , 9, 10]);
_b.label = 2;
case 2:
if (false) {}
return [4, __await(reader.read())];
case 3:
_a = _b.sent(), value = _a.value, done = _a.done;
if (!done) return [3, 5];
return [4, __await(void 0)];
case 4: return [2, _b.sent()];
case 5: return [4, __await(value)];
case 6: return [4, _b.sent()];
case 7:
_b.sent();
return [3, 2];
case 8: return [3, 10];
case 9:
reader.releaseLock();
return [7];
case 10: return [2];
}
});
});
}
exports.readableStreamLikeToAsyncGenerator = readableStreamLikeToAsyncGenerator;
function isReadableStreamLike(obj) {
return isFunction_1.isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
}
exports.isReadableStreamLike = isReadableStreamLike;
//# sourceMappingURL=isReadableStreamLike.js.map
/***/ }),
/***/ 84078:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isScheduler = void 0;
var isFunction_1 = __nccwpck_require__(67206);
function isScheduler(value) {
return value && isFunction_1.isFunction(value.schedule);
}
exports.isScheduler = isScheduler;
//# sourceMappingURL=isScheduler.js.map
/***/ }),
/***/ 38669:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.operate = exports.hasLift = void 0;
var isFunction_1 = __nccwpck_require__(67206);
function hasLift(source) {
return isFunction_1.isFunction(source === null || source === void 0 ? void 0 : source.lift);
}
exports.hasLift = hasLift;
function operate(init) {
return function (source) {
if (hasLift(source)) {
return source.lift(function (liftedSource) {
try {
return init(liftedSource, this);
}
catch (err) {
this.error(err);
}
});
}
throw new TypeError('Unable to lift unknown Observable type');
};
}
exports.operate = operate;
//# sourceMappingURL=lift.js.map
/***/ }),
/***/ 78934:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mapOneOrManyArgs = void 0;
var map_1 = __nccwpck_require__(5987);
var isArray = Array.isArray;
function callOrApply(fn, args) {
return isArray(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);
}
function mapOneOrManyArgs(fn) {
return map_1.map(function (args) { return callOrApply(fn, args); });
}
exports.mapOneOrManyArgs = mapOneOrManyArgs;
//# sourceMappingURL=mapOneOrManyArgs.js.map
/***/ }),
/***/ 11642:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.noop = void 0;
function noop() { }
exports.noop = noop;
//# sourceMappingURL=noop.js.map
/***/ }),
/***/ 54338:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.not = void 0;
function not(pred, thisArg) {
return function (value, index) { return !pred.call(thisArg, value, index); };
}
exports.not = not;
//# sourceMappingURL=not.js.map
/***/ }),
/***/ 49587:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pipeFromArray = exports.pipe = void 0;
var identity_1 = __nccwpck_require__(60283);
function pipe() {
var fns = [];
for (var _i = 0; _i < arguments.length; _i++) {
fns[_i] = arguments[_i];
}
return pipeFromArray(fns);
}
exports.pipe = pipe;
function pipeFromArray(fns) {
if (fns.length === 0) {
return identity_1.identity;
}
if (fns.length === 1) {
return fns[0];
}
return function piped(input) {
return fns.reduce(function (prev, fn) { return fn(prev); }, input);
};
}
exports.pipeFromArray = pipeFromArray;
//# sourceMappingURL=pipe.js.map
/***/ }),
/***/ 92445:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reportUnhandledError = void 0;
var config_1 = __nccwpck_require__(92233);
var timeoutProvider_1 = __nccwpck_require__(1613);
function reportUnhandledError(err) {
timeoutProvider_1.timeoutProvider.setTimeout(function () {
var onUnhandledError = config_1.config.onUnhandledError;
if (onUnhandledError) {
onUnhandledError(err);
}
else {
throw err;
}
});
}
exports.reportUnhandledError = reportUnhandledError;
//# sourceMappingURL=reportUnhandledError.js.map
/***/ }),
/***/ 97364:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createInvalidObservableTypeError = void 0;
function createInvalidObservableTypeError(input) {
return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
}
exports.createInvalidObservableTypeError = createInvalidObservableTypeError;
//# sourceMappingURL=throwUnobservableError.js.map
/***/ }),
/***/ 50749:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mergeAll = exports.merge = exports.max = exports.materialize = exports.mapTo = exports.map = exports.last = exports.isEmpty = exports.ignoreElements = exports.groupBy = exports.first = exports.findIndex = exports.find = exports.finalize = exports.filter = exports.expand = exports.exhaustMap = exports.exhaustAll = exports.exhaust = exports.every = exports.endWith = exports.elementAt = exports.distinctUntilKeyChanged = exports.distinctUntilChanged = exports.distinct = exports.dematerialize = exports.delayWhen = exports.delay = exports.defaultIfEmpty = exports.debounceTime = exports.debounce = exports.count = exports.connect = exports.concatWith = exports.concatMapTo = exports.concatMap = exports.concatAll = exports.concat = exports.combineLatestWith = exports.combineLatest = exports.combineLatestAll = exports.combineAll = exports.catchError = exports.bufferWhen = exports.bufferToggle = exports.bufferTime = exports.bufferCount = exports.buffer = exports.auditTime = exports.audit = void 0;
exports.timeInterval = exports.throwIfEmpty = exports.throttleTime = exports.throttle = exports.tap = exports.takeWhile = exports.takeUntil = exports.takeLast = exports.take = exports.switchScan = exports.switchMapTo = exports.switchMap = exports.switchAll = exports.subscribeOn = exports.startWith = exports.skipWhile = exports.skipUntil = exports.skipLast = exports.skip = exports.single = exports.shareReplay = exports.share = exports.sequenceEqual = exports.scan = exports.sampleTime = exports.sample = exports.refCount = exports.retryWhen = exports.retry = exports.repeatWhen = exports.repeat = exports.reduce = exports.raceWith = exports.race = exports.publishReplay = exports.publishLast = exports.publishBehavior = exports.publish = exports.pluck = exports.partition = exports.pairwise = exports.onErrorResumeNext = exports.observeOn = exports.multicast = exports.min = exports.mergeWith = exports.mergeScan = exports.mergeMapTo = exports.mergeMap = exports.flatMap = void 0;
exports.zipWith = exports.zipAll = exports.zip = exports.withLatestFrom = exports.windowWhen = exports.windowToggle = exports.windowTime = exports.windowCount = exports.window = exports.toArray = exports.timestamp = exports.timeoutWith = exports.timeout = void 0;
var audit_1 = __nccwpck_require__(43471);
Object.defineProperty(exports, "audit", ({ enumerable: true, get: function () { return audit_1.audit; } }));
var auditTime_1 = __nccwpck_require__(18780);
Object.defineProperty(exports, "auditTime", ({ enumerable: true, get: function () { return auditTime_1.auditTime; } }));
var buffer_1 = __nccwpck_require__(34253);
Object.defineProperty(exports, "buffer", ({ enumerable: true, get: function () { return buffer_1.buffer; } }));
var bufferCount_1 = __nccwpck_require__(17253);
Object.defineProperty(exports, "bufferCount", ({ enumerable: true, get: function () { return bufferCount_1.bufferCount; } }));
var bufferTime_1 = __nccwpck_require__(73102);
Object.defineProperty(exports, "bufferTime", ({ enumerable: true, get: function () { return bufferTime_1.bufferTime; } }));
var bufferToggle_1 = __nccwpck_require__(83781);
Object.defineProperty(exports, "bufferToggle", ({ enumerable: true, get: function () { return bufferToggle_1.bufferToggle; } }));
var bufferWhen_1 = __nccwpck_require__(82855);
Object.defineProperty(exports, "bufferWhen", ({ enumerable: true, get: function () { return bufferWhen_1.bufferWhen; } }));
var catchError_1 = __nccwpck_require__(37765);
Object.defineProperty(exports, "catchError", ({ enumerable: true, get: function () { return catchError_1.catchError; } }));
var combineAll_1 = __nccwpck_require__(88817);
Object.defineProperty(exports, "combineAll", ({ enumerable: true, get: function () { return combineAll_1.combineAll; } }));
var combineLatestAll_1 = __nccwpck_require__(91063);
Object.defineProperty(exports, "combineLatestAll", ({ enumerable: true, get: function () { return combineLatestAll_1.combineLatestAll; } }));
var combineLatest_1 = __nccwpck_require__(96008);
Object.defineProperty(exports, "combineLatest", ({ enumerable: true, get: function () { return combineLatest_1.combineLatest; } }));
var combineLatestWith_1 = __nccwpck_require__(19044);
Object.defineProperty(exports, "combineLatestWith", ({ enumerable: true, get: function () { return combineLatestWith_1.combineLatestWith; } }));
var concat_1 = __nccwpck_require__(18500);
Object.defineProperty(exports, "concat", ({ enumerable: true, get: function () { return concat_1.concat; } }));
var concatAll_1 = __nccwpck_require__(88049);
Object.defineProperty(exports, "concatAll", ({ enumerable: true, get: function () { return concatAll_1.concatAll; } }));
var concatMap_1 = __nccwpck_require__(19130);
Object.defineProperty(exports, "concatMap", ({ enumerable: true, get: function () { return concatMap_1.concatMap; } }));
var concatMapTo_1 = __nccwpck_require__(61596);
Object.defineProperty(exports, "concatMapTo", ({ enumerable: true, get: function () { return concatMapTo_1.concatMapTo; } }));
var concatWith_1 = __nccwpck_require__(97998);
Object.defineProperty(exports, "concatWith", ({ enumerable: true, get: function () { return concatWith_1.concatWith; } }));
var connect_1 = __nccwpck_require__(51101);
Object.defineProperty(exports, "connect", ({ enumerable: true, get: function () { return connect_1.connect; } }));
var count_1 = __nccwpck_require__(36571);
Object.defineProperty(exports, "count", ({ enumerable: true, get: function () { return count_1.count; } }));
var debounce_1 = __nccwpck_require__(19348);
Object.defineProperty(exports, "debounce", ({ enumerable: true, get: function () { return debounce_1.debounce; } }));
var debounceTime_1 = __nccwpck_require__(62379);
Object.defineProperty(exports, "debounceTime", ({ enumerable: true, get: function () { return debounceTime_1.debounceTime; } }));
var defaultIfEmpty_1 = __nccwpck_require__(30621);
Object.defineProperty(exports, "defaultIfEmpty", ({ enumerable: true, get: function () { return defaultIfEmpty_1.defaultIfEmpty; } }));
var delay_1 = __nccwpck_require__(99818);
Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_1.delay; } }));
var delayWhen_1 = __nccwpck_require__(16994);
Object.defineProperty(exports, "delayWhen", ({ enumerable: true, get: function () { return delayWhen_1.delayWhen; } }));
var dematerialize_1 = __nccwpck_require__(95338);
Object.defineProperty(exports, "dematerialize", ({ enumerable: true, get: function () { return dematerialize_1.dematerialize; } }));
var distinct_1 = __nccwpck_require__(52594);
Object.defineProperty(exports, "distinct", ({ enumerable: true, get: function () { return distinct_1.distinct; } }));
var distinctUntilChanged_1 = __nccwpck_require__(20632);
Object.defineProperty(exports, "distinctUntilChanged", ({ enumerable: true, get: function () { return distinctUntilChanged_1.distinctUntilChanged; } }));
var distinctUntilKeyChanged_1 = __nccwpck_require__(13809);
Object.defineProperty(exports, "distinctUntilKeyChanged", ({ enumerable: true, get: function () { return distinctUntilKeyChanged_1.distinctUntilKeyChanged; } }));
var elementAt_1 = __nccwpck_require__(73381);
Object.defineProperty(exports, "elementAt", ({ enumerable: true, get: function () { return elementAt_1.elementAt; } }));
var endWith_1 = __nccwpck_require__(42961);
Object.defineProperty(exports, "endWith", ({ enumerable: true, get: function () { return endWith_1.endWith; } }));
var every_1 = __nccwpck_require__(69559);
Object.defineProperty(exports, "every", ({ enumerable: true, get: function () { return every_1.every; } }));
var exhaust_1 = __nccwpck_require__(75686);
Object.defineProperty(exports, "exhaust", ({ enumerable: true, get: function () { return exhaust_1.exhaust; } }));
var exhaustAll_1 = __nccwpck_require__(79777);
Object.defineProperty(exports, "exhaustAll", ({ enumerable: true, get: function () { return exhaustAll_1.exhaustAll; } }));
var exhaustMap_1 = __nccwpck_require__(21527);
Object.defineProperty(exports, "exhaustMap", ({ enumerable: true, get: function () { return exhaustMap_1.exhaustMap; } }));
var expand_1 = __nccwpck_require__(21585);
Object.defineProperty(exports, "expand", ({ enumerable: true, get: function () { return expand_1.expand; } }));
var filter_1 = __nccwpck_require__(36894);
Object.defineProperty(exports, "filter", ({ enumerable: true, get: function () { return filter_1.filter; } }));
var finalize_1 = __nccwpck_require__(4013);
Object.defineProperty(exports, "finalize", ({ enumerable: true, get: function () { return finalize_1.finalize; } }));
var find_1 = __nccwpck_require__(28981);
Object.defineProperty(exports, "find", ({ enumerable: true, get: function () { return find_1.find; } }));
var findIndex_1 = __nccwpck_require__(92602);
Object.defineProperty(exports, "findIndex", ({ enumerable: true, get: function () { return findIndex_1.findIndex; } }));
var first_1 = __nccwpck_require__(63345);
Object.defineProperty(exports, "first", ({ enumerable: true, get: function () { return first_1.first; } }));
var groupBy_1 = __nccwpck_require__(51650);
Object.defineProperty(exports, "groupBy", ({ enumerable: true, get: function () { return groupBy_1.groupBy; } }));
var ignoreElements_1 = __nccwpck_require__(31062);
Object.defineProperty(exports, "ignoreElements", ({ enumerable: true, get: function () { return ignoreElements_1.ignoreElements; } }));
var isEmpty_1 = __nccwpck_require__(77722);
Object.defineProperty(exports, "isEmpty", ({ enumerable: true, get: function () { return isEmpty_1.isEmpty; } }));
var last_1 = __nccwpck_require__(46831);
Object.defineProperty(exports, "last", ({ enumerable: true, get: function () { return last_1.last; } }));
var map_1 = __nccwpck_require__(5987);
Object.defineProperty(exports, "map", ({ enumerable: true, get: function () { return map_1.map; } }));
var mapTo_1 = __nccwpck_require__(52300);
Object.defineProperty(exports, "mapTo", ({ enumerable: true, get: function () { return mapTo_1.mapTo; } }));
var materialize_1 = __nccwpck_require__(67108);
Object.defineProperty(exports, "materialize", ({ enumerable: true, get: function () { return materialize_1.materialize; } }));
var max_1 = __nccwpck_require__(17314);
Object.defineProperty(exports, "max", ({ enumerable: true, get: function () { return max_1.max; } }));
var merge_1 = __nccwpck_require__(39510);
Object.defineProperty(exports, "merge", ({ enumerable: true, get: function () { return merge_1.merge; } }));
var mergeAll_1 = __nccwpck_require__(2057);
Object.defineProperty(exports, "mergeAll", ({ enumerable: true, get: function () { return mergeAll_1.mergeAll; } }));
var flatMap_1 = __nccwpck_require__(40186);
Object.defineProperty(exports, "flatMap", ({ enumerable: true, get: function () { return flatMap_1.flatMap; } }));
var mergeMap_1 = __nccwpck_require__(69914);
Object.defineProperty(exports, "mergeMap", ({ enumerable: true, get: function () { return mergeMap_1.mergeMap; } }));
var mergeMapTo_1 = __nccwpck_require__(49151);
Object.defineProperty(exports, "mergeMapTo", ({ enumerable: true, get: function () { return mergeMapTo_1.mergeMapTo; } }));
var mergeScan_1 = __nccwpck_require__(11519);
Object.defineProperty(exports, "mergeScan", ({ enumerable: true, get: function () { return mergeScan_1.mergeScan; } }));
var mergeWith_1 = __nccwpck_require__(22117);
Object.defineProperty(exports, "mergeWith", ({ enumerable: true, get: function () { return mergeWith_1.mergeWith; } }));
var min_1 = __nccwpck_require__(87641);
Object.defineProperty(exports, "min", ({ enumerable: true, get: function () { return min_1.min; } }));
var multicast_1 = __nccwpck_require__(65457);
Object.defineProperty(exports, "multicast", ({ enumerable: true, get: function () { return multicast_1.multicast; } }));
var observeOn_1 = __nccwpck_require__(22451);
Object.defineProperty(exports, "observeOn", ({ enumerable: true, get: function () { return observeOn_1.observeOn; } }));
var onErrorResumeNextWith_1 = __nccwpck_require__(33569);
Object.defineProperty(exports, "onErrorResumeNext", ({ enumerable: true, get: function () { return onErrorResumeNextWith_1.onErrorResumeNext; } }));
var pairwise_1 = __nccwpck_require__(52206);
Object.defineProperty(exports, "pairwise", ({ enumerable: true, get: function () { return pairwise_1.pairwise; } }));
var partition_1 = __nccwpck_require__(55949);
Object.defineProperty(exports, "partition", ({ enumerable: true, get: function () { return partition_1.partition; } }));
var pluck_1 = __nccwpck_require__(16073);
Object.defineProperty(exports, "pluck", ({ enumerable: true, get: function () { return pluck_1.pluck; } }));
var publish_1 = __nccwpck_require__(84084);
Object.defineProperty(exports, "publish", ({ enumerable: true, get: function () { return publish_1.publish; } }));
var publishBehavior_1 = __nccwpck_require__(40045);
Object.defineProperty(exports, "publishBehavior", ({ enumerable: true, get: function () { return publishBehavior_1.publishBehavior; } }));
var publishLast_1 = __nccwpck_require__(84149);
Object.defineProperty(exports, "publishLast", ({ enumerable: true, get: function () { return publishLast_1.publishLast; } }));
var publishReplay_1 = __nccwpck_require__(47656);
Object.defineProperty(exports, "publishReplay", ({ enumerable: true, get: function () { return publishReplay_1.publishReplay; } }));
var race_1 = __nccwpck_require__(85846);
Object.defineProperty(exports, "race", ({ enumerable: true, get: function () { return race_1.race; } }));
var raceWith_1 = __nccwpck_require__(58008);
Object.defineProperty(exports, "raceWith", ({ enumerable: true, get: function () { return raceWith_1.raceWith; } }));
var reduce_1 = __nccwpck_require__(62087);
Object.defineProperty(exports, "reduce", ({ enumerable: true, get: function () { return reduce_1.reduce; } }));
var repeat_1 = __nccwpck_require__(22418);
Object.defineProperty(exports, "repeat", ({ enumerable: true, get: function () { return repeat_1.repeat; } }));
var repeatWhen_1 = __nccwpck_require__(70754);
Object.defineProperty(exports, "repeatWhen", ({ enumerable: true, get: function () { return repeatWhen_1.repeatWhen; } }));
var retry_1 = __nccwpck_require__(56251);
Object.defineProperty(exports, "retry", ({ enumerable: true, get: function () { return retry_1.retry; } }));
var retryWhen_1 = __nccwpck_require__(69018);
Object.defineProperty(exports, "retryWhen", ({ enumerable: true, get: function () { return retryWhen_1.retryWhen; } }));
var refCount_1 = __nccwpck_require__(2331);
Object.defineProperty(exports, "refCount", ({ enumerable: true, get: function () { return refCount_1.refCount; } }));
var sample_1 = __nccwpck_require__(13774);
Object.defineProperty(exports, "sample", ({ enumerable: true, get: function () { return sample_1.sample; } }));
var sampleTime_1 = __nccwpck_require__(49807);
Object.defineProperty(exports, "sampleTime", ({ enumerable: true, get: function () { return sampleTime_1.sampleTime; } }));
var scan_1 = __nccwpck_require__(25578);
Object.defineProperty(exports, "scan", ({ enumerable: true, get: function () { return scan_1.scan; } }));
var sequenceEqual_1 = __nccwpck_require__(16126);
Object.defineProperty(exports, "sequenceEqual", ({ enumerable: true, get: function () { return sequenceEqual_1.sequenceEqual; } }));
var share_1 = __nccwpck_require__(48960);
Object.defineProperty(exports, "share", ({ enumerable: true, get: function () { return share_1.share; } }));
var shareReplay_1 = __nccwpck_require__(92118);
Object.defineProperty(exports, "shareReplay", ({ enumerable: true, get: function () { return shareReplay_1.shareReplay; } }));
var single_1 = __nccwpck_require__(58441);
Object.defineProperty(exports, "single", ({ enumerable: true, get: function () { return single_1.single; } }));
var skip_1 = __nccwpck_require__(80947);
Object.defineProperty(exports, "skip", ({ enumerable: true, get: function () { return skip_1.skip; } }));
var skipLast_1 = __nccwpck_require__(65865);
Object.defineProperty(exports, "skipLast", ({ enumerable: true, get: function () { return skipLast_1.skipLast; } }));
var skipUntil_1 = __nccwpck_require__(41110);
Object.defineProperty(exports, "skipUntil", ({ enumerable: true, get: function () { return skipUntil_1.skipUntil; } }));
var skipWhile_1 = __nccwpck_require__(92550);
Object.defineProperty(exports, "skipWhile", ({ enumerable: true, get: function () { return skipWhile_1.skipWhile; } }));
var startWith_1 = __nccwpck_require__(25471);
Object.defineProperty(exports, "startWith", ({ enumerable: true, get: function () { return startWith_1.startWith; } }));
var subscribeOn_1 = __nccwpck_require__(7224);
Object.defineProperty(exports, "subscribeOn", ({ enumerable: true, get: function () { return subscribeOn_1.subscribeOn; } }));
var switchAll_1 = __nccwpck_require__(40327);
Object.defineProperty(exports, "switchAll", ({ enumerable: true, get: function () { return switchAll_1.switchAll; } }));
var switchMap_1 = __nccwpck_require__(26704);
Object.defineProperty(exports, "switchMap", ({ enumerable: true, get: function () { return switchMap_1.switchMap; } }));
var switchMapTo_1 = __nccwpck_require__(1713);
Object.defineProperty(exports, "switchMapTo", ({ enumerable: true, get: function () { return switchMapTo_1.switchMapTo; } }));
var switchScan_1 = __nccwpck_require__(13355);
Object.defineProperty(exports, "switchScan", ({ enumerable: true, get: function () { return switchScan_1.switchScan; } }));
var take_1 = __nccwpck_require__(33698);
Object.defineProperty(exports, "take", ({ enumerable: true, get: function () { return take_1.take; } }));
var takeLast_1 = __nccwpck_require__(65041);
Object.defineProperty(exports, "takeLast", ({ enumerable: true, get: function () { return takeLast_1.takeLast; } }));
var takeUntil_1 = __nccwpck_require__(55150);
Object.defineProperty(exports, "takeUntil", ({ enumerable: true, get: function () { return takeUntil_1.takeUntil; } }));
var takeWhile_1 = __nccwpck_require__(76700);
Object.defineProperty(exports, "takeWhile", ({ enumerable: true, get: function () { return takeWhile_1.takeWhile; } }));
var tap_1 = __nccwpck_require__(48845);
Object.defineProperty(exports, "tap", ({ enumerable: true, get: function () { return tap_1.tap; } }));
var throttle_1 = __nccwpck_require__(36713);
Object.defineProperty(exports, "throttle", ({ enumerable: true, get: function () { return throttle_1.throttle; } }));
var throttleTime_1 = __nccwpck_require__(83435);
Object.defineProperty(exports, "throttleTime", ({ enumerable: true, get: function () { return throttleTime_1.throttleTime; } }));
var throwIfEmpty_1 = __nccwpck_require__(91566);
Object.defineProperty(exports, "throwIfEmpty", ({ enumerable: true, get: function () { return throwIfEmpty_1.throwIfEmpty; } }));
var timeInterval_1 = __nccwpck_require__(14643);
Object.defineProperty(exports, "timeInterval", ({ enumerable: true, get: function () { return timeInterval_1.timeInterval; } }));
var timeout_1 = __nccwpck_require__(12051);
Object.defineProperty(exports, "timeout", ({ enumerable: true, get: function () { return timeout_1.timeout; } }));
var timeoutWith_1 = __nccwpck_require__(43540);
Object.defineProperty(exports, "timeoutWith", ({ enumerable: true, get: function () { return timeoutWith_1.timeoutWith; } }));
var timestamp_1 = __nccwpck_require__(75518);
Object.defineProperty(exports, "timestamp", ({ enumerable: true, get: function () { return timestamp_1.timestamp; } }));
var toArray_1 = __nccwpck_require__(35114);
Object.defineProperty(exports, "toArray", ({ enumerable: true, get: function () { return toArray_1.toArray; } }));
var window_1 = __nccwpck_require__(98255);
Object.defineProperty(exports, "window", ({ enumerable: true, get: function () { return window_1.window; } }));
var windowCount_1 = __nccwpck_require__(73144);
Object.defineProperty(exports, "windowCount", ({ enumerable: true, get: function () { return windowCount_1.windowCount; } }));
var windowTime_1 = __nccwpck_require__(2738);
Object.defineProperty(exports, "windowTime", ({ enumerable: true, get: function () { return windowTime_1.windowTime; } }));
var windowToggle_1 = __nccwpck_require__(52741);
Object.defineProperty(exports, "windowToggle", ({ enumerable: true, get: function () { return windowToggle_1.windowToggle; } }));
var windowWhen_1 = __nccwpck_require__(82645);
Object.defineProperty(exports, "windowWhen", ({ enumerable: true, get: function () { return windowWhen_1.windowWhen; } }));
var withLatestFrom_1 = __nccwpck_require__(20501);
Object.defineProperty(exports, "withLatestFrom", ({ enumerable: true, get: function () { return withLatestFrom_1.withLatestFrom; } }));
var zip_1 = __nccwpck_require__(17600);
Object.defineProperty(exports, "zip", ({ enumerable: true, get: function () { return zip_1.zip; } }));
var zipAll_1 = __nccwpck_require__(92335);
Object.defineProperty(exports, "zipAll", ({ enumerable: true, get: function () { return zipAll_1.zipAll; } }));
var zipWith_1 = __nccwpck_require__(95520);
Object.defineProperty(exports, "zipWith", ({ enumerable: true, get: function () { return zipWith_1.zipWith; } }));
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 4905:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const parse = __nccwpck_require__(7703)
const types = parse.types
function safeRegex (re, opts) {
if (!opts) opts = {}
const replimit = opts.limit === undefined ? 25 : opts.limit
if (isRegExp(re)) re = re.source
else if (typeof re !== 'string') re = String(re)
try { re = parse(re) } catch (err) { return false }
let reps = 0
return (function walk (node, starHeight) {
let i
let ok
let len
if (node.type === types.REPETITION) {
starHeight++
reps++
if (starHeight > 1) return false
if (reps > replimit) return false
}
if (node.options) {
for (i = 0, len = node.options.length; i < len; i++) {
ok = walk({ stack: node.options[i] }, starHeight)
if (!ok) return false
}
}
const stack = node.stack || (node.value && node.value.stack)
if (!stack) return true
for (i = 0; i < stack.length; i++) {
ok = walk(stack[i], starHeight)
if (!ok) return false
}
return true
})(re, 0)
}
function isRegExp (x) {
return {}.toString.call(x) === '[object RegExp]'
}
module.exports = safeRegex
module.exports["default"] = safeRegex
module.exports.safeRegex = safeRegex
/***/ }),
/***/ 37560:
/***/ ((module, exports) => {
"use strict";
const { hasOwnProperty } = Object.prototype
const stringify = configure()
// @ts-expect-error
stringify.configure = configure
// @ts-expect-error
stringify.stringify = stringify
// @ts-expect-error
stringify.default = stringify
// @ts-expect-error used for named export
exports.stringify = stringify
// @ts-expect-error used for named export
exports.configure = configure
module.exports = stringify
// eslint-disable-next-line no-control-regex
const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/
// Escape C0 control characters, double quotes, the backslash and every code
// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.
function strEscape (str) {
// Some magic numbers that worked out fine while benchmarking with v8 8.0
if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {
return `"${str}"`
}
return JSON.stringify(str)
}
function insertSort (array) {
// Insertion sort is very efficient for small input sizes but it has a bad
// worst case complexity. Thus, use native array sort for bigger values.
if (array.length > 2e2) {
return array.sort()
}
for (let i = 1; i < array.length; i++) {
const currentValue = array[i]
let position = i
while (position !== 0 && array[position - 1] > currentValue) {
array[position] = array[position - 1]
position--
}
array[position] = currentValue
}
return array
}
const typedArrayPrototypeGetSymbolToStringTag =
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(
Object.getPrototypeOf(
new Int8Array()
)
),
Symbol.toStringTag
).get
function isTypedArrayWithEntries (value) {
return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0
}
function stringifyTypedArray (array, separator, maximumBreadth) {
if (array.length < maximumBreadth) {
maximumBreadth = array.length
}
const whitespace = separator === ',' ? '' : ' '
let res = `"0":${whitespace}${array[0]}`
for (let i = 1; i < maximumBreadth; i++) {
res += `${separator}"${i}":${whitespace}${array[i]}`
}
return res
}
function getCircularValueOption (options) {
if (hasOwnProperty.call(options, 'circularValue')) {
const circularValue = options.circularValue
if (typeof circularValue === 'string') {
return `"${circularValue}"`
}
if (circularValue == null) {
return circularValue
}
if (circularValue === Error || circularValue === TypeError) {
return {
toString () {
throw new TypeError('Converting circular structure to JSON')
}
}
}
throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')
}
return '"[Circular]"'
}
function getBooleanOption (options, key) {
let value
if (hasOwnProperty.call(options, key)) {
value = options[key]
if (typeof value !== 'boolean') {
throw new TypeError(`The "${key}" argument must be of type boolean`)
}
}
return value === undefined ? true : value
}
function getPositiveIntegerOption (options, key) {
let value
if (hasOwnProperty.call(options, key)) {
value = options[key]
if (typeof value !== 'number') {
throw new TypeError(`The "${key}" argument must be of type number`)
}
if (!Number.isInteger(value)) {
throw new TypeError(`The "${key}" argument must be an integer`)
}
if (value < 1) {
throw new RangeError(`The "${key}" argument must be >= 1`)
}
}
return value === undefined ? Infinity : value
}
function getItemCount (number) {
if (number === 1) {
return '1 item'
}
return `${number} items`
}
function getUniqueReplacerSet (replacerArray) {
const replacerSet = new Set()
for (const value of replacerArray) {
if (typeof value === 'string' || typeof value === 'number') {
replacerSet.add(String(value))
}
}
return replacerSet
}
function getStrictOption (options) {
if (hasOwnProperty.call(options, 'strict')) {
const value = options.strict
if (typeof value !== 'boolean') {
throw new TypeError('The "strict" argument must be of type boolean')
}
if (value) {
return (value) => {
let message = `Object can not safely be stringified. Received type ${typeof value}`
if (typeof value !== 'function') message += ` (${value.toString()})`
throw new Error(message)
}
}
}
}
function configure (options) {
options = { ...options }
const fail = getStrictOption(options)
if (fail) {
if (options.bigint === undefined) {
options.bigint = false
}
if (!('circularValue' in options)) {
options.circularValue = Error
}
}
const circularValue = getCircularValueOption(options)
const bigint = getBooleanOption(options, 'bigint')
const deterministic = getBooleanOption(options, 'deterministic')
const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')
const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')
function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {
let value = parent[key]
if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
value = value.toJSON(key)
}
value = replacer.call(parent, key, value)
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
let res = ''
let join = ','
const originalIndentation = indentation
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
if (spacer !== '') {
indentation += spacer
res += `\n${indentation}`
join = `,\n${indentation}`
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
if (spacer !== '') {
res += `\n${originalIndentation}`
}
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
let whitespace = ''
let separator = ''
if (spacer !== '') {
indentation += spacer
join = `,\n${indentation}`
whitespace = ' '
}
const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (deterministic && !isTypedArrayWithEntries(value)) {
keys = insertSort(keys)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${whitespace}${tmp}`
separator = join
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`
separator = join
}
if (spacer !== '' && separator.length > 1) {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {
if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
value = value.toJSON(key)
}
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
const originalIndentation = indentation
let res = ''
let join = ','
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
if (spacer !== '') {
indentation += spacer
res += `\n${indentation}`
join = `,\n${indentation}`
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
if (spacer !== '') {
res += `\n${originalIndentation}`
}
stack.pop()
return `[${res}]`
}
stack.push(value)
let whitespace = ''
if (spacer !== '') {
indentation += spacer
join = `,\n${indentation}`
whitespace = ' '
}
let separator = ''
for (const key of replacer) {
const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${whitespace}${tmp}`
separator = join
}
}
if (spacer !== '' && separator.length > 1) {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifyIndent (key, value, stack, spacer, indentation) {
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (typeof value.toJSON === 'function') {
value = value.toJSON(key)
// Prevent calling `toJSON` again.
if (typeof value !== 'object') {
return stringifyIndent(key, value, stack, spacer, indentation)
}
if (value === null) {
return 'null'
}
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
const originalIndentation = indentation
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
indentation += spacer
let res = `\n${indentation}`
const join = `,\n${indentation}`
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
res += `\n${originalIndentation}`
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
indentation += spacer
const join = `,\n${indentation}`
let res = ''
let separator = ''
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, join, maximumBreadth)
keys = keys.slice(value.length)
maximumPropertiesToStringify -= value.length
separator = join
}
if (deterministic) {
keys = insertSort(keys)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}: ${tmp}`
separator = join
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`
separator = join
}
if (separator !== '') {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifySimple (key, value, stack) {
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (typeof value.toJSON === 'function') {
value = value.toJSON(key)
// Prevent calling `toJSON` again
if (typeof value !== 'object') {
return stringifySimple(key, value, stack)
}
if (value === null) {
return 'null'
}
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
let res = ''
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifySimple(String(i), value[i], stack)
res += tmp !== undefined ? tmp : 'null'
res += ','
}
const tmp = stringifySimple(String(i), value[i], stack)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `,"... ${getItemCount(removedKeys)} not stringified"`
}
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
let separator = ''
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, ',', maximumBreadth)
keys = keys.slice(value.length)
maximumPropertiesToStringify -= value.length
separator = ','
}
if (deterministic) {
keys = insertSort(keys)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifySimple(key, value[key], stack)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${tmp}`
separator = ','
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringify (value, replacer, space) {
if (arguments.length > 1) {
let spacer = ''
if (typeof space === 'number') {
spacer = ' '.repeat(Math.min(space, 10))
} else if (typeof space === 'string') {
spacer = space.slice(0, 10)
}
if (replacer != null) {
if (typeof replacer === 'function') {
return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')
}
if (Array.isArray(replacer)) {
return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')
}
}
if (spacer.length !== 0) {
return stringifyIndent('', value, [], spacer, '')
}
}
return stringifySimple('', value, [])
}
return stringify
}
/***/ }),
/***/ 70707:
/***/ ((module) => {
"use strict";
const hasBuffer = typeof Buffer !== 'undefined'
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/
function _parse (text, reviver, options) {
// Normalize arguments
if (options == null) {
if (reviver !== null && typeof reviver === 'object') {
options = reviver
reviver = undefined
}
}
if (hasBuffer && Buffer.isBuffer(text)) {
text = text.toString()
}
// BOM checker
if (text && text.charCodeAt(0) === 0xFEFF) {
text = text.slice(1)
}
// Parse normally, allowing exceptions
const obj = JSON.parse(text, reviver)
// Ignore null and non-objects
if (obj === null || typeof obj !== 'object') {
return obj
}
const protoAction = (options && options.protoAction) || 'error'
const constructorAction = (options && options.constructorAction) || 'error'
// options: 'error' (default) / 'remove' / 'ignore'
if (protoAction === 'ignore' && constructorAction === 'ignore') {
return obj
}
if (protoAction !== 'ignore' && constructorAction !== 'ignore') {
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
return obj
}
} else if (protoAction !== 'ignore' && constructorAction === 'ignore') {
if (suspectProtoRx.test(text) === false) {
return obj
}
} else {
if (suspectConstructorRx.test(text) === false) {
return obj
}
}
// Scan result for proto keys
return filter(obj, { protoAction, constructorAction, safe: options && options.safe })
}
function filter (obj, { protoAction = 'error', constructorAction = 'error', safe } = {}) {
let next = [obj]
while (next.length) {
const nodes = next
next = []
for (const node of nodes) {
if (protoAction !== 'ignore' && Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
if (safe === true) {
return null
} else if (protoAction === 'error') {
throw new SyntaxError('Object contains forbidden prototype property')
}
delete node.__proto__ // eslint-disable-line no-proto
}
if (constructorAction !== 'ignore' &&
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')) { // Avoid calling node.hasOwnProperty directly
if (safe === true) {
return null
} else if (constructorAction === 'error') {
throw new SyntaxError('Object contains forbidden prototype property')
}
delete node.constructor
}
for (const key in node) {
const value = node[key]
if (value && typeof value === 'object') {
next.push(value)
}
}
}
}
return obj
}
function parse (text, reviver, options) {
const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 0
try {
return _parse(text, reviver, options)
} finally {
Error.stackTraceLimit = stackTraceLimit
}
}
function safeParse (text, reviver) {
const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 0
try {
return _parse(text, reviver, { safe: true })
} catch (_e) {
return null
} finally {
Error.stackTraceLimit = stackTraceLimit
}
}
module.exports = parse
module.exports["default"] = parse
module.exports.parse = parse
module.exports.safeParse = safeParse
module.exports.scan = filter
/***/ }),
/***/ 91532:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
comp = comp.trim().split(/\s+/).join(' ')
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
options = parseOptions(options)
// Special cases where nothing can possibly be lower
if (options.includePrerelease &&
(this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
return false
}
if (!options.includePrerelease &&
(this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false
}
// Same direction increasing (> or >=)
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
return true
}
// Same direction decreasing (< or <=)
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
return true
}
// same SemVer and both sides are inclusive (<= or >=)
if (
(this.semver.version === comp.semver.version) &&
this.operator.includes('=') && comp.operator.includes('=')) {
return true
}
// opposite directions less than
if (cmp(this.semver, '<', comp.semver, options) &&
this.operator.startsWith('>') && comp.operator.startsWith('<')) {
return true
}
// opposite directions greater than
if (cmp(this.semver, '>', comp.semver, options) &&
this.operator.startsWith('<') && comp.operator.startsWith('>')) {
return true
}
return false
}
}
module.exports = Comparator
const parseOptions = __nccwpck_require__(40785)
const { safeRe: re, t } = __nccwpck_require__(9523)
const cmp = __nccwpck_require__(75098)
const debug = __nccwpck_require__(50427)
const SemVer = __nccwpck_require__(48088)
const Range = __nccwpck_require__(9828)
/***/ }),
/***/ 9828:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First reduce all whitespace as much as possible so we do not have to rely
// on potentially slow regexes like \s*. This is then stored and used for
// future error messages as well.
this.raw = range
.trim()
.split(/\s+/)
.join(' ')
// First, split on ||
this.set = this.raw
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0) {
this.set = [first]
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.format()
}
format () {
this.range = this.set
.map((comps) => comps.join(' ').trim())
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts =
(this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
(this.options.loose && FLAG_LOOSE)
const memoKey = memoOpts + ':' + range
const cached = cache.get(memoKey)
if (cached) {
return cached
}
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range)
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
debug('tilde trim', range)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
debug('caret trim', range)
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options)
return !!comp.match(re[t.COMPARATORLOOSE])
})
}
debug('range list', rangeList)
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map()
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp]
}
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('')
}
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = __nccwpck_require__(81196)
const cache = new LRU({ max: 1000 })
const parseOptions = __nccwpck_require__(40785)
const Comparator = __nccwpck_require__(91532)
const debug = __nccwpck_require__(50427)
const SemVer = __nccwpck_require__(48088)
const {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = __nccwpck_require__(9523)
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(42293)
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceTilde(c, options))
.join(' ')
}
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceCaret(c, options))
.join(' ')
}
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp
.split(/\s+/)
.map((c) => replaceXRange(c, options))
.join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<') {
pr = '-0'
}
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp
.trim()
.replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp
.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return `${from} ${to}`.trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}
/***/ }),
/***/ 48088:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const debug = __nccwpck_require__(50427)
const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(42293)
const { safeRe: re, t } = __nccwpck_require__(9523)
const parseOptions = __nccwpck_require__(40785)
const { compareIdentifiers } = __nccwpck_require__(92463)
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier, identifierBase) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier, identifierBase)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier, identifierBase)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier, identifierBase)
this.inc('pre', identifier, identifierBase)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier, identifierBase)
}
this.inc('pre', identifier, identifierBase)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre': {
const base = Number(identifierBase) ? 1 : 0
if (!identifier && identifierBase === false) {
throw new Error('invalid increment argument: identifier is empty')
}
if (this.prerelease.length === 0) {
this.prerelease = [base]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
if (identifier === this.prerelease.join('.') && identifierBase === false) {
throw new Error('invalid increment argument: identifier already exists')
}
this.prerelease.push(base)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
let prerelease = [identifier, base]
if (identifierBase === false) {
prerelease = [identifier]
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease
}
} else {
this.prerelease = prerelease
}
}
break
}
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.raw = this.format()
if (this.build.length) {
this.raw += `+${this.build.join('.')}`
}
return this
}
}
module.exports = SemVer
/***/ }),
/***/ 48848:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const parse = __nccwpck_require__(75925)
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean
/***/ }),
/***/ 75098:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const eq = __nccwpck_require__(91898)
const neq = __nccwpck_require__(6017)
const gt = __nccwpck_require__(84123)
const gte = __nccwpck_require__(15522)
const lt = __nccwpck_require__(80194)
const lte = __nccwpck_require__(77520)
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a === b
case '!==':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp
/***/ }),
/***/ 13466:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const parse = __nccwpck_require__(75925)
const { safeRe: re, t } = __nccwpck_require__(9523)
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
// With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
let next
while ((next = coerceRtlRegex.exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
coerceRtlRegex.lastIndex = -1
}
if (match === null) {
return null
}
const major = match[2]
const minor = match[3] || '0'
const patch = match[4] || '0'
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
module.exports = coerce
/***/ }),
/***/ 92156:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild
/***/ }),
/***/ 62804:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose
/***/ }),
/***/ 44309:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare
/***/ }),
/***/ 64297:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const parse = __nccwpck_require__(75925)
const diff = (version1, version2) => {
const v1 = parse(version1, null, true)
const v2 = parse(version2, null, true)
const comparison = v1.compare(v2)
if (comparison === 0) {
return null
}
const v1Higher = comparison > 0
const highVersion = v1Higher ? v1 : v2
const lowVersion = v1Higher ? v2 : v1
const highHasPre = !!highVersion.prerelease.length
const lowHasPre = !!lowVersion.prerelease.length
if (lowHasPre && !highHasPre) {
// Going from prerelease -> no prerelease requires some special casing
// If the low version has only a major, then it will always be a major
// Some examples:
// 1.0.0-1 -> 1.0.0
// 1.0.0-1 -> 1.1.1
// 1.0.0-1 -> 2.0.0
if (!lowVersion.patch && !lowVersion.minor) {
return 'major'
}
// Otherwise it can be determined by checking the high version
if (highVersion.patch) {
// anything higher than a patch bump would result in the wrong version
return 'patch'
}
if (highVersion.minor) {
// anything higher than a minor bump would result in the wrong version
return 'minor'
}
// bumping major/minor/patch all have same result
return 'major'
}
// add the `pre` prefix if we are going to a prerelease version
const prefix = highHasPre ? 'pre' : ''
if (v1.major !== v2.major) {
return prefix + 'major'
}
if (v1.minor !== v2.minor) {
return prefix + 'minor'
}
if (v1.patch !== v2.patch) {
return prefix + 'patch'
}
// high and low are preleases
return 'prerelease'
}
module.exports = diff
/***/ }),
/***/ 91898:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
/***/ }),
/***/ 84123:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt
/***/ }),
/***/ 15522:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte
/***/ }),
/***/ 30900:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const inc = (version, release, options, identifier, identifierBase) => {
if (typeof (options) === 'string') {
identifierBase = identifier
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier, identifierBase).version
} catch (er) {
return null
}
}
module.exports = inc
/***/ }),
/***/ 80194:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt
/***/ }),
/***/ 77520:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte
/***/ }),
/***/ 76688:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major
/***/ }),
/***/ 38447:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor
/***/ }),
/***/ 6017:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq
/***/ }),
/***/ 75925:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const parse = (version, options, throwErrors = false) => {
if (version instanceof SemVer) {
return version
}
try {
return new SemVer(version, options)
} catch (er) {
if (!throwErrors) {
return null
}
throw er
}
}
module.exports = parse
/***/ }),
/***/ 42866:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
/***/ }),
/***/ 24016:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const parse = __nccwpck_require__(75925)
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease
/***/ }),
/***/ 76417:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compare = __nccwpck_require__(44309)
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare
/***/ }),
/***/ 8701:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compareBuild = __nccwpck_require__(92156)
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort
/***/ }),
/***/ 6055:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const Range = __nccwpck_require__(9828)
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies
/***/ }),
/***/ 61426:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const compareBuild = __nccwpck_require__(92156)
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort
/***/ }),
/***/ 19601:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const parse = __nccwpck_require__(75925)
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid
/***/ }),
/***/ 11383:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
// just pre-load all the stuff that index.js lazily exports
const internalRe = __nccwpck_require__(9523)
const constants = __nccwpck_require__(42293)
const SemVer = __nccwpck_require__(48088)
const identifiers = __nccwpck_require__(92463)
const parse = __nccwpck_require__(75925)
const valid = __nccwpck_require__(19601)
const clean = __nccwpck_require__(48848)
const inc = __nccwpck_require__(30900)
const diff = __nccwpck_require__(64297)
const major = __nccwpck_require__(76688)
const minor = __nccwpck_require__(38447)
const patch = __nccwpck_require__(42866)
const prerelease = __nccwpck_require__(24016)
const compare = __nccwpck_require__(44309)
const rcompare = __nccwpck_require__(76417)
const compareLoose = __nccwpck_require__(62804)
const compareBuild = __nccwpck_require__(92156)
const sort = __nccwpck_require__(61426)
const rsort = __nccwpck_require__(8701)
const gt = __nccwpck_require__(84123)
const lt = __nccwpck_require__(80194)
const eq = __nccwpck_require__(91898)
const neq = __nccwpck_require__(6017)
const gte = __nccwpck_require__(15522)
const lte = __nccwpck_require__(77520)
const cmp = __nccwpck_require__(75098)
const coerce = __nccwpck_require__(13466)
const Comparator = __nccwpck_require__(91532)
const Range = __nccwpck_require__(9828)
const satisfies = __nccwpck_require__(6055)
const toComparators = __nccwpck_require__(52706)
const maxSatisfying = __nccwpck_require__(20579)
const minSatisfying = __nccwpck_require__(10832)
const minVersion = __nccwpck_require__(34179)
const validRange = __nccwpck_require__(2098)
const outside = __nccwpck_require__(60420)
const gtr = __nccwpck_require__(9380)
const ltr = __nccwpck_require__(33323)
const intersects = __nccwpck_require__(27008)
const simplifyRange = __nccwpck_require__(75297)
const subset = __nccwpck_require__(7863)
module.exports = {
parse,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
}
/***/ }),
/***/ 42293:
/***/ ((module) => {
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
const RELEASE_TYPES = [
'major',
'premajor',
'minor',
'preminor',
'patch',
'prepatch',
'prerelease',
]
module.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 0b001,
FLAG_LOOSE: 0b010,
}
/***/ }),
/***/ 50427:
/***/ ((module) => {
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug
/***/ }),
/***/ 92463:
/***/ ((module) => {
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}
/***/ }),
/***/ 40785:
/***/ ((module) => {
// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
if (!options) {
return emptyOpts
}
if (typeof options !== 'object') {
return looseOption
}
return options
}
module.exports = parseOptions
/***/ }),
/***/ 9523:
/***/ ((module, exports, __nccwpck_require__) => {
const {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH,
} = __nccwpck_require__(42293)
const debug = __nccwpck_require__(50427)
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const t = exports.t = {}
let R = 0
const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
['\\s', 1],
['\\d', MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]
const makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value
.split(`${token}*`).join(`${token}{0,${max}}`)
.split(`${token}+`).join(`${token}{1,${max}}`)
}
return value
}
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value)
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
}|${src[t.NONNUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
}|${src[t.NONNUMERICIDENTIFIER]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
`(?:${src[t.PRERELEASE]})?` +
`(?:${src[t.BUILD]})?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
/***/ }),
/***/ 81196:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// A linked list to keep track of recently-used-ness
const Yallist = __nccwpck_require__(70220)
const MAX = Symbol('max')
const LENGTH = Symbol('length')
const LENGTH_CALCULATOR = Symbol('lengthCalculator')
const ALLOW_STALE = Symbol('allowStale')
const MAX_AGE = Symbol('maxAge')
const DISPOSE = Symbol('dispose')
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
const LRU_LIST = Symbol('lruList')
const CACHE = Symbol('cache')
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
const naiveLength = () => 1
// lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
class LRUCache {
constructor (options) {
if (typeof options === 'number')
options = { max: options }
if (!options)
options = {}
if (options.max && (typeof options.max !== 'number' || options.max < 0))
throw new TypeError('max must be a non-negative number')
// Kind of weird to have a default max of Infinity, but oh well.
const max = this[MAX] = options.max || Infinity
const lc = options.length || naiveLength
this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
this[ALLOW_STALE] = options.stale || false
if (options.maxAge && typeof options.maxAge !== 'number')
throw new TypeError('maxAge must be a number')
this[MAX_AGE] = options.maxAge || 0
this[DISPOSE] = options.dispose
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
this.reset()
}
// resize the cache when the max changes.
set max (mL) {
if (typeof mL !== 'number' || mL < 0)
throw new TypeError('max must be a non-negative number')
this[MAX] = mL || Infinity
trim(this)
}
get max () {
return this[MAX]
}
set allowStale (allowStale) {
this[ALLOW_STALE] = !!allowStale
}
get allowStale () {
return this[ALLOW_STALE]
}
set maxAge (mA) {
if (typeof mA !== 'number')
throw new TypeError('maxAge must be a non-negative number')
this[MAX_AGE] = mA
trim(this)
}
get maxAge () {
return this[MAX_AGE]
}
// resize the cache when the lengthCalculator changes.
set lengthCalculator (lC) {
if (typeof lC !== 'function')
lC = naiveLength
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC
this[LENGTH] = 0
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
this[LENGTH] += hit.length
})
}
trim(this)
}
get lengthCalculator () { return this[LENGTH_CALCULATOR] }
get length () { return this[LENGTH] }
get itemCount () { return this[LRU_LIST].length }
rforEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev
forEachStep(this, fn, walker, thisp)
walker = prev
}
}
forEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next
forEachStep(this, fn, walker, thisp)
walker = next
}
}
keys () {
return this[LRU_LIST].toArray().map(k => k.key)
}
values () {
return this[LRU_LIST].toArray().map(k => k.value)
}
reset () {
if (this[DISPOSE] &&
this[LRU_LIST] &&
this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
}
this[CACHE] = new Map() // hash of items by key
this[LRU_LIST] = new Yallist() // list of items in order of use recency
this[LENGTH] = 0 // length of items in the list
}
dump () {
return this[LRU_LIST].map(hit =>
isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h)
}
dumpLru () {
return this[LRU_LIST]
}
set (key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE]
if (maxAge && typeof maxAge !== 'number')
throw new TypeError('maxAge must be a number')
const now = maxAge ? Date.now() : 0
const len = this[LENGTH_CALCULATOR](value, key)
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key))
return false
}
const node = this[CACHE].get(key)
const item = node.value
// dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET])
this[DISPOSE](key, item.value)
}
item.now = now
item.maxAge = maxAge
item.value = value
this[LENGTH] += len - item.length
item.length = len
this.get(key)
trim(this)
return true
}
const hit = new Entry(key, value, len, now, maxAge)
// oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE])
this[DISPOSE](key, value)
return false
}
this[LENGTH] += hit.length
this[LRU_LIST].unshift(hit)
this[CACHE].set(key, this[LRU_LIST].head)
trim(this)
return true
}
has (key) {
if (!this[CACHE].has(key)) return false
const hit = this[CACHE].get(key).value
return !isStale(this, hit)
}
get (key) {
return get(this, key, true)
}
peek (key) {
return get(this, key, false)
}
pop () {
const node = this[LRU_LIST].tail
if (!node)
return null
del(this, node)
return node.value
}
del (key) {
del(this, this[CACHE].get(key))
}
load (arr) {
// reset the cache
this.reset()
const now = Date.now()
// A previous serialized cache has the most recent items first
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l]
const expiresAt = hit.e || 0
if (expiresAt === 0)
// the item was created without expiration in a non aged cache
this.set(hit.k, hit.v)
else {
const maxAge = expiresAt - now
// dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge)
}
}
}
}
prune () {
this[CACHE].forEach((value, key) => get(this, key, false))
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key)
if (node) {
const hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
return undefined
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET])
node.value.now = Date.now()
self[LRU_LIST].unshiftNode(node)
}
}
return hit.value
}
}
const isStale = (self, hit) => {
if (!hit || (!hit.maxAge && !self[MAX_AGE]))
return false
const diff = Date.now() - hit.now
return hit.maxAge ? diff > hit.maxAge
: self[MAX_AGE] && (diff > self[MAX_AGE])
}
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail;
self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
const prev = walker.prev
del(self, walker)
walker = prev
}
}
}
const del = (self, node) => {
if (node) {
const hit = node.value
if (self[DISPOSE])
self[DISPOSE](hit.key, hit.value)
self[LENGTH] -= hit.length
self[CACHE].delete(hit.key)
self[LRU_LIST].removeNode(node)
}
}
class Entry {
constructor (key, value, length, now, maxAge) {
this.key = key
this.value = value
this.length = length
this.now = now
this.maxAge = maxAge || 0
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
hit = undefined
}
if (hit)
fn.call(thisp, hit.value, hit.key, self)
}
module.exports = LRUCache
/***/ }),
/***/ 45327:
/***/ ((module) => {
"use strict";
module.exports = function (Yallist) {
Yallist.prototype[Symbol.iterator] = function* () {
for (let walker = this.head; walker; walker = walker.next) {
yield walker.value
}
}
}
/***/ }),
/***/ 70220:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports = Yallist
Yallist.Node = Node
Yallist.create = Yallist
function Yallist (list) {
var self = this
if (!(self instanceof Yallist)) {
self = new Yallist()
}
self.tail = null
self.head = null
self.length = 0
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item)
})
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i])
}
}
return self
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list')
}
var next = node.next
var prev = node.prev
if (next) {
next.prev = prev
}
if (prev) {
prev.next = next
}
if (node === this.head) {
this.head = next
}
if (node === this.tail) {
this.tail = prev
}
node.list.length--
node.next = null
node.prev = null
node.list = null
return next
}
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var head = this.head
node.list = this
node.next = head
if (head) {
head.prev = node
}
this.head = node
if (!this.tail) {
this.tail = node
}
this.length++
}
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var tail = this.tail
node.list = this
node.prev = tail
if (tail) {
tail.next = node
}
this.tail = node
if (!this.head) {
this.head = node
}
this.length++
}
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i])
}
return this.length
}
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i])
}
return this.length
}
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined
}
var res = this.tail.value
this.tail = this.tail.prev
if (this.tail) {
this.tail.next = null
} else {
this.head = null
}
this.length--
return res
}
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined
}
var res = this.head.value
this.head = this.head.next
if (this.head) {
this.head.prev = null
} else {
this.tail = null
}
this.length--
return res
}
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this)
walker = walker.next
}
}
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this)
walker = walker.prev
}
}
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.next
}
return res
}
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.prev
}
return res
}
Yallist.prototype.reduce = function (fn, initial) {
var acc
var walker = this.head
if (arguments.length > 1) {
acc = initial
} else if (this.head) {
walker = this.head.next
acc = this.head.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i)
walker = walker.next
}
return acc
}
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc
var walker = this.tail
if (arguments.length > 1) {
acc = initial
} else if (this.tail) {
walker = this.tail.prev
acc = this.tail.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i)
walker = walker.prev
}
return acc
}
Yallist.prototype.toArray = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value
walker = walker.next
}
return arr
}
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value
walker = walker.prev
}
return arr
}
Yallist.prototype.slice = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
if (start > this.length) {
start = this.length - 1
}
if (start < 0) {
start = this.length + start;
}
for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
walker = walker.next
}
var ret = []
for (var i = 0; walker && i < deleteCount; i++) {
ret.push(walker.value)
walker = this.removeNode(walker)
}
if (walker === null) {
walker = this.tail
}
if (walker !== this.head && walker !== this.tail) {
walker = walker.prev
}
for (var i = 0; i < nodes.length; i++) {
walker = insert(this, walker, nodes[i])
}
return ret;
}
Yallist.prototype.reverse = function () {
var head = this.head
var tail = this.tail
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev
walker.prev = walker.next
walker.next = p
}
this.head = tail
this.tail = head
return this
}
function insert (self, node, value) {
var inserted = node === self.head ?
new Node(value, null, node, self) :
new Node(value, node, node.next, self)
if (inserted.next === null) {
self.tail = inserted
}
if (inserted.prev === null) {
self.head = inserted
}
self.length++
return inserted
}
function push (self, item) {
self.tail = new Node(item, self.tail, null, self)
if (!self.head) {
self.head = self.tail
}
self.length++
}
function unshift (self, item) {
self.head = new Node(item, null, self.head, self)
if (!self.tail) {
self.tail = self.head
}
self.length++
}
function Node (value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list)
}
this.list = list
this.value = value
if (prev) {
prev.next = this
this.prev = prev
} else {
this.prev = null
}
if (next) {
next.prev = this
this.next = next
} else {
this.next = null
}
}
try {
// add if support for Symbol.iterator is present
__nccwpck_require__(45327)(Yallist)
} catch (er) {}
/***/ }),
/***/ 9380:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
// Determine if version is greater than all the versions possible in the range.
const outside = __nccwpck_require__(60420)
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr
/***/ }),
/***/ 27008:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const Range = __nccwpck_require__(9828)
const intersects = (r1, r2, options) => {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2, options)
}
module.exports = intersects
/***/ }),
/***/ 33323:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const outside = __nccwpck_require__(60420)
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr
/***/ }),
/***/ 20579:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const Range = __nccwpck_require__(9828)
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying
/***/ }),
/***/ 10832:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const Range = __nccwpck_require__(9828)
const minSatisfying = (versions, range, options) => {
let min = null
let minSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
module.exports = minSatisfying
/***/ }),
/***/ 34179:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const Range = __nccwpck_require__(9828)
const gt = __nccwpck_require__(84123)
const minVersion = (range, loose) => {
range = new Range(range, loose)
let minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let setMin = null
comparators.forEach((comparator) => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!setMin || gt(compver, setMin)) {
setMin = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`)
}
})
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin
}
}
if (minver && range.test(minver)) {
return minver
}
return null
}
module.exports = minVersion
/***/ }),
/***/ 60420:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const SemVer = __nccwpck_require__(48088)
const Comparator = __nccwpck_require__(91532)
const { ANY } = Comparator
const Range = __nccwpck_require__(9828)
const satisfies = __nccwpck_require__(6055)
const gt = __nccwpck_require__(84123)
const lt = __nccwpck_require__(80194)
const lte = __nccwpck_require__(77520)
const gte = __nccwpck_require__(15522)
const outside = (version, range, hilo, options) => {
version = new SemVer(version, options)
range = new Range(range, options)
let gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisfies the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let high = null
let low = null
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
module.exports = outside
/***/ }),
/***/ 75297:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = __nccwpck_require__(6055)
const compare = __nccwpck_require__(44309)
module.exports = (versions, range, options) => {
const set = []
let first = null
let prev = null
const v = versions.sort((a, b) => compare(a, b, options))
for (const version of v) {
const included = satisfies(version, range, options)
if (included) {
prev = version
if (!first) {
first = version
}
} else {
if (prev) {
set.push([first, prev])
}
prev = null
first = null
}
}
if (first) {
set.push([first, null])
}
const ranges = []
for (const [min, max] of set) {
if (min === max) {
ranges.push(min)
} else if (!max && min === v[0]) {
ranges.push('*')
} else if (!max) {
ranges.push(`>=${min}`)
} else if (min === v[0]) {
ranges.push(`<=${max}`)
} else {
ranges.push(`${min} - ${max}`)
}
}
const simplified = ranges.join(' || ')
const original = typeof range.raw === 'string' ? range.raw : String(range)
return simplified.length < original.length ? simplified : range
}
/***/ }),
/***/ 7863:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const Range = __nccwpck_require__(9828)
const Comparator = __nccwpck_require__(91532)
const { ANY } = Comparator
const satisfies = __nccwpck_require__(6055)
const compare = __nccwpck_require__(44309)
// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
// some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else if in prerelease mode, return false
// - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
// - if in prerelease mode, return true
// - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT.semver is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
// - If LT.semver is greater than any < or <= comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true
const subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true
}
sub = new Range(sub, options)
dom = new Range(dom, options)
let sawNonNull = false
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options)
sawNonNull = sawNonNull || isSub !== null
if (isSub) {
continue OUTER
}
}
// the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull) {
return false
}
}
return true
}
const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]
const simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true
} else if (options.includePrerelease) {
sub = minimumVersionWithPreRelease
} else {
sub = minimumVersion
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true
} else {
dom = minimumVersion
}
}
const eqSet = new Set()
let gt, lt
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') {
gt = higherGT(gt, c, options)
} else if (c.operator === '<' || c.operator === '<=') {
lt = lowerLT(lt, c, options)
} else {
eqSet.add(c.semver)
}
}
if (eqSet.size > 1) {
return null
}
let gtltComp
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options)
if (gtltComp > 0) {
return null
} else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
return null
}
}
// will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) {
return null
}
if (lt && !satisfies(eq, String(lt), options)) {
return null
}
for (const c of dom) {
if (!satisfies(eq, String(c), options)) {
return false
}
}
return true
}
let higher, lower
let hasDomLT, hasDomGT
// if the subset has a prerelease, we need a comparator in the superset
// with the same tuple and a prerelease, or it's not a subset
let needDomLTPre = lt &&
!options.includePrerelease &&
lt.semver.prerelease.length ? lt.semver : false
let needDomGTPre = gt &&
!options.includePrerelease &&
gt.semver.prerelease.length ? gt.semver : false
// exception: <1.2.3-0 is the same as <1.2.3
if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomGTPre.major &&
c.semver.minor === needDomGTPre.minor &&
c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options)
if (higher === c && higher !== gt) {
return false
}
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
return false
}
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomLTPre.major &&
c.semver.minor === needDomLTPre.minor &&
c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options)
if (lower === c && lower !== lt) {
return false
}
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
return false
}
}
if (!c.operator && (lt || gt) && gtltComp !== 0) {
return false
}
}
// if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false
}
// we needed a prerelease range in a specific tuple, but didn't get one
// then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
// because it includes prereleases in the 1.2.3 tuple
if (needDomGTPre || needDomLTPre) {
return false
}
return true
}
// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp > 0 ? a
: comp < 0 ? b
: b.operator === '>' && a.operator === '>=' ? b
: a
}
// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp < 0 ? a
: comp > 0 ? b
: b.operator === '<' && a.operator === '<=' ? b
: a
}
module.exports = subset
/***/ }),
/***/ 52706:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const Range = __nccwpck_require__(9828)
// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
new Range(range, options).set
.map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
module.exports = toComparators
/***/ }),
/***/ 2098:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const Range = __nccwpck_require__(9828)
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
module.exports = validRange
/***/ }),
/***/ 37303:
/***/ ((module) => {
"use strict";
var defaultParseOptions = {
decodeValues: true,
map: false,
silent: false,
};
function isNonEmptyString(str) {
return typeof str === "string" && !!str.trim();
}
function parseString(setCookieValue, options) {
var parts = setCookieValue.split(";").filter(isNonEmptyString);
var nameValuePairStr = parts.shift();
var parsed = parseNameValuePair(nameValuePairStr);
var name = parsed.name;
var value = parsed.value;
options = options
? Object.assign({}, defaultParseOptions, options)
: defaultParseOptions;
try {
value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
} catch (e) {
console.error(
"set-cookie-parser encountered an error while decoding a cookie with value '" +
value +
"'. Set options.decodeValues to false to disable this feature.",
e
);
}
var cookie = {
name: name,
value: value,
};
parts.forEach(function (part) {
var sides = part.split("=");
var key = sides.shift().trimLeft().toLowerCase();
var value = sides.join("=");
if (key === "expires") {
cookie.expires = new Date(value);
} else if (key === "max-age") {
cookie.maxAge = parseInt(value, 10);
} else if (key === "secure") {
cookie.secure = true;
} else if (key === "httponly") {
cookie.httpOnly = true;
} else if (key === "samesite") {
cookie.sameSite = value;
} else {
cookie[key] = value;
}
});
return cookie;
}
function parseNameValuePair(nameValuePairStr) {
// Parses name-value-pair according to rfc6265bis draft
var name = "";
var value = "";
var nameValueArr = nameValuePairStr.split("=");
if (nameValueArr.length > 1) {
name = nameValueArr.shift();
value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part
} else {
value = nameValuePairStr;
}
return { name: name, value: value };
}
function parse(input, options) {
options = options
? Object.assign({}, defaultParseOptions, options)
: defaultParseOptions;
if (!input) {
if (!options.map) {
return [];
} else {
return {};
}
}
if (input.headers) {
if (typeof input.headers.getSetCookie === "function") {
// for fetch responses - they combine headers of the same type in the headers array,
// but getSetCookie returns an uncombined array
input = input.headers.getSetCookie();
} else if (input.headers["set-cookie"]) {
// fast-path for node.js (which automatically normalizes header names to lower-case
input = input.headers["set-cookie"];
} else {
// slow-path for other environments - see #25
var sch =
input.headers[
Object.keys(input.headers).find(function (key) {
return key.toLowerCase() === "set-cookie";
})
];
// warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
if (!sch && input.headers.cookie && !options.silent) {
console.warn(
"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
);
}
input = sch;
}
}
if (!Array.isArray(input)) {
input = [input];
}
options = options
? Object.assign({}, defaultParseOptions, options)
: defaultParseOptions;
if (!options.map) {
return input.filter(isNonEmptyString).map(function (str) {
return parseString(str, options);
});
} else {
var cookies = {};
return input.filter(isNonEmptyString).reduce(function (cookies, str) {
var cookie = parseString(str, options);
cookies[cookie.name] = cookie;
return cookies;
}, cookies);
}
}
/*
Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
that are within a single set-cookie field-value, such as in the Expires portion.
This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
React Native's fetch does this for *every* header, including set-cookie.
Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/
function splitCookiesString(cookiesString) {
if (Array.isArray(cookiesString)) {
return cookiesString;
}
if (typeof cookiesString !== "string") {
return [];
}
var cookiesStrings = [];
var pos = 0;
var start;
var ch;
var lastComma;
var nextStart;
var cookiesSeparatorFound;
function skipWhitespace() {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
}
function notSpecialChar() {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
}
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.substring(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
}
}
return cookiesStrings;
}
module.exports = parse;
module.exports.parse = parse;
module.exports.parseString = parseString;
module.exports.splitCookiesString = splitCookiesString;
/***/ }),
/***/ 12890:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var Promise = __nccwpck_require__(55768)
module.exports = function (stream, done) {
if (!stream) {
// no arguments, meaning stream = this
stream = this
} else if (typeof stream === 'function') {
// stream = this, callback passed
done = stream
stream = this
}
var deferred
if (!stream.readable) deferred = Promise.resolve([])
else deferred = new Promise(function (resolve, reject) {
// stream is already ended
if (!stream.readable) return resolve([])
var arr = []
stream.on('data', onData)
stream.on('end', onEnd)
stream.on('error', onEnd)
stream.on('close', onClose)
function onData(doc) {
arr.push(doc)
}
function onEnd(err) {
if (err) reject(err)
else resolve(arr)
cleanup()
}
function onClose() {
resolve(arr)
cleanup()
}
function cleanup() {
arr = null
stream.removeListener('data', onData)
stream.removeListener('end', onEnd)
stream.removeListener('error', onEnd)
stream.removeListener('close', onClose)
}
})
if (typeof done === 'function') {
deferred.then(function (arr) {
process.nextTick(function() {
done(null, arr)
})
}, done)
}
return deferred
}
/***/ }),
/***/ 92111:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const toArray = __nccwpck_require__(12890)
const Promise = __nccwpck_require__(55768)
const onEnd = __nccwpck_require__(81205)
module.exports = streamToPromise
async function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
}
async function fromReadable (stream) {
const promise = toArray(stream)
// Ensure stream is in flowing mode
if (stream.resume) stream.resume()
const parts = await promise
if (stream._readableState && stream._readableState.objectMode) {
return parts
}
return Buffer.concat(parts.map(bufferize))
}
async function fromWritable (stream) {
return new Promise(function (resolve, reject) {
onEnd(stream, function (err) {
(err ? reject : resolve)(err)
})
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
}
/***/ }),
/***/ 59318:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const os = __nccwpck_require__(22037);
const tty = __nccwpck_require__(76224);
const hasFlag = __nccwpck_require__(31621);
const {env} = process;
let forceColor;
if (hasFlag('no-color') ||
hasFlag('no-colors') ||
hasFlag('color=false') ||
hasFlag('color=never')) {
forceColor = 0;
} else if (hasFlag('color') ||
hasFlag('colors') ||
hasFlag('color=true') ||
hasFlag('color=always')) {
forceColor = 1;
}
if ('FORCE_COLOR' in env) {
if (env.FORCE_COLOR === 'true') {
forceColor = 1;
} else if (env.FORCE_COLOR === 'false') {
forceColor = 0;
} else {
forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor(haveStream, streamIsTTY) {
if (forceColor === 0) {
return 0;
}
if (hasFlag('color=16m') ||
hasFlag('color=full') ||
hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === 'dumb') {
return min;
}
if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(osRelease[0]) >= 10 &&
Number(osRelease[2]) >= 10586
) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === 'truecolor') {
return 3;
}
if ('TERM_PROGRAM' in env) {
const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
return min;
}
function getSupportLevel(stream) {
const level = supportsColor(stream, stream && stream.isTTY);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: translateLevel(supportsColor(true, tty.isatty(1))),
stderr: translateLevel(supportsColor(true, tty.isatty(2)))
};
/***/ }),
/***/ 78366:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { version } = __nccwpck_require__(82954)
const { EventEmitter } = __nccwpck_require__(82361)
const { Worker } = __nccwpck_require__(71267)
const { join } = __nccwpck_require__(71017)
const { pathToFileURL } = __nccwpck_require__(57310)
const { wait } = __nccwpck_require__(33916)
const {
WRITE_INDEX,
READ_INDEX
} = __nccwpck_require__(4212)
const buffer = __nccwpck_require__(14300)
const assert = __nccwpck_require__(39491)
const kImpl = Symbol('kImpl')
// V8 limit for string size
const MAX_STRING = buffer.constants.MAX_STRING_LENGTH
class FakeWeakRef {
constructor (value) {
this._value = value
}
deref () {
return this._value
}
}
class FakeFinalizationRegistry {
register () {}
unregister () {}
}
// Currently using FinalizationRegistry with code coverage breaks the world
// Ref: https://github.com/nodejs/node/issues/49344
const FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry
const WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef
const registry = new FinalizationRegistry((worker) => {
if (worker.exited) {
return
}
worker.terminate()
})
function createWorker (stream, opts) {
const { filename, workerData } = opts
const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}
const toExecute = bundlerOverrides['thread-stream-worker'] || __nccwpck_require__.ab + "worker1.js"
const worker = new Worker(toExecute, {
...opts.workerOpts,
trackUnmanagedFds: false,
workerData: {
filename: filename.indexOf('file://') === 0
? filename
: pathToFileURL(filename).href,
dataBuf: stream[kImpl].dataBuf,
stateBuf: stream[kImpl].stateBuf,
workerData: {
$context: {
threadStreamVersion: version
},
...workerData
}
}
})
// We keep a strong reference for now,
// we need to start writing first
worker.stream = new FakeWeakRef(stream)
worker.on('message', onWorkerMessage)
worker.on('exit', onWorkerExit)
registry.register(stream, worker)
return worker
}
function drain (stream) {
assert(!stream[kImpl].sync)
if (stream[kImpl].needDrain) {
stream[kImpl].needDrain = false
stream.emit('drain')
}
}
function nextFlush (stream) {
const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)
let leftover = stream[kImpl].data.length - writeIndex
if (leftover > 0) {
if (stream[kImpl].buf.length === 0) {
stream[kImpl].flushing = false
if (stream[kImpl].ending) {
end(stream)
} else if (stream[kImpl].needDrain) {
process.nextTick(drain, stream)
}
return
}
let toWrite = stream[kImpl].buf.slice(0, leftover)
let toWriteBytes = Buffer.byteLength(toWrite)
if (toWriteBytes <= leftover) {
stream[kImpl].buf = stream[kImpl].buf.slice(leftover)
// process._rawDebug('writing ' + toWrite.length)
write(stream, toWrite, nextFlush.bind(null, stream))
} else {
// multi-byte utf-8
stream.flush(() => {
// err is already handled in flush()
if (stream.destroyed) {
return
}
Atomics.store(stream[kImpl].state, READ_INDEX, 0)
Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)
// Find a toWrite length that fits the buffer
// it must exists as the buffer is at least 4 bytes length
// and the max utf-8 length for a char is 4 bytes.
while (toWriteBytes > stream[kImpl].data.length) {
leftover = leftover / 2
toWrite = stream[kImpl].buf.slice(0, leftover)
toWriteBytes = Buffer.byteLength(toWrite)
}
stream[kImpl].buf = stream[kImpl].buf.slice(leftover)
write(stream, toWrite, nextFlush.bind(null, stream))
})
}
} else if (leftover === 0) {
if (writeIndex === 0 && stream[kImpl].buf.length === 0) {
// we had a flushSync in the meanwhile
return
}
stream.flush(() => {
Atomics.store(stream[kImpl].state, READ_INDEX, 0)
Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)
nextFlush(stream)
})
} else {
// This should never happen
destroy(stream, new Error('overwritten'))
}
}
function onWorkerMessage (msg) {
const stream = this.stream.deref()
if (stream === undefined) {
this.exited = true
// Terminate the worker.
this.terminate()
return
}
switch (msg.code) {
case 'READY':
// Replace the FakeWeakRef with a
// proper one.
this.stream = new WeakRef(stream)
stream.flush(() => {
stream[kImpl].ready = true
stream.emit('ready')
})
break
case 'ERROR':
destroy(stream, msg.err)
break
case 'EVENT':
if (Array.isArray(msg.args)) {
stream.emit(msg.name, ...msg.args)
} else {
stream.emit(msg.name, msg.args)
}
break
case 'WARNING':
process.emitWarning(msg.err)
break
default:
destroy(stream, new Error('this should not happen: ' + msg.code))
}
}
function onWorkerExit (code) {
const stream = this.stream.deref()
if (stream === undefined) {
// Nothing to do, the worker already exit
return
}
registry.unregister(stream)
stream.worker.exited = true
stream.worker.off('exit', onWorkerExit)
destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)
}
class ThreadStream extends EventEmitter {
constructor (opts = {}) {
super()
if (opts.bufferSize < 4) {
throw new Error('bufferSize must at least fit a 4-byte utf-8 char')
}
this[kImpl] = {}
this[kImpl].stateBuf = new SharedArrayBuffer(128)
this[kImpl].state = new Int32Array(this[kImpl].stateBuf)
this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)
this[kImpl].data = Buffer.from(this[kImpl].dataBuf)
this[kImpl].sync = opts.sync || false
this[kImpl].ending = false
this[kImpl].ended = false
this[kImpl].needDrain = false
this[kImpl].destroyed = false
this[kImpl].flushing = false
this[kImpl].ready = false
this[kImpl].finished = false
this[kImpl].errored = null
this[kImpl].closed = false
this[kImpl].buf = ''
// TODO (fix): Make private?
this.worker = createWorker(this, opts) // TODO (fix): make private
this.on('message', (message, transferList) => {
this.worker.postMessage(message, transferList)
})
}
write (data) {
if (this[kImpl].destroyed) {
error(this, new Error('the worker has exited'))
return false
}
if (this[kImpl].ending) {
error(this, new Error('the worker is ending'))
return false
}
if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {
try {
writeSync(this)
this[kImpl].flushing = true
} catch (err) {
destroy(this, err)
return false
}
}
this[kImpl].buf += data
if (this[kImpl].sync) {
try {
writeSync(this)
return true
} catch (err) {
destroy(this, err)
return false
}
}
if (!this[kImpl].flushing) {
this[kImpl].flushing = true
setImmediate(nextFlush, this)
}
this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0
return !this[kImpl].needDrain
}
end () {
if (this[kImpl].destroyed) {
return
}
this[kImpl].ending = true
end(this)
}
flush (cb) {
if (this[kImpl].destroyed) {
if (typeof cb === 'function') {
process.nextTick(cb, new Error('the worker has exited'))
}
return
}
// TODO write all .buf
const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)
// process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)
wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {
if (err) {
destroy(this, err)
process.nextTick(cb, err)
return
}
if (res === 'not-equal') {
// TODO handle deadlock
this.flush(cb)
return
}
process.nextTick(cb)
})
}
flushSync () {
if (this[kImpl].destroyed) {
return
}
writeSync(this)
flushSync(this)
}
unref () {
this.worker.unref()
}
ref () {
this.worker.ref()
}
get ready () {
return this[kImpl].ready
}
get destroyed () {
return this[kImpl].destroyed
}
get closed () {
return this[kImpl].closed
}
get writable () {
return !this[kImpl].destroyed && !this[kImpl].ending
}
get writableEnded () {
return this[kImpl].ending
}
get writableFinished () {
return this[kImpl].finished
}
get writableNeedDrain () {
return this[kImpl].needDrain
}
get writableObjectMode () {
return false
}
get writableErrored () {
return this[kImpl].errored
}
}
function error (stream, err) {
setImmediate(() => {
stream.emit('error', err)
})
}
function destroy (stream, err) {
if (stream[kImpl].destroyed) {
return
}
stream[kImpl].destroyed = true
if (err) {
stream[kImpl].errored = err
error(stream, err)
}
if (!stream.worker.exited) {
stream.worker.terminate()
.catch(() => {})
.then(() => {
stream[kImpl].closed = true
stream.emit('close')
})
} else {
setImmediate(() => {
stream[kImpl].closed = true
stream.emit('close')
})
}
}
function write (stream, data, cb) {
// data is smaller than the shared buffer length
const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)
const length = Buffer.byteLength(data)
stream[kImpl].data.write(data, current)
Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)
Atomics.notify(stream[kImpl].state, WRITE_INDEX)
cb()
return true
}
function end (stream) {
if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {
return
}
stream[kImpl].ended = true
try {
stream.flushSync()
let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)
// process._rawDebug('writing index')
Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)
// process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)
Atomics.notify(stream[kImpl].state, WRITE_INDEX)
// Wait for the process to complete
let spins = 0
while (readIndex !== -1) {
// process._rawDebug(`read = ${read}`)
Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)
readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)
if (readIndex === -2) {
destroy(stream, new Error('end() failed'))
return
}
if (++spins === 10) {
destroy(stream, new Error('end() took too long (10s)'))
return
}
}
process.nextTick(() => {
stream[kImpl].finished = true
stream.emit('finish')
})
} catch (err) {
destroy(stream, err)
}
// process._rawDebug('end finished...')
}
function writeSync (stream) {
const cb = () => {
if (stream[kImpl].ending) {
end(stream)
} else if (stream[kImpl].needDrain) {
process.nextTick(drain, stream)
}
}
stream[kImpl].flushing = false
while (stream[kImpl].buf.length !== 0) {
const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)
let leftover = stream[kImpl].data.length - writeIndex
if (leftover === 0) {
flushSync(stream)
Atomics.store(stream[kImpl].state, READ_INDEX, 0)
Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)
continue
} else if (leftover < 0) {
// stream should never happen
throw new Error('overwritten')
}
let toWrite = stream[kImpl].buf.slice(0, leftover)
let toWriteBytes = Buffer.byteLength(toWrite)
if (toWriteBytes <= leftover) {
stream[kImpl].buf = stream[kImpl].buf.slice(leftover)
// process._rawDebug('writing ' + toWrite.length)
write(stream, toWrite, cb)
} else {
// multi-byte utf-8
flushSync(stream)
Atomics.store(stream[kImpl].state, READ_INDEX, 0)
Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)
// Find a toWrite length that fits the buffer
// it must exists as the buffer is at least 4 bytes length
// and the max utf-8 length for a char is 4 bytes.
while (toWriteBytes > stream[kImpl].buf.length) {
leftover = leftover / 2
toWrite = stream[kImpl].buf.slice(0, leftover)
toWriteBytes = Buffer.byteLength(toWrite)
}
stream[kImpl].buf = stream[kImpl].buf.slice(leftover)
write(stream, toWrite, cb)
}
}
}
function flushSync (stream) {
if (stream[kImpl].flushing) {
throw new Error('unable to flush while flushing')
}
// process._rawDebug('flushSync started')
const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)
let spins = 0
// TODO handle deadlock
while (true) {
const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)
if (readIndex === -2) {
throw Error('_flushSync failed')
}
// process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)
if (readIndex !== writeIndex) {
// TODO stream timeouts for some reason.
Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)
} else {
break
}
if (++spins === 10) {
throw new Error('_flushSync took too long (10s)')
}
}
// process._rawDebug('flushSync finished')
}
module.exports = ThreadStream
/***/ }),
/***/ 4212:
/***/ ((module) => {
"use strict";
const WRITE_INDEX = 4
const READ_INDEX = 8
module.exports = {
WRITE_INDEX,
READ_INDEX
}
/***/ }),
/***/ 33916:
/***/ ((module) => {
"use strict";
const MAX_TIMEOUT = 1000
function wait (state, index, expected, timeout, done) {
const max = Date.now() + timeout
let current = Atomics.load(state, index)
if (current === expected) {
done(null, 'ok')
return
}
let prior = current
const check = (backoff) => {
if (Date.now() > max) {
done(null, 'timed-out')
} else {
setTimeout(() => {
prior = current
current = Atomics.load(state, index)
if (current === prior) {
check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)
} else {
if (current === expected) done(null, 'ok')
else done(null, 'not-equal')
}
}, backoff)
}
}
check(1)
}
// let waitDiffCount = 0
function waitDiff (state, index, expected, timeout, done) {
// const id = waitDiffCount++
// process._rawDebug(`>>> waitDiff ${id}`)
const max = Date.now() + timeout
let current = Atomics.load(state, index)
if (current !== expected) {
done(null, 'ok')
return
}
const check = (backoff) => {
// process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)
// process._rawDebug('' + backoff)
if (Date.now() > max) {
done(null, 'timed-out')
} else {
setTimeout(() => {
current = Atomics.load(state, index)
if (current !== expected) {
done(null, 'ok')
} else {
check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)
}
}, backoff)
}
}
check(1)
}
module.exports = { wait, waitDiff }
/***/ }),
/***/ 74294:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
module.exports = __nccwpck_require__(54219);
/***/ }),
/***/ 54219:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var net = __nccwpck_require__(41808);
var tls = __nccwpck_require__(24404);
var http = __nccwpck_require__(13685);
var https = __nccwpck_require__(95687);
var events = __nccwpck_require__(82361);
var assert = __nccwpck_require__(39491);
var util = __nccwpck_require__(73837);
exports.httpOverHttp = httpOverHttp;
exports.httpsOverHttp = httpsOverHttp;
exports.httpOverHttps = httpOverHttps;
exports.httpsOverHttps = httpsOverHttps;
function httpOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
return agent;
}
function httpsOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function httpOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
return agent;
}
function httpsOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function TunnelingAgent(options) {
var self = this;
self.options = options || {};
self.proxyOptions = self.options.proxy || {};
self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
self.requests = [];
self.sockets = [];
self.on('free', function onFree(socket, host, port, localAddress) {
var options = toOptions(host, port, localAddress);
for (var i = 0, len = self.requests.length; i < len; ++i) {
var pending = self.requests[i];
if (pending.host === options.host && pending.port === options.port) {
// Detect the request to connect same origin server,
// reuse the connection.
self.requests.splice(i, 1);
pending.request.onSocket(socket);
return;
}
}
socket.destroy();
self.removeSocket(socket);
});
}
util.inherits(TunnelingAgent, events.EventEmitter);
TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
var self = this;
var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
if (self.sockets.length >= this.maxSockets) {
// We are over limit so we'll add it to the queue.
self.requests.push(options);
return;
}
// If we are under maxSockets create a new one.
self.createSocket(options, function(socket) {
socket.on('free', onFree);
socket.on('close', onCloseOrRemove);
socket.on('agentRemove', onCloseOrRemove);
req.onSocket(socket);
function onFree() {
self.emit('free', socket, options);
}
function onCloseOrRemove(err) {
self.removeSocket(socket);
socket.removeListener('free', onFree);
socket.removeListener('close', onCloseOrRemove);
socket.removeListener('agentRemove', onCloseOrRemove);
}
});
};
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
var self = this;
var placeholder = {};
self.sockets.push(placeholder);
var connectOptions = mergeOptions({}, self.proxyOptions, {
method: 'CONNECT',
path: options.host + ':' + options.port,
agent: false,
headers: {
host: options.host + ':' + options.port
}
});
if (options.localAddress) {
connectOptions.localAddress = options.localAddress;
}
if (connectOptions.proxyAuth) {
connectOptions.headers = connectOptions.headers || {};
connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
new Buffer(connectOptions.proxyAuth).toString('base64');
}
debug('making CONNECT request');
var connectReq = self.request(connectOptions);
connectReq.useChunkedEncodingByDefault = false; // for v0.6
connectReq.once('response', onResponse); // for v0.6
connectReq.once('upgrade', onUpgrade); // for v0.6
connectReq.once('connect', onConnect); // for v0.7 or later
connectReq.once('error', onError);
connectReq.end();
function onResponse(res) {
// Very hacky. This is necessary to avoid http-parser leaks.
res.upgrade = true;
}
function onUpgrade(res, socket, head) {
// Hacky.
process.nextTick(function() {
onConnect(res, socket, head);
});
}
function onConnect(res, socket, head) {
connectReq.removeAllListeners();
socket.removeAllListeners();
if (res.statusCode !== 200) {
debug('tunneling socket could not be established, statusCode=%d',
res.statusCode);
socket.destroy();
var error = new Error('tunneling socket could not be established, ' +
'statusCode=' + res.statusCode);
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
return;
}
if (head.length > 0) {
debug('got illegal response body from proxy');
socket.destroy();
var error = new Error('got illegal response body from proxy');
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
return;
}
debug('tunneling connection has established');
self.sockets[self.sockets.indexOf(placeholder)] = socket;
return cb(socket);
}
function onError(cause) {
connectReq.removeAllListeners();
debug('tunneling socket could not be established, cause=%s\n',
cause.message, cause.stack);
var error = new Error('tunneling socket could not be established, ' +
'cause=' + cause.message);
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
}
};
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
var pos = this.sockets.indexOf(socket)
if (pos === -1) {
return;
}
this.sockets.splice(pos, 1);
var pending = this.requests.shift();
if (pending) {
// 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(pending, function(socket) {
pending.request.onSocket(socket);
});
}
};
function createSecureSocket(options, cb) {
var self = this;
TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
var hostHeader = options.request.getHeader('host');
var tlsOptions = mergeOptions({}, self.options, {
socket: socket,
servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
});
// 0 is dummy port for v0.6
var secureSocket = tls.connect(0, tlsOptions);
self.sockets[self.sockets.indexOf(socket)] = secureSocket;
cb(secureSocket);
});
}
function toOptions(host, port, localAddress) {
if (typeof host === 'string') { // since v0.10
return {
host: host,
port: port,
localAddress: localAddress
};
}
return host; // for v0.11 or later
}
function mergeOptions(target) {
for (var i = 1, len = arguments.length; i < len; ++i) {
var overrides = arguments[i];
if (typeof overrides === 'object') {
var keys = Object.keys(overrides);
for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
var k = keys[j];
if (overrides[k] !== undefined) {
target[k] = overrides[k];
}
}
}
}
return target;
}
var debug;
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === 'string') {
args[0] = 'TUNNEL: ' + args[0];
} else {
args.unshift('TUNNEL:');
}
console.error.apply(console, args);
}
} else {
debug = function() {};
}
exports.debug = debug; // for test
/***/ }),
/***/ 41773:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Client = __nccwpck_require__(33598)
const Dispatcher = __nccwpck_require__(60412)
const errors = __nccwpck_require__(48045)
const Pool = __nccwpck_require__(4634)
const BalancedPool = __nccwpck_require__(37931)
const Agent = __nccwpck_require__(7890)
const util = __nccwpck_require__(83983)
const { InvalidArgumentError } = errors
const api = __nccwpck_require__(44059)
const buildConnector = __nccwpck_require__(82067)
const MockClient = __nccwpck_require__(58687)
const MockAgent = __nccwpck_require__(66771)
const MockPool = __nccwpck_require__(26193)
const mockErrors = __nccwpck_require__(50888)
const ProxyAgent = __nccwpck_require__(97858)
const RetryHandler = __nccwpck_require__(82286)
const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(21892)
const DecoratorHandler = __nccwpck_require__(46930)
const RedirectHandler = __nccwpck_require__(72860)
const createRedirectInterceptor = __nccwpck_require__(38861)
let hasCrypto
try {
__nccwpck_require__(6113)
hasCrypto = true
} catch {
hasCrypto = false
}
Object.assign(Dispatcher.prototype, api)
module.exports.Dispatcher = Dispatcher
module.exports.Client = Client
module.exports.Pool = Pool
module.exports.BalancedPool = BalancedPool
module.exports.Agent = Agent
module.exports.ProxyAgent = ProxyAgent
module.exports.RetryHandler = RetryHandler
module.exports.DecoratorHandler = DecoratorHandler
module.exports.RedirectHandler = RedirectHandler
module.exports.createRedirectInterceptor = createRedirectInterceptor
module.exports.buildConnector = buildConnector
module.exports.errors = errors
function makeDispatcher (fn) {
return (url, opts, handler) => {
if (typeof opts === 'function') {
handler = opts
opts = null
}
if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
throw new InvalidArgumentError('invalid url')
}
if (opts != null && typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (opts && opts.path != null) {
if (typeof opts.path !== 'string') {
throw new InvalidArgumentError('invalid opts.path')
}
let path = opts.path
if (!opts.path.startsWith('/')) {
path = `/${path}`
}
url = new URL(util.parseOrigin(url).origin + path)
} else {
if (!opts) {
opts = typeof url === 'object' ? url : {}
}
url = util.parseURL(url)
}
const { agent, dispatcher = getGlobalDispatcher() } = opts
if (agent) {
throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
}
return fn.call(dispatcher, {
...opts,
origin: url.origin,
path: url.search ? `${url.pathname}${url.search}` : url.pathname,
method: opts.method || (opts.body ? 'PUT' : 'GET')
}, handler)
}
}
module.exports.setGlobalDispatcher = setGlobalDispatcher
module.exports.getGlobalDispatcher = getGlobalDispatcher
if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
let fetchImpl = null
module.exports.fetch = async function fetch (resource) {
if (!fetchImpl) {
fetchImpl = (__nccwpck_require__(74881).fetch)
}
try {
return await fetchImpl(...arguments)
} catch (err) {
if (typeof err === 'object') {
Error.captureStackTrace(err, this)
}
throw err
}
}
module.exports.Headers = __nccwpck_require__(10554).Headers
module.exports.Response = __nccwpck_require__(27823).Response
module.exports.Request = __nccwpck_require__(48359).Request
module.exports.FormData = __nccwpck_require__(72015).FormData
module.exports.File = __nccwpck_require__(78511).File
module.exports.FileReader = __nccwpck_require__(1446).FileReader
const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(71246)
module.exports.setGlobalOrigin = setGlobalOrigin
module.exports.getGlobalOrigin = getGlobalOrigin
const { CacheStorage } = __nccwpck_require__(37907)
const { kConstruct } = __nccwpck_require__(29174)
// Cache & CacheStorage are tightly coupled with fetch. Even if it may run
// in an older version of Node, it doesn't have any use without fetch.
module.exports.caches = new CacheStorage(kConstruct)
}
if (util.nodeMajor >= 16) {
const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(41724)
module.exports.deleteCookie = deleteCookie
module.exports.getCookies = getCookies
module.exports.getSetCookies = getSetCookies
module.exports.setCookie = setCookie
const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685)
module.exports.parseMIMEType = parseMIMEType
module.exports.serializeAMimeType = serializeAMimeType
}
if (util.nodeMajor >= 18 && hasCrypto) {
const { WebSocket } = __nccwpck_require__(54284)
module.exports.WebSocket = WebSocket
}
module.exports.request = makeDispatcher(api.request)
module.exports.stream = makeDispatcher(api.stream)
module.exports.pipeline = makeDispatcher(api.pipeline)
module.exports.connect = makeDispatcher(api.connect)
module.exports.upgrade = makeDispatcher(api.upgrade)
module.exports.MockClient = MockClient
module.exports.MockPool = MockPool
module.exports.MockAgent = MockAgent
module.exports.mockErrors = mockErrors
/***/ }),
/***/ 7890:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { InvalidArgumentError } = __nccwpck_require__(48045)
const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(72785)
const DispatcherBase = __nccwpck_require__(74839)
const Pool = __nccwpck_require__(4634)
const Client = __nccwpck_require__(33598)
const util = __nccwpck_require__(83983)
const createRedirectInterceptor = __nccwpck_require__(38861)
const { WeakRef, FinalizationRegistry } = __nccwpck_require__(56436)()
const kOnConnect = Symbol('onConnect')
const kOnDisconnect = Symbol('onDisconnect')
const kOnConnectionError = Symbol('onConnectionError')
const kMaxRedirections = Symbol('maxRedirections')
const kOnDrain = Symbol('onDrain')
const kFactory = Symbol('factory')
const kFinalizer = Symbol('finalizer')
const kOptions = Symbol('options')
function defaultFactory (origin, opts) {
return opts && opts.connections === 1
? new Client(origin, opts)
: new Pool(origin, opts)
}
class Agent extends DispatcherBase {
constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
super()
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}
if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
throw new InvalidArgumentError('connect must be a function or an object')
}
if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
throw new InvalidArgumentError('maxRedirections must be a positive number')
}
if (connect && typeof connect !== 'function') {
connect = { ...connect }
}
this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
? options.interceptors.Agent
: [createRedirectInterceptor({ maxRedirections })]
this[kOptions] = { ...util.deepClone(options), connect }
this[kOptions].interceptors = options.interceptors
? { ...options.interceptors }
: undefined
this[kMaxRedirections] = maxRedirections
this[kFactory] = factory
this[kClients] = new Map()
this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
const ref = this[kClients].get(key)
if (ref !== undefined && ref.deref() === undefined) {
this[kClients].delete(key)
}
})
const agent = this
this[kOnDrain] = (origin, targets) => {
agent.emit('drain', origin, [agent, ...targets])
}
this[kOnConnect] = (origin, targets) => {
agent.emit('connect', origin, [agent, ...targets])
}
this[kOnDisconnect] = (origin, targets, err) => {
agent.emit('disconnect', origin, [agent, ...targets], err)
}
this[kOnConnectionError] = (origin, targets, err) => {
agent.emit('connectionError', origin, [agent, ...targets], err)
}
}
get [kRunning] () {
let ret = 0
for (const ref of this[kClients].values()) {
const client = ref.deref()
/* istanbul ignore next: gc is undeterministic */
if (client) {
ret += client[kRunning]
}
}
return ret
}
[kDispatch] (opts, handler) {
let key
if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
key = String(opts.origin)
} else {
throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
}
const ref = this[kClients].get(key)
let dispatcher = ref ? ref.deref() : null
if (!dispatcher) {
dispatcher = this[kFactory](opts.origin, this[kOptions])
.on('drain', this[kOnDrain])
.on('connect', this[kOnConnect])
.on('disconnect', this[kOnDisconnect])
.on('connectionError', this[kOnConnectionError])
this[kClients].set(key, new WeakRef(dispatcher))
this[kFinalizer].register(dispatcher, key)
}
return dispatcher.dispatch(opts, handler)
}
async [kClose] () {
const closePromises = []
for (const ref of this[kClients].values()) {
const client = ref.deref()
/* istanbul ignore else: gc is undeterministic */
if (client) {
closePromises.push(client.close())
}
}
await Promise.all(closePromises)
}
async [kDestroy] (err) {
const destroyPromises = []
for (const ref of this[kClients].values()) {
const client = ref.deref()
/* istanbul ignore else: gc is undeterministic */
if (client) {
destroyPromises.push(client.destroy(err))
}
}
await Promise.all(destroyPromises)
}
}
module.exports = Agent
/***/ }),
/***/ 7032:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const { addAbortListener } = __nccwpck_require__(83983)
const { RequestAbortedError } = __nccwpck_require__(48045)
const kListener = Symbol('kListener')
const kSignal = Symbol('kSignal')
function abort (self) {
if (self.abort) {
self.abort()
} else {
self.onError(new RequestAbortedError())
}
}
function addSignal (self, signal) {
self[kSignal] = null
self[kListener] = null
if (!signal) {
return
}
if (signal.aborted) {
abort(self)
return
}
self[kSignal] = signal
self[kListener] = () => {
abort(self)
}
addAbortListener(self[kSignal], self[kListener])
}
function removeSignal (self) {
if (!self[kSignal]) {
return
}
if ('removeEventListener' in self[kSignal]) {
self[kSignal].removeEventListener('abort', self[kListener])
} else {
self[kSignal].removeListener('abort', self[kListener])
}
self[kSignal] = null
self[kListener] = null
}
module.exports = {
addSignal,
removeSignal
}
/***/ }),
/***/ 29744:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { AsyncResource } = __nccwpck_require__(50852)
const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { addSignal, removeSignal } = __nccwpck_require__(7032)
class ConnectHandler extends AsyncResource {
constructor (opts, callback) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
const { signal, opaque, responseHeaders } = opts
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
super('UNDICI_CONNECT')
this.opaque = opaque || null
this.responseHeaders = responseHeaders || null
this.callback = callback
this.abort = null
addSignal(this, signal)
}
onConnect (abort, context) {
if (!this.callback) {
throw new RequestAbortedError()
}
this.abort = abort
this.context = context
}
onHeaders () {
throw new SocketError('bad connect', null)
}
onUpgrade (statusCode, rawHeaders, socket) {
const { callback, opaque, context } = this
removeSignal(this)
this.callback = null
let headers = rawHeaders
// Indicates is an HTTP2Session
if (headers != null) {
headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
}
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
socket,
opaque,
context
})
}
onError (err) {
const { callback, opaque } = this
removeSignal(this)
if (callback) {
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
})
}
}
}
function connect (opts, callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
connect.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
try {
const connectHandler = new ConnectHandler(opts, callback)
this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
} catch (err) {
if (typeof callback !== 'function') {
throw err
}
const opaque = opts && opts.opaque
queueMicrotask(() => callback(err, { opaque }))
}
}
module.exports = connect
/***/ }),
/***/ 28752:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
Readable,
Duplex,
PassThrough
} = __nccwpck_require__(12781)
const {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { AsyncResource } = __nccwpck_require__(50852)
const { addSignal, removeSignal } = __nccwpck_require__(7032)
const assert = __nccwpck_require__(39491)
const kResume = Symbol('resume')
class PipelineRequest extends Readable {
constructor () {
super({ autoDestroy: true })
this[kResume] = null
}
_read () {
const { [kResume]: resume } = this
if (resume) {
this[kResume] = null
resume()
}
}
_destroy (err, callback) {
this._read()
callback(err)
}
}
class PipelineResponse extends Readable {
constructor (resume) {
super({ autoDestroy: true })
this[kResume] = resume
}
_read () {
this[kResume]()
}
_destroy (err, callback) {
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError()
}
callback(err)
}
}
class PipelineHandler extends AsyncResource {
constructor (opts, handler) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (typeof handler !== 'function') {
throw new InvalidArgumentError('invalid handler')
}
const { signal, method, opaque, onInfo, responseHeaders } = opts
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
if (method === 'CONNECT') {
throw new InvalidArgumentError('invalid method')
}
if (onInfo && typeof onInfo !== 'function') {
throw new InvalidArgumentError('invalid onInfo callback')
}
super('UNDICI_PIPELINE')
this.opaque = opaque || null
this.responseHeaders = responseHeaders || null
this.handler = handler
this.abort = null
this.context = null
this.onInfo = onInfo || null
this.req = new PipelineRequest().on('error', util.nop)
this.ret = new Duplex({
readableObjectMode: opts.objectMode,
autoDestroy: true,
read: () => {
const { body } = this
if (body && body.resume) {
body.resume()
}
},
write: (chunk, encoding, callback) => {
const { req } = this
if (req.push(chunk, encoding) || req._readableState.destroyed) {
callback()
} else {
req[kResume] = callback
}
},
destroy: (err, callback) => {
const { body, req, res, ret, abort } = this
if (!err && !ret._readableState.endEmitted) {
err = new RequestAbortedError()
}
if (abort && err) {
abort()
}
util.destroy(body, err)
util.destroy(req, err)
util.destroy(res, err)
removeSignal(this)
callback(err)
}
}).on('prefinish', () => {
const { req } = this
// Node < 15 does not call _final in same tick.
req.push(null)
})
this.res = null
addSignal(this, signal)
}
onConnect (abort, context) {
const { ret, res } = this
assert(!res, 'pipeline cannot be retried')
if (ret.destroyed) {
throw new RequestAbortedError()
}
this.abort = abort
this.context = context
}
onHeaders (statusCode, rawHeaders, resume) {
const { opaque, handler, context } = this
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
this.onInfo({ statusCode, headers })
}
return
}
this.res = new PipelineResponse(resume)
let body
try {
this.handler = null
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
opaque,
body: this.res,
context
})
} catch (err) {
this.res.on('error', util.nop)
throw err
}
if (!body || typeof body.on !== 'function') {
throw new InvalidReturnValueError('expected Readable')
}
body
.on('data', (chunk) => {
const { ret, body } = this
if (!ret.push(chunk) && body.pause) {
body.pause()
}
})
.on('error', (err) => {
const { ret } = this
util.destroy(ret, err)
})
.on('end', () => {
const { ret } = this
ret.push(null)
})
.on('close', () => {
const { ret } = this
if (!ret._readableState.ended) {
util.destroy(ret, new RequestAbortedError())
}
})
this.body = body
}
onData (chunk) {
const { res } = this
return res.push(chunk)
}
onComplete (trailers) {
const { res } = this
res.push(null)
}
onError (err) {
const { ret } = this
this.handler = null
util.destroy(ret, err)
}
}
function pipeline (opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler)
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
return pipelineHandler.ret
} catch (err) {
return new PassThrough().destroy(err)
}
}
module.exports = pipeline
/***/ }),
/***/ 55448:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Readable = __nccwpck_require__(73858)
const {
InvalidArgumentError,
RequestAbortedError
} = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { getResolveErrorBodyCallback } = __nccwpck_require__(77474)
const { AsyncResource } = __nccwpck_require__(50852)
const { addSignal, removeSignal } = __nccwpck_require__(7032)
class RequestHandler extends AsyncResource {
constructor (opts, callback) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
try {
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
throw new InvalidArgumentError('invalid highWaterMark')
}
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
if (method === 'CONNECT') {
throw new InvalidArgumentError('invalid method')
}
if (onInfo && typeof onInfo !== 'function') {
throw new InvalidArgumentError('invalid onInfo callback')
}
super('UNDICI_REQUEST')
} catch (err) {
if (util.isStream(body)) {
util.destroy(body.on('error', util.nop), err)
}
throw err
}
this.responseHeaders = responseHeaders || null
this.opaque = opaque || null
this.callback = callback
this.res = null
this.abort = null
this.body = body
this.trailers = {}
this.context = null
this.onInfo = onInfo || null
this.throwOnError = throwOnError
this.highWaterMark = highWaterMark
if (util.isStream(body)) {
body.on('error', (err) => {
this.onError(err)
})
}
addSignal(this, signal)
}
onConnect (abort, context) {
if (!this.callback) {
throw new RequestAbortedError()
}
this.abort = abort
this.context = context
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers })
}
return
}
const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
const contentType = parsedHeaders['content-type']
const body = new Readable({ resume, abort, contentType, highWaterMark })
this.callback = null
this.res = body
if (callback !== null) {
if (this.throwOnError && statusCode >= 400) {
this.runInAsyncScope(getResolveErrorBodyCallback, null,
{ callback, body, contentType, statusCode, statusMessage, headers }
)
} else {
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
trailers: this.trailers,
opaque,
body,
context
})
}
}
}
onData (chunk) {
const { res } = this
return res.push(chunk)
}
onComplete (trailers) {
const { res } = this
removeSignal(this)
util.parseHeaders(trailers, this.trailers)
res.push(null)
}
onError (err) {
const { res, callback, body, opaque } = this
removeSignal(this)
if (callback) {
// TODO: Does this need queueMicrotask?
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
})
}
if (res) {
this.res = null
// Ensure all queued handlers are invoked before destroying res.
queueMicrotask(() => {
util.destroy(res, err)
})
}
if (body) {
this.body = null
util.destroy(body, err)
}
}
}
function request (opts, callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
request.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
try {
this.dispatch(opts, new RequestHandler(opts, callback))
} catch (err) {
if (typeof callback !== 'function') {
throw err
}
const opaque = opts && opts.opaque
queueMicrotask(() => callback(err, { opaque }))
}
}
module.exports = request
module.exports.RequestHandler = RequestHandler
/***/ }),
/***/ 75395:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { finished, PassThrough } = __nccwpck_require__(12781)
const {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { getResolveErrorBodyCallback } = __nccwpck_require__(77474)
const { AsyncResource } = __nccwpck_require__(50852)
const { addSignal, removeSignal } = __nccwpck_require__(7032)
class StreamHandler extends AsyncResource {
constructor (opts, factory, callback) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
try {
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
if (typeof factory !== 'function') {
throw new InvalidArgumentError('invalid factory')
}
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
if (method === 'CONNECT') {
throw new InvalidArgumentError('invalid method')
}
if (onInfo && typeof onInfo !== 'function') {
throw new InvalidArgumentError('invalid onInfo callback')
}
super('UNDICI_STREAM')
} catch (err) {
if (util.isStream(body)) {
util.destroy(body.on('error', util.nop), err)
}
throw err
}
this.responseHeaders = responseHeaders || null
this.opaque = opaque || null
this.factory = factory
this.callback = callback
this.res = null
this.abort = null
this.context = null
this.trailers = null
this.body = body
this.onInfo = onInfo || null
this.throwOnError = throwOnError || false
if (util.isStream(body)) {
body.on('error', (err) => {
this.onError(err)
})
}
addSignal(this, signal)
}
onConnect (abort, context) {
if (!this.callback) {
throw new RequestAbortedError()
}
this.abort = abort
this.context = context
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
const { factory, opaque, context, callback, responseHeaders } = this
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers })
}
return
}
this.factory = null
let res
if (this.throwOnError && statusCode >= 400) {
const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
const contentType = parsedHeaders['content-type']
res = new PassThrough()
this.callback = null
this.runInAsyncScope(getResolveErrorBodyCallback, null,
{ callback, body: res, contentType, statusCode, statusMessage, headers }
)
} else {
if (factory === null) {
return
}
res = this.runInAsyncScope(factory, null, {
statusCode,
headers,
opaque,
context
})
if (
!res ||
typeof res.write !== 'function' ||
typeof res.end !== 'function' ||
typeof res.on !== 'function'
) {
throw new InvalidReturnValueError('expected Writable')
}
// TODO: Avoid finished. It registers an unnecessary amount of listeners.
finished(res, { readable: false }, (err) => {
const { callback, res, opaque, trailers, abort } = this
this.res = null
if (err || !res.readable) {
util.destroy(res, err)
}
this.callback = null
this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
if (err) {
abort()
}
})
}
res.on('drain', resume)
this.res = res
const needDrain = res.writableNeedDrain !== undefined
? res.writableNeedDrain
: res._writableState && res._writableState.needDrain
return needDrain !== true
}
onData (chunk) {
const { res } = this
return res ? res.write(chunk) : true
}
onComplete (trailers) {
const { res } = this
removeSignal(this)
if (!res) {
return
}
this.trailers = util.parseHeaders(trailers)
res.end()
}
onError (err) {
const { res, callback, opaque, body } = this
removeSignal(this)
this.factory = null
if (res) {
this.res = null
util.destroy(res, err)
} else if (callback) {
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
})
}
if (body) {
this.body = null
util.destroy(body, err)
}
}
}
function stream (opts, factory, callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
stream.call(this, opts, factory, (err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
try {
this.dispatch(opts, new StreamHandler(opts, factory, callback))
} catch (err) {
if (typeof callback !== 'function') {
throw err
}
const opaque = opts && opts.opaque
queueMicrotask(() => callback(err, { opaque }))
}
}
module.exports = stream
/***/ }),
/***/ 36923:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(48045)
const { AsyncResource } = __nccwpck_require__(50852)
const util = __nccwpck_require__(83983)
const { addSignal, removeSignal } = __nccwpck_require__(7032)
const assert = __nccwpck_require__(39491)
class UpgradeHandler extends AsyncResource {
constructor (opts, callback) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
const { signal, opaque, responseHeaders } = opts
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
super('UNDICI_UPGRADE')
this.responseHeaders = responseHeaders || null
this.opaque = opaque || null
this.callback = callback
this.abort = null
this.context = null
addSignal(this, signal)
}
onConnect (abort, context) {
if (!this.callback) {
throw new RequestAbortedError()
}
this.abort = abort
this.context = null
}
onHeaders () {
throw new SocketError('bad upgrade', null)
}
onUpgrade (statusCode, rawHeaders, socket) {
const { callback, opaque, context } = this
assert.strictEqual(statusCode, 101)
removeSignal(this)
this.callback = null
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
this.runInAsyncScope(callback, null, null, {
headers,
socket,
opaque,
context
})
}
onError (err) {
const { callback, opaque } = this
removeSignal(this)
if (callback) {
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
})
}
}
}
function upgrade (opts, callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
upgrade.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
try {
const upgradeHandler = new UpgradeHandler(opts, callback)
this.dispatch({
...opts,
method: opts.method || 'GET',
upgrade: opts.protocol || 'Websocket'
}, upgradeHandler)
} catch (err) {
if (typeof callback !== 'function') {
throw err
}
const opaque = opts && opts.opaque
queueMicrotask(() => callback(err, { opaque }))
}
}
module.exports = upgrade
/***/ }),
/***/ 44059:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports.request = __nccwpck_require__(55448)
module.exports.stream = __nccwpck_require__(75395)
module.exports.pipeline = __nccwpck_require__(28752)
module.exports.upgrade = __nccwpck_require__(36923)
module.exports.connect = __nccwpck_require__(29744)
/***/ }),
/***/ 73858:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// Ported from https://github.com/nodejs/undici/pull/907
const assert = __nccwpck_require__(39491)
const { Readable } = __nccwpck_require__(12781)
const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(83983)
let Blob
const kConsume = Symbol('kConsume')
const kReading = Symbol('kReading')
const kBody = Symbol('kBody')
const kAbort = Symbol('abort')
const kContentType = Symbol('kContentType')
const noop = () => {}
module.exports = class BodyReadable extends Readable {
constructor ({
resume,
abort,
contentType = '',
highWaterMark = 64 * 1024 // Same as nodejs fs streams.
}) {
super({
autoDestroy: true,
read: resume,
highWaterMark
})
this._readableState.dataEmitted = false
this[kAbort] = abort
this[kConsume] = null
this[kBody] = null
this[kContentType] = contentType
// Is stream being consumed through Readable API?
// This is an optimization so that we avoid checking
// for 'data' and 'readable' listeners in the hot path
// inside push().
this[kReading] = false
}
destroy (err) {
if (this.destroyed) {
// Node < 16
return this
}
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError()
}
if (err) {
this[kAbort]()
}
return super.destroy(err)
}
emit (ev, ...args) {
if (ev === 'data') {
// Node < 16.7
this._readableState.dataEmitted = true
} else if (ev === 'error') {
// Node < 16
this._readableState.errorEmitted = true
}
return super.emit(ev, ...args)
}
on (ev, ...args) {
if (ev === 'data' || ev === 'readable') {
this[kReading] = true
}
return super.on(ev, ...args)
}
addListener (ev, ...args) {
return this.on(ev, ...args)
}
off (ev, ...args) {
const ret = super.off(ev, ...args)
if (ev === 'data' || ev === 'readable') {
this[kReading] = (
this.listenerCount('data') > 0 ||
this.listenerCount('readable') > 0
)
}
return ret
}
removeListener (ev, ...args) {
return this.off(ev, ...args)
}
push (chunk) {
if (this[kConsume] && chunk !== null && this.readableLength === 0) {
consumePush(this[kConsume], chunk)
return this[kReading] ? super.push(chunk) : true
}
return super.push(chunk)
}
// https://fetch.spec.whatwg.org/#dom-body-text
async text () {
return consume(this, 'text')
}
// https://fetch.spec.whatwg.org/#dom-body-json
async json () {
return consume(this, 'json')
}
// https://fetch.spec.whatwg.org/#dom-body-blob
async blob () {
return consume(this, 'blob')
}
// https://fetch.spec.whatwg.org/#dom-body-arraybuffer
async arrayBuffer () {
return consume(this, 'arrayBuffer')
}
// https://fetch.spec.whatwg.org/#dom-body-formdata
async formData () {
// TODO: Implement.
throw new NotSupportedError()
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
get bodyUsed () {
return util.isDisturbed(this)
}
// https://fetch.spec.whatwg.org/#dom-body-body
get body () {
if (!this[kBody]) {
this[kBody] = ReadableStreamFrom(this)
if (this[kConsume]) {
// TODO: Is this the best way to force a lock?
this[kBody].getReader() // Ensure stream is locked.
assert(this[kBody].locked)
}
}
return this[kBody]
}
dump (opts) {
let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
const signal = opts && opts.signal
if (signal) {
try {
if (typeof signal !== 'object' || !('aborted' in signal)) {
throw new InvalidArgumentError('signal must be an AbortSignal')
}
util.throwIfAborted(signal)
} catch (err) {
return Promise.reject(err)
}
}
if (this.closed) {
return Promise.resolve(null)
}
return new Promise((resolve, reject) => {
const signalListenerCleanup = signal
? util.addAbortListener(signal, () => {
this.destroy()
})
: noop
this
.on('close', function () {
signalListenerCleanup()
if (signal && signal.aborted) {
reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
} else {
resolve(null)
}
})
.on('error', noop)
.on('data', function (chunk) {
limit -= chunk.length
if (limit <= 0) {
this.destroy()
}
})
.resume()
})
}
}
// https://streams.spec.whatwg.org/#readablestream-locked
function isLocked (self) {
// Consume is an implicit lock.
return (self[kBody] && self[kBody].locked === true) || self[kConsume]
}
// https://fetch.spec.whatwg.org/#body-unusable
function isUnusable (self) {
return util.isDisturbed(self) || isLocked(self)
}
async function consume (stream, type) {
if (isUnusable(stream)) {
throw new TypeError('unusable')
}
assert(!stream[kConsume])
return new Promise((resolve, reject) => {
stream[kConsume] = {
type,
stream,
resolve,
reject,
length: 0,
body: []
}
stream
.on('error', function (err) {
consumeFinish(this[kConsume], err)
})
.on('close', function () {
if (this[kConsume].body !== null) {
consumeFinish(this[kConsume], new RequestAbortedError())
}
})
process.nextTick(consumeStart, stream[kConsume])
})
}
function consumeStart (consume) {
if (consume.body === null) {
return
}
const { _readableState: state } = consume.stream
for (const chunk of state.buffer) {
consumePush(consume, chunk)
}
if (state.endEmitted) {
consumeEnd(this[kConsume])
} else {
consume.stream.on('end', function () {
consumeEnd(this[kConsume])
})
}
consume.stream.resume()
while (consume.stream.read() != null) {
// Loop
}
}
function consumeEnd (consume) {
const { type, body, resolve, stream, length } = consume
try {
if (type === 'text') {
resolve(toUSVString(Buffer.concat(body)))
} else if (type === 'json') {
resolve(JSON.parse(Buffer.concat(body)))
} else if (type === 'arrayBuffer') {
const dst = new Uint8Array(length)
let pos = 0
for (const buf of body) {
dst.set(buf, pos)
pos += buf.byteLength
}
resolve(dst.buffer)
} else if (type === 'blob') {
if (!Blob) {
Blob = (__nccwpck_require__(14300).Blob)
}
resolve(new Blob(body, { type: stream[kContentType] }))
}
consumeFinish(consume)
} catch (err) {
stream.destroy(err)
}
}
function consumePush (consume, chunk) {
consume.length += chunk.length
consume.body.push(chunk)
}
function consumeFinish (consume, err) {
if (consume.body === null) {
return
}
if (err) {
consume.reject(err)
} else {
consume.resolve()
}
consume.type = null
consume.stream = null
consume.resolve = null
consume.reject = null
consume.length = 0
consume.body = null
}
/***/ }),
/***/ 77474:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const assert = __nccwpck_require__(39491)
const {
ResponseStatusCodeError
} = __nccwpck_require__(48045)
const { toUSVString } = __nccwpck_require__(83983)
async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
assert(body)
let chunks = []
let limit = 0
for await (const chunk of body) {
chunks.push(chunk)
limit += chunk.length
if (limit > 128 * 1024) {
chunks = null
break
}
}
if (statusCode === 204 || !contentType || !chunks) {
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
return
}
try {
if (contentType.startsWith('application/json')) {
const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
return
}
if (contentType.startsWith('text/')) {
const payload = toUSVString(Buffer.concat(chunks))
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
return
}
} catch (err) {
// Process in a fallback if error
}
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
}
module.exports = { getResolveErrorBodyCallback }
/***/ }),
/***/ 37931:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
BalancedPoolMissingUpstreamError,
InvalidArgumentError
} = __nccwpck_require__(48045)
const {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
} = __nccwpck_require__(73198)
const Pool = __nccwpck_require__(4634)
const { kUrl, kInterceptors } = __nccwpck_require__(72785)
const { parseOrigin } = __nccwpck_require__(83983)
const kFactory = Symbol('factory')
const kOptions = Symbol('options')
const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
const kCurrentWeight = Symbol('kCurrentWeight')
const kIndex = Symbol('kIndex')
const kWeight = Symbol('kWeight')
const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
const kErrorPenalty = Symbol('kErrorPenalty')
function getGreatestCommonDivisor (a, b) {
if (b === 0) return a
return getGreatestCommonDivisor(b, a % b)
}
function defaultFactory (origin, opts) {
return new Pool(origin, opts)
}
class BalancedPool extends PoolBase {
constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
super()
this[kOptions] = opts
this[kIndex] = -1
this[kCurrentWeight] = 0
this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
this[kErrorPenalty] = this[kOptions].errorPenalty || 15
if (!Array.isArray(upstreams)) {
upstreams = [upstreams]
}
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}
this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
? opts.interceptors.BalancedPool
: []
this[kFactory] = factory
for (const upstream of upstreams) {
this.addUpstream(upstream)
}
this._updateBalancedPoolStats()
}
addUpstream (upstream) {
const upstreamOrigin = parseOrigin(upstream).origin
if (this[kClients].find((pool) => (
pool[kUrl].origin === upstreamOrigin &&
pool.closed !== true &&
pool.destroyed !== true
))) {
return this
}
const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
this[kAddClient](pool)
pool.on('connect', () => {
pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
})
pool.on('connectionError', () => {
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
this._updateBalancedPoolStats()
})
pool.on('disconnect', (...args) => {
const err = args[2]
if (err && err.code === 'UND_ERR_SOCKET') {
// decrease the weight of the pool.
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
this._updateBalancedPoolStats()
}
})
for (const client of this[kClients]) {
client[kWeight] = this[kMaxWeightPerServer]
}
this._updateBalancedPoolStats()
return this
}
_updateBalancedPoolStats () {
this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
}
removeUpstream (upstream) {
const upstreamOrigin = parseOrigin(upstream).origin
const pool = this[kClients].find((pool) => (
pool[kUrl].origin === upstreamOrigin &&
pool.closed !== true &&
pool.destroyed !== true
))
if (pool) {
this[kRemoveClient](pool)
}
return this
}
get upstreams () {
return this[kClients]
.filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
.map((p) => p[kUrl].origin)
}
[kGetDispatcher] () {
// We validate that pools is greater than 0,
// otherwise we would have to wait until an upstream
// is added, which might never happen.
if (this[kClients].length === 0) {
throw new BalancedPoolMissingUpstreamError()
}
const dispatcher = this[kClients].find(dispatcher => (
!dispatcher[kNeedDrain] &&
dispatcher.closed !== true &&
dispatcher.destroyed !== true
))
if (!dispatcher) {
return
}
const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
if (allClientsBusy) {
return
}
let counter = 0
let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
while (counter++ < this[kClients].length) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length
const pool = this[kClients][this[kIndex]]
// find pool index with the largest weight
if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
maxWeightIndex = this[kIndex]
}
// decrease the current weight every `this[kClients].length`.
if (this[kIndex] === 0) {
// Set the current weight to the next lower weight.
this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
if (this[kCurrentWeight] <= 0) {
this[kCurrentWeight] = this[kMaxWeightPerServer]
}
}
if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
return pool
}
}
this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
this[kIndex] = maxWeightIndex
return this[kClients][maxWeightIndex]
}
}
module.exports = BalancedPool
/***/ }),
/***/ 66101:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { kConstruct } = __nccwpck_require__(29174)
const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(82396)
const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(83983)
const { kHeadersList } = __nccwpck_require__(72785)
const { webidl } = __nccwpck_require__(21744)
const { Response, cloneResponse } = __nccwpck_require__(27823)
const { Request } = __nccwpck_require__(48359)
const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861)
const { fetching } = __nccwpck_require__(74881)
const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(52538)
const assert = __nccwpck_require__(39491)
const { getGlobalDispatcher } = __nccwpck_require__(21892)
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
* @typedef {Object} CacheBatchOperation
* @property {'delete' | 'put'} type
* @property {any} request
* @property {any} response
* @property {import('../../types/cache').CacheQueryOptions} options
*/
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
* @typedef {[any, any][]} requestResponseList
*/
class Cache {
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
* @type {requestResponseList}
*/
#relevantRequestResponseList
constructor () {
if (arguments[0] !== kConstruct) {
webidl.illegalConstructor()
}
this.#relevantRequestResponseList = arguments[1]
}
async match (request, options = {}) {
webidl.brandCheck(this, Cache)
webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
const p = await this.matchAll(request, options)
if (p.length === 0) {
return
}
return p[0]
}
async matchAll (request = undefined, options = {}) {
webidl.brandCheck(this, Cache)
if (request !== undefined) request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
// 1.
let r = null
// 2.
if (request !== undefined) {
if (request instanceof Request) {
// 2.1.1
r = request[kState]
// 2.1.2
if (r.method !== 'GET' && !options.ignoreMethod) {
return []
}
} else if (typeof request === 'string') {
// 2.2.1
r = new Request(request)[kState]
}
}
// 5.
// 5.1
const responses = []
// 5.2
if (request === undefined) {
// 5.2.1
for (const requestResponse of this.#relevantRequestResponseList) {
responses.push(requestResponse[1])
}
} else { // 5.3
// 5.3.1
const requestResponses = this.#queryCache(r, options)
// 5.3.2
for (const requestResponse of requestResponses) {
responses.push(requestResponse[1])
}
}
// 5.4
// We don't implement CORs so we don't need to loop over the responses, yay!
// 5.5.1
const responseList = []
// 5.5.2
for (const response of responses) {
// 5.5.2.1
const responseObject = new Response(response.body?.source ?? null)
const body = responseObject[kState].body
responseObject[kState] = response
responseObject[kState].body = body
responseObject[kHeaders][kHeadersList] = response.headersList
responseObject[kHeaders][kGuard] = 'immutable'
responseList.push(responseObject)
}
// 6.
return Object.freeze(responseList)
}
async add (request) {
webidl.brandCheck(this, Cache)
webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
request = webidl.converters.RequestInfo(request)
// 1.
const requests = [request]
// 2.
const responseArrayPromise = this.addAll(requests)
// 3.
return await responseArrayPromise
}
async addAll (requests) {
webidl.brandCheck(this, Cache)
webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
requests = webidl.converters['sequence<RequestInfo>'](requests)
// 1.
const responsePromises = []
// 2.
const requestList = []
// 3.
for (const request of requests) {
if (typeof request === 'string') {
continue
}
// 3.1
const r = request[kState]
// 3.2
if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
throw webidl.errors.exception({
header: 'Cache.addAll',
message: 'Expected http/s scheme when method is not GET.'
})
}
}
// 4.
/** @type {ReturnType<typeof fetching>[]} */
const fetchControllers = []
// 5.
for (const request of requests) {
// 5.1
const r = new Request(request)[kState]
// 5.2
if (!urlIsHttpHttpsScheme(r.url)) {
throw webidl.errors.exception({
header: 'Cache.addAll',
message: 'Expected http/s scheme.'
})
}
// 5.4
r.initiator = 'fetch'
r.destination = 'subresource'
// 5.5
requestList.push(r)
// 5.6
const responsePromise = createDeferredPromise()
// 5.7
fetchControllers.push(fetching({
request: r,
dispatcher: getGlobalDispatcher(),
processResponse (response) {
// 1.
if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
responsePromise.reject(webidl.errors.exception({
header: 'Cache.addAll',
message: 'Received an invalid status code or the request failed.'
}))
} else if (response.headersList.contains('vary')) { // 2.
// 2.1
const fieldValues = getFieldValues(response.headersList.get('vary'))
// 2.2
for (const fieldValue of fieldValues) {
// 2.2.1
if (fieldValue === '*') {
responsePromise.reject(webidl.errors.exception({
header: 'Cache.addAll',
message: 'invalid vary field value'
}))
for (const controller of fetchControllers) {
controller.abort()
}
return
}
}
}
},
processResponseEndOfBody (response) {
// 1.
if (response.aborted) {
responsePromise.reject(new DOMException('aborted', 'AbortError'))
return
}
// 2.
responsePromise.resolve(response)
}
}))
// 5.8
responsePromises.push(responsePromise.promise)
}
// 6.
const p = Promise.all(responsePromises)
// 7.
const responses = await p
// 7.1
const operations = []
// 7.2
let index = 0
// 7.3
for (const response of responses) {
// 7.3.1
/** @type {CacheBatchOperation} */
const operation = {
type: 'put', // 7.3.2
request: requestList[index], // 7.3.3
response // 7.3.4
}
operations.push(operation) // 7.3.5
index++ // 7.3.6
}
// 7.5
const cacheJobPromise = createDeferredPromise()
// 7.6.1
let errorData = null
// 7.6.2
try {
this.#batchCacheOperations(operations)
} catch (e) {
errorData = e
}
// 7.6.3
queueMicrotask(() => {
// 7.6.3.1
if (errorData === null) {
cacheJobPromise.resolve(undefined)
} else {
// 7.6.3.2
cacheJobPromise.reject(errorData)
}
})
// 7.7
return cacheJobPromise.promise
}
async put (request, response) {
webidl.brandCheck(this, Cache)
webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
request = webidl.converters.RequestInfo(request)
response = webidl.converters.Response(response)
// 1.
let innerRequest = null
// 2.
if (request instanceof Request) {
innerRequest = request[kState]
} else { // 3.
innerRequest = new Request(request)[kState]
}
// 4.
if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
throw webidl.errors.exception({
header: 'Cache.put',
message: 'Expected an http/s scheme when method is not GET'
})
}
// 5.
const innerResponse = response[kState]
// 6.
if (innerResponse.status === 206) {
throw webidl.errors.exception({
header: 'Cache.put',
message: 'Got 206 status'
})
}
// 7.
if (innerResponse.headersList.contains('vary')) {
// 7.1.
const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
// 7.2.
for (const fieldValue of fieldValues) {
// 7.2.1
if (fieldValue === '*') {
throw webidl.errors.exception({
header: 'Cache.put',
message: 'Got * vary field value'
})
}
}
}
// 8.
if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
throw webidl.errors.exception({
header: 'Cache.put',
message: 'Response body is locked or disturbed'
})
}
// 9.
const clonedResponse = cloneResponse(innerResponse)
// 10.
const bodyReadPromise = createDeferredPromise()
// 11.
if (innerResponse.body != null) {
// 11.1
const stream = innerResponse.body.stream
// 11.2
const reader = stream.getReader()
// 11.3
readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
} else {
bodyReadPromise.resolve(undefined)
}
// 12.
/** @type {CacheBatchOperation[]} */
const operations = []
// 13.
/** @type {CacheBatchOperation} */
const operation = {
type: 'put', // 14.
request: innerRequest, // 15.
response: clonedResponse // 16.
}
// 17.
operations.push(operation)
// 19.
const bytes = await bodyReadPromise.promise
if (clonedResponse.body != null) {
clonedResponse.body.source = bytes
}
// 19.1
const cacheJobPromise = createDeferredPromise()
// 19.2.1
let errorData = null
// 19.2.2
try {
this.#batchCacheOperations(operations)
} catch (e) {
errorData = e
}
// 19.2.3
queueMicrotask(() => {
// 19.2.3.1
if (errorData === null) {
cacheJobPromise.resolve()
} else { // 19.2.3.2
cacheJobPromise.reject(errorData)
}
})
return cacheJobPromise.promise
}
async delete (request, options = {}) {
webidl.brandCheck(this, Cache)
webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
/**
* @type {Request}
*/
let r = null
if (request instanceof Request) {
r = request[kState]
if (r.method !== 'GET' && !options.ignoreMethod) {
return false
}
} else {
assert(typeof request === 'string')
r = new Request(request)[kState]
}
/** @type {CacheBatchOperation[]} */
const operations = []
/** @type {CacheBatchOperation} */
const operation = {
type: 'delete',
request: r,
options
}
operations.push(operation)
const cacheJobPromise = createDeferredPromise()
let errorData = null
let requestResponses
try {
requestResponses = this.#batchCacheOperations(operations)
} catch (e) {
errorData = e
}
queueMicrotask(() => {
if (errorData === null) {
cacheJobPromise.resolve(!!requestResponses?.length)
} else {
cacheJobPromise.reject(errorData)
}
})
return cacheJobPromise.promise
}
/**
* @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
* @param {any} request
* @param {import('../../types/cache').CacheQueryOptions} options
* @returns {readonly Request[]}
*/
async keys (request = undefined, options = {}) {
webidl.brandCheck(this, Cache)
if (request !== undefined) request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
// 1.
let r = null
// 2.
if (request !== undefined) {
// 2.1
if (request instanceof Request) {
// 2.1.1
r = request[kState]
// 2.1.2
if (r.method !== 'GET' && !options.ignoreMethod) {
return []
}
} else if (typeof request === 'string') { // 2.2
r = new Request(request)[kState]
}
}
// 4.
const promise = createDeferredPromise()
// 5.
// 5.1
const requests = []
// 5.2
if (request === undefined) {
// 5.2.1
for (const requestResponse of this.#relevantRequestResponseList) {
// 5.2.1.1
requests.push(requestResponse[0])
}
} else { // 5.3
// 5.3.1
const requestResponses = this.#queryCache(r, options)
// 5.3.2
for (const requestResponse of requestResponses) {
// 5.3.2.1
requests.push(requestResponse[0])
}
}
// 5.4
queueMicrotask(() => {
// 5.4.1
const requestList = []
// 5.4.2
for (const request of requests) {
const requestObject = new Request('https://a')
requestObject[kState] = request
requestObject[kHeaders][kHeadersList] = request.headersList
requestObject[kHeaders][kGuard] = 'immutable'
requestObject[kRealm] = request.client
// 5.4.2.1
requestList.push(requestObject)
}
// 5.4.3
promise.resolve(Object.freeze(requestList))
})
return promise.promise
}
/**
* @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
* @param {CacheBatchOperation[]} operations
* @returns {requestResponseList}
*/
#batchCacheOperations (operations) {
// 1.
const cache = this.#relevantRequestResponseList
// 2.
const backupCache = [...cache]
// 3.
const addedItems = []
// 4.1
const resultList = []
try {
// 4.2
for (const operation of operations) {
// 4.2.1
if (operation.type !== 'delete' && operation.type !== 'put') {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'operation type does not match "delete" or "put"'
})
}
// 4.2.2
if (operation.type === 'delete' && operation.response != null) {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'delete operation should not have an associated response'
})
}
// 4.2.3
if (this.#queryCache(operation.request, operation.options, addedItems).length) {
throw new DOMException('???', 'InvalidStateError')
}
// 4.2.4
let requestResponses
// 4.2.5
if (operation.type === 'delete') {
// 4.2.5.1
requestResponses = this.#queryCache(operation.request, operation.options)
// TODO: the spec is wrong, this is needed to pass WPTs
if (requestResponses.length === 0) {
return []
}
// 4.2.5.2
for (const requestResponse of requestResponses) {
const idx = cache.indexOf(requestResponse)
assert(idx !== -1)
// 4.2.5.2.1
cache.splice(idx, 1)
}
} else if (operation.type === 'put') { // 4.2.6
// 4.2.6.1
if (operation.response == null) {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'put operation should have an associated response'
})
}
// 4.2.6.2
const r = operation.request
// 4.2.6.3
if (!urlIsHttpHttpsScheme(r.url)) {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'expected http or https scheme'
})
}
// 4.2.6.4
if (r.method !== 'GET') {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'not get method'
})
}
// 4.2.6.5
if (operation.options != null) {
throw webidl.errors.exception({
header: 'Cache.#batchCacheOperations',
message: 'options must not be defined'
})
}
// 4.2.6.6
requestResponses = this.#queryCache(operation.request)
// 4.2.6.7
for (const requestResponse of requestResponses) {
const idx = cache.indexOf(requestResponse)
assert(idx !== -1)
// 4.2.6.7.1
cache.splice(idx, 1)
}
// 4.2.6.8
cache.push([operation.request, operation.response])
// 4.2.6.10
addedItems.push([operation.request, operation.response])
}
// 4.2.7
resultList.push([operation.request, operation.response])
}
// 4.3
return resultList
} catch (e) { // 5.
// 5.1
this.#relevantRequestResponseList.length = 0
// 5.2
this.#relevantRequestResponseList = backupCache
// 5.3
throw e
}
}
/**
* @see https://w3c.github.io/ServiceWorker/#query-cache
* @param {any} requestQuery
* @param {import('../../types/cache').CacheQueryOptions} options
* @param {requestResponseList} targetStorage
* @returns {requestResponseList}
*/
#queryCache (requestQuery, options, targetStorage) {
/** @type {requestResponseList} */
const resultList = []
const storage = targetStorage ?? this.#relevantRequestResponseList
for (const requestResponse of storage) {
const [cachedRequest, cachedResponse] = requestResponse
if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
resultList.push(requestResponse)
}
}
return resultList
}
/**
* @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
* @param {any} requestQuery
* @param {any} request
* @param {any | null} response
* @param {import('../../types/cache').CacheQueryOptions | undefined} options
* @returns {boolean}
*/
#requestMatchesCachedItem (requestQuery, request, response = null, options) {
// if (options?.ignoreMethod === false && request.method === 'GET') {
// return false
// }
const queryURL = new URL(requestQuery.url)
const cachedURL = new URL(request.url)
if (options?.ignoreSearch) {
cachedURL.search = ''
queryURL.search = ''
}
if (!urlEquals(queryURL, cachedURL, true)) {
return false
}
if (
response == null ||
options?.ignoreVary ||
!response.headersList.contains('vary')
) {
return true
}
const fieldValues = getFieldValues(response.headersList.get('vary'))
for (const fieldValue of fieldValues) {
if (fieldValue === '*') {
return false
}
const requestValue = request.headersList.get(fieldValue)
const queryValue = requestQuery.headersList.get(fieldValue)
// If one has the header and the other doesn't, or one has
// a different value than the other, return false
if (requestValue !== queryValue) {
return false
}
}
return true
}
}
Object.defineProperties(Cache.prototype, {
[Symbol.toStringTag]: {
value: 'Cache',
configurable: true
},
match: kEnumerableProperty,
matchAll: kEnumerableProperty,
add: kEnumerableProperty,
addAll: kEnumerableProperty,
put: kEnumerableProperty,
delete: kEnumerableProperty,
keys: kEnumerableProperty
})
const cacheQueryOptionConverters = [
{
key: 'ignoreSearch',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'ignoreMethod',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'ignoreVary',
converter: webidl.converters.boolean,
defaultValue: false
}
]
webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
...cacheQueryOptionConverters,
{
key: 'cacheName',
converter: webidl.converters.DOMString
}
])
webidl.converters.Response = webidl.interfaceConverter(Response)
webidl.converters['sequence<RequestInfo>'] = webidl.sequenceConverter(
webidl.converters.RequestInfo
)
module.exports = {
Cache
}
/***/ }),
/***/ 37907:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { kConstruct } = __nccwpck_require__(29174)
const { Cache } = __nccwpck_require__(66101)
const { webidl } = __nccwpck_require__(21744)
const { kEnumerableProperty } = __nccwpck_require__(83983)
class CacheStorage {
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
* @type {Map<string, import('./cache').requestResponseList}
*/
#caches = new Map()
constructor () {
if (arguments[0] !== kConstruct) {
webidl.illegalConstructor()
}
}
async match (request, options = {}) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' })
request = webidl.converters.RequestInfo(request)
options = webidl.converters.MultiCacheQueryOptions(options)
// 1.
if (options.cacheName != null) {
// 1.1.1.1
if (this.#caches.has(options.cacheName)) {
// 1.1.1.1.1
const cacheList = this.#caches.get(options.cacheName)
const cache = new Cache(kConstruct, cacheList)
return await cache.match(request, options)
}
} else { // 2.
// 2.2
for (const cacheList of this.#caches.values()) {
const cache = new Cache(kConstruct, cacheList)
// 2.2.1.2
const response = await cache.match(request, options)
if (response !== undefined) {
return response
}
}
}
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-has
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async has (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
cacheName = webidl.converters.DOMString(cacheName)
// 2.1.1
// 2.2
return this.#caches.has(cacheName)
}
/**
* @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
* @param {string} cacheName
* @returns {Promise<Cache>}
*/
async open (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
cacheName = webidl.converters.DOMString(cacheName)
// 2.1
if (this.#caches.has(cacheName)) {
// await caches.open('v1') !== await caches.open('v1')
// 2.1.1
const cache = this.#caches.get(cacheName)
// 2.1.1.1
return new Cache(kConstruct, cache)
}
// 2.2
const cache = []
// 2.3
this.#caches.set(cacheName, cache)
// 2.4
return new Cache(kConstruct, cache)
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async delete (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
cacheName = webidl.converters.DOMString(cacheName)
return this.#caches.delete(cacheName)
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
* @returns {string[]}
*/
async keys () {
webidl.brandCheck(this, CacheStorage)
// 2.1
const keys = this.#caches.keys()
// 2.2
return [...keys]
}
}
Object.defineProperties(CacheStorage.prototype, {
[Symbol.toStringTag]: {
value: 'CacheStorage',
configurable: true
},
match: kEnumerableProperty,
has: kEnumerableProperty,
open: kEnumerableProperty,
delete: kEnumerableProperty,
keys: kEnumerableProperty
})
module.exports = {
CacheStorage
}
/***/ }),
/***/ 29174:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports = {
kConstruct: (__nccwpck_require__(72785).kConstruct)
}
/***/ }),
/***/ 82396:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(39491)
const { URLSerializer } = __nccwpck_require__(685)
const { isValidHeaderName } = __nccwpck_require__(52538)
/**
* @see https://url.spec.whatwg.org/#concept-url-equals
* @param {URL} A
* @param {URL} B
* @param {boolean | undefined} excludeFragment
* @returns {boolean}
*/
function urlEquals (A, B, excludeFragment = false) {
const serializedA = URLSerializer(A, excludeFragment)
const serializedB = URLSerializer(B, excludeFragment)
return serializedA === serializedB
}
/**
* @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
* @param {string} header
*/
function fieldValues (header) {
assert(header !== null)
const values = []
for (let value of header.split(',')) {
value = value.trim()
if (!value.length) {
continue
} else if (!isValidHeaderName(value)) {
continue
}
values.push(value)
}
return values
}
module.exports = {
urlEquals,
fieldValues
}
/***/ }),
/***/ 33598:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
/* global WebAssembly */
const assert = __nccwpck_require__(39491)
const net = __nccwpck_require__(41808)
const http = __nccwpck_require__(13685)
const { pipeline } = __nccwpck_require__(12781)
const util = __nccwpck_require__(83983)
const timers = __nccwpck_require__(29459)
const Request = __nccwpck_require__(62905)
const DispatcherBase = __nccwpck_require__(74839)
const {
RequestContentLengthMismatchError,
ResponseContentLengthMismatchError,
InvalidArgumentError,
RequestAbortedError,
HeadersTimeoutError,
HeadersOverflowError,
SocketError,
InformationalError,
BodyTimeoutError,
HTTPParserError,
ResponseExceededMaxSizeError,
ClientDestroyedError
} = __nccwpck_require__(48045)
const buildConnector = __nccwpck_require__(82067)
const {
kUrl,
kReset,
kServerName,
kClient,
kBusy,
kParser,
kConnect,
kBlocking,
kResuming,
kRunning,
kPending,
kSize,
kWriting,
kQueue,
kConnected,
kConnecting,
kNeedDrain,
kNoRef,
kKeepAliveDefaultTimeout,
kHostHeader,
kPendingIdx,
kRunningIdx,
kError,
kPipelining,
kSocket,
kKeepAliveTimeoutValue,
kMaxHeadersSize,
kKeepAliveMaxTimeout,
kKeepAliveTimeoutThreshold,
kHeadersTimeout,
kBodyTimeout,
kStrictContentLength,
kConnector,
kMaxRedirections,
kMaxRequests,
kCounter,
kClose,
kDestroy,
kDispatch,
kInterceptors,
kLocalAddress,
kMaxResponseSize,
kHTTPConnVersion,
// HTTP2
kHost,
kHTTP2Session,
kHTTP2SessionState,
kHTTP2BuildRequest,
kHTTP2CopyHeaders,
kHTTP1BuildRequest
} = __nccwpck_require__(72785)
/** @type {import('http2')} */
let http2
try {
http2 = __nccwpck_require__(85158)
} catch {
// @ts-ignore
http2 = { constants: {} }
}
const {
constants: {
HTTP2_HEADER_AUTHORITY,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_CONTENT_LENGTH,
HTTP2_HEADER_EXPECT,
HTTP2_HEADER_STATUS
}
} = http2
// Experimental
let h2ExperimentalWarned = false
const FastBuffer = Buffer[Symbol.species]
const kClosedResolve = Symbol('kClosedResolve')
const channels = {}
try {
const diagnosticsChannel = __nccwpck_require__(67643)
channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
channels.connected = diagnosticsChannel.channel('undici:client:connected')
} catch {
channels.sendHeaders = { hasSubscribers: false }
channels.beforeConnect = { hasSubscribers: false }
channels.connectError = { hasSubscribers: false }
channels.connected = { hasSubscribers: false }
}
/**
* @type {import('../types/client').default}
*/
class Client extends DispatcherBase {
/**
*
* @param {string|URL} url
* @param {import('../types/client').Client.Options} options
*/
constructor (url, {
interceptors,
maxHeaderSize,
headersTimeout,
socketTimeout,
requestTimeout,
connectTimeout,
bodyTimeout,
idleTimeout,
keepAlive,
keepAliveTimeout,
maxKeepAliveTimeout,
keepAliveMaxTimeout,
keepAliveTimeoutThreshold,
socketPath,
pipelining,
tls,
strictContentLength,
maxCachedSessions,
maxRedirections,
connect,
maxRequestsPerClient,
localAddress,
maxResponseSize,
autoSelectFamily,
autoSelectFamilyAttemptTimeout,
// h2
allowH2,
maxConcurrentStreams
} = {}) {
super()
if (keepAlive !== undefined) {
throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
}
if (socketTimeout !== undefined) {
throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
}
if (requestTimeout !== undefined) {
throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
}
if (idleTimeout !== undefined) {
throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
}
if (maxKeepAliveTimeout !== undefined) {
throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
}
if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
throw new InvalidArgumentError('invalid maxHeaderSize')
}
if (socketPath != null && typeof socketPath !== 'string') {
throw new InvalidArgumentError('invalid socketPath')
}
if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
throw new InvalidArgumentError('invalid connectTimeout')
}
if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
throw new InvalidArgumentError('invalid keepAliveTimeout')
}
if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
}
if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
}
if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
}
if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
}
if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
throw new InvalidArgumentError('connect must be a function or an object')
}
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError('maxRedirections must be a positive number')
}
if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
}
if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
throw new InvalidArgumentError('localAddress must be valid string IP address')
}
if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
throw new InvalidArgumentError('maxResponseSize must be a positive number')
}
if (
autoSelectFamilyAttemptTimeout != null &&
(!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
) {
throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
}
// h2
if (allowH2 != null && typeof allowH2 !== 'boolean') {
throw new InvalidArgumentError('allowH2 must be a valid boolean value')
}
if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
}
if (typeof connect !== 'function') {
connect = buildConnector({
...tls,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
...connect
})
}
this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
? interceptors.Client
: [createRedirectInterceptor({ maxRedirections })]
this[kUrl] = util.parseOrigin(url)
this[kConnector] = connect
this[kSocket] = null
this[kPipelining] = pipelining != null ? pipelining : 1
this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
this[kServerName] = null
this[kLocalAddress] = localAddress != null ? localAddress : null
this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
this[kMaxRedirections] = maxRedirections
this[kMaxRequests] = maxRequestsPerClient
this[kClosedResolve] = null
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
this[kHTTPConnVersion] = 'h1'
// HTTP/2
this[kHTTP2Session] = null
this[kHTTP2SessionState] = !allowH2
? null
: {
// streams: null, // Fixed queue of streams - For future support of `push`
openStreams: 0, // Keep track of them to decide wether or not unref the session
maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
}
this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
// kQueue is built up of 3 sections separated by
// the kRunningIdx and kPendingIdx indices.
// | complete | running | pending |
// ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
// kRunningIdx points to the first running element.
// kPendingIdx points to the first pending element.
// This implements a fast queue with an amortized
// time of O(1).
this[kQueue] = []
this[kRunningIdx] = 0
this[kPendingIdx] = 0
}
get pipelining () {
return this[kPipelining]
}
set pipelining (value) {
this[kPipelining] = value
resume(this, true)
}
get [kPending] () {
return this[kQueue].length - this[kPendingIdx]
}
get [kRunning] () {
return this[kPendingIdx] - this[kRunningIdx]
}
get [kSize] () {
return this[kQueue].length - this[kRunningIdx]
}
get [kConnected] () {
return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
}
get [kBusy] () {
const socket = this[kSocket]
return (
(socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
(this[kSize] >= (this[kPipelining] || 1)) ||
this[kPending] > 0
)
}
/* istanbul ignore: only used for test */
[kConnect] (cb) {
connect(this)
this.once('connect', cb)
}
[kDispatch] (opts, handler) {
const origin = opts.origin || this[kUrl].origin
const request = this[kHTTPConnVersion] === 'h2'
? Request[kHTTP2BuildRequest](origin, opts, handler)
: Request[kHTTP1BuildRequest](origin, opts, handler)
this[kQueue].push(request)
if (this[kResuming]) {
// Do nothing.
} else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
// Wait a tick in case stream/iterator is ended in the same tick.
this[kResuming] = 1
process.nextTick(resume, this)
} else {
resume(this, true)
}
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
this[kNeedDrain] = 2
}
return this[kNeedDrain] < 2
}
async [kClose] () {
// TODO: for H2 we need to gracefully flush the remaining enqueued
// request and close each stream.
return new Promise((resolve) => {
if (!this[kSize]) {
resolve(null)
} else {
this[kClosedResolve] = resolve
}
})
}
async [kDestroy] (err) {
return new Promise((resolve) => {
const requests = this[kQueue].splice(this[kPendingIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
errorRequest(this, request, err)
}
const callback = () => {
if (this[kClosedResolve]) {
// TODO (fix): Should we error here with ClientDestroyedError?
this[kClosedResolve]()
this[kClosedResolve] = null
}
resolve()
}
if (this[kHTTP2Session] != null) {
util.destroy(this[kHTTP2Session], err)
this[kHTTP2Session] = null
this[kHTTP2SessionState] = null
}
if (!this[kSocket]) {
queueMicrotask(callback)
} else {
util.destroy(this[kSocket].on('close', callback), err)
}
resume(this)
})
}
}
function onHttp2SessionError (err) {
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
this[kSocket][kError] = err
onError(this[kClient], err)
}
function onHttp2FrameError (type, code, id) {
const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
if (id === 0) {
this[kSocket][kError] = err
onError(this[kClient], err)
}
}
function onHttp2SessionEnd () {
util.destroy(this, new SocketError('other side closed'))
util.destroy(this[kSocket], new SocketError('other side closed'))
}
function onHTTP2GoAway (code) {
const client = this[kClient]
const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
client[kSocket] = null
client[kHTTP2Session] = null
if (client.destroyed) {
assert(this[kPending] === 0)
// Fail entire queue.
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
errorRequest(this, request, err)
}
} else if (client[kRunning] > 0) {
// Fail head of pipeline.
const request = client[kQueue][client[kRunningIdx]]
client[kQueue][client[kRunningIdx]++] = null
errorRequest(client, request, err)
}
client[kPendingIdx] = client[kRunningIdx]
assert(client[kRunning] === 0)
client.emit('disconnect',
client[kUrl],
[client],
err
)
resume(client)
}
const constants = __nccwpck_require__(30953)
const createRedirectInterceptor = __nccwpck_require__(38861)
const EMPTY_BUF = Buffer.alloc(0)
async function lazyllhttp () {
const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(61145) : undefined
let mod
try {
mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(95627), 'base64'))
} catch (e) {
/* istanbul ignore next */
// We could check if the error was caused by the simd option not
// being enabled, but the occurring of this other error
// * https://github.com/emscripten-core/emscripten/issues/11495
// got me to remove that check to avoid breaking Node 12.
mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(61145), 'base64'))
}
return await WebAssembly.instantiate(mod, {
env: {
/* eslint-disable camelcase */
wasm_on_url: (p, at, len) => {
/* istanbul ignore next */
return 0
},
wasm_on_status: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p)
const start = at - currentBufferPtr + currentBufferRef.byteOffset
return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
},
wasm_on_message_begin: (p) => {
assert.strictEqual(currentParser.ptr, p)
return currentParser.onMessageBegin() || 0
},
wasm_on_header_field: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p)
const start = at - currentBufferPtr + currentBufferRef.byteOffset
return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
},
wasm_on_header_value: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p)
const start = at - currentBufferPtr + currentBufferRef.byteOffset
return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
},
wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
assert.strictEqual(currentParser.ptr, p)
return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
},
wasm_on_body: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p)
const start = at - currentBufferPtr + currentBufferRef.byteOffset
return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
},
wasm_on_message_complete: (p) => {
assert.strictEqual(currentParser.ptr, p)
return currentParser.onMessageComplete() || 0
}
/* eslint-enable camelcase */
}
})
}
let llhttpInstance = null
let llhttpPromise = lazyllhttp()
llhttpPromise.catch()
let currentParser = null
let currentBufferRef = null
let currentBufferSize = 0
let currentBufferPtr = null
const TIMEOUT_HEADERS = 1
const TIMEOUT_BODY = 2
const TIMEOUT_IDLE = 3
class Parser {
constructor (client, socket, { exports }) {
assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
this.llhttp = exports
this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
this.client = client
this.socket = socket
this.timeout = null
this.timeoutValue = null
this.timeoutType = null
this.statusCode = null
this.statusText = ''
this.upgrade = false
this.headers = []
this.headersSize = 0
this.headersMaxSize = client[kMaxHeadersSize]
this.shouldKeepAlive = false
this.paused = false
this.resume = this.resume.bind(this)
this.bytesRead = 0
this.keepAlive = ''
this.contentLength = ''
this.connection = ''
this.maxResponseSize = client[kMaxResponseSize]
}
setTimeout (value, type) {
this.timeoutType = type
if (value !== this.timeoutValue) {
timers.clearTimeout(this.timeout)
if (value) {
this.timeout = timers.setTimeout(onParserTimeout, value, this)
// istanbul ignore else: only for jest
if (this.timeout.unref) {
this.timeout.unref()
}
} else {
this.timeout = null
}
this.timeoutValue = value
} else if (this.timeout) {
// istanbul ignore else: only for jest
if (this.timeout.refresh) {
this.timeout.refresh()
}
}
}
resume () {
if (this.socket.destroyed || !this.paused) {
return
}
assert(this.ptr != null)
assert(currentParser == null)
this.llhttp.llhttp_resume(this.ptr)
assert(this.timeoutType === TIMEOUT_BODY)
if (this.timeout) {
// istanbul ignore else: only for jest
if (this.timeout.refresh) {
this.timeout.refresh()
}
}
this.paused = false
this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
this.readMore()
}
readMore () {
while (!this.paused && this.ptr) {
const chunk = this.socket.read()
if (chunk === null) {
break
}
this.execute(chunk)
}
}
execute (data) {
assert(this.ptr != null)
assert(currentParser == null)
assert(!this.paused)
const { socket, llhttp } = this
if (data.length > currentBufferSize) {
if (currentBufferPtr) {
llhttp.free(currentBufferPtr)
}
currentBufferSize = Math.ceil(data.length / 4096) * 4096
currentBufferPtr = llhttp.malloc(currentBufferSize)
}
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
// Call `execute` on the wasm parser.
// We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
// and finally the length of bytes to parse.
// The return value is an error code or `constants.ERROR.OK`.
try {
let ret
try {
currentBufferRef = data
currentParser = this
ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
/* eslint-disable-next-line no-useless-catch */
} catch (err) {
/* istanbul ignore next: difficult to make a test case for */
throw err
} finally {
currentParser = null
currentBufferRef = null
}
const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
if (ret === constants.ERROR.PAUSED_UPGRADE) {
this.onUpgrade(data.slice(offset))
} else if (ret === constants.ERROR.PAUSED) {
this.paused = true
socket.unshift(data.slice(offset))
} else if (ret !== constants.ERROR.OK) {
const ptr = llhttp.llhttp_get_error_reason(this.ptr)
let message = ''
/* istanbul ignore else: difficult to make a test case for */
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
message =
'Response does not match the HTTP/1.1 protocol (' +
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
')'
}
throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
}
} catch (err) {
util.destroy(socket, err)
}
}
destroy () {
assert(this.ptr != null)
assert(currentParser == null)
this.llhttp.llhttp_free(this.ptr)
this.ptr = null
timers.clearTimeout(this.timeout)
this.timeout = null
this.timeoutValue = null
this.timeoutType = null
this.paused = false
}
onStatus (buf) {
this.statusText = buf.toString()
}
onMessageBegin () {
const { socket, client } = this
/* istanbul ignore next: difficult to make a test case for */
if (socket.destroyed) {
return -1
}
const request = client[kQueue][client[kRunningIdx]]
if (!request) {
return -1
}
}
onHeaderField (buf) {
const len = this.headers.length
if ((len & 1) === 0) {
this.headers.push(buf)
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
}
this.trackHeader(buf.length)
}
onHeaderValue (buf) {
let len = this.headers.length
if ((len & 1) === 1) {
this.headers.push(buf)
len += 1
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
}
const key = this.headers[len - 2]
if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
this.keepAlive += buf.toString()
} else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
this.connection += buf.toString()
} else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
this.contentLength += buf.toString()
}
this.trackHeader(buf.length)
}
trackHeader (len) {
this.headersSize += len
if (this.headersSize >= this.headersMaxSize) {
util.destroy(this.socket, new HeadersOverflowError())
}
}
onUpgrade (head) {
const { upgrade, client, socket, headers, statusCode } = this
assert(upgrade)
const request = client[kQueue][client[kRunningIdx]]
assert(request)
assert(!socket.destroyed)
assert(socket === client[kSocket])
assert(!this.paused)
assert(request.upgrade || request.method === 'CONNECT')
this.statusCode = null
this.statusText = ''
this.shouldKeepAlive = null
assert(this.headers.length % 2 === 0)
this.headers = []
this.headersSize = 0
socket.unshift(head)
socket[kParser].destroy()
socket[kParser] = null
socket[kClient] = null
socket[kError] = null
socket
.removeListener('error', onSocketError)
.removeListener('readable', onSocketReadable)
.removeListener('end', onSocketEnd)
.removeListener('close', onSocketClose)
client[kSocket] = null
client[kQueue][client[kRunningIdx]++] = null
client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
try {
request.onUpgrade(statusCode, headers, socket)
} catch (err) {
util.destroy(socket, err)
}
resume(client)
}
onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
const { client, socket, headers, statusText } = this
/* istanbul ignore next: difficult to make a test case for */
if (socket.destroyed) {
return -1
}
const request = client[kQueue][client[kRunningIdx]]
/* istanbul ignore next: difficult to make a test case for */
if (!request) {
return -1
}
assert(!this.upgrade)
assert(this.statusCode < 200)
if (statusCode === 100) {
util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
return -1
}
/* this can only happen if server is misbehaving */
if (upgrade && !request.upgrade) {
util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
return -1
}
assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
this.statusCode = statusCode
this.shouldKeepAlive = (
shouldKeepAlive ||
// Override llhttp value which does not allow keepAlive for HEAD.
(request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
)
if (this.statusCode >= 200) {
const bodyTimeout = request.bodyTimeout != null
? request.bodyTimeout
: client[kBodyTimeout]
this.setTimeout(bodyTimeout, TIMEOUT_BODY)
} else if (this.timeout) {
// istanbul ignore else: only for jest
if (this.timeout.refresh) {
this.timeout.refresh()
}
}
if (request.method === 'CONNECT') {
assert(client[kRunning] === 1)
this.upgrade = true
return 2
}
if (upgrade) {
assert(client[kRunning] === 1)
this.upgrade = true
return 2
}
assert(this.headers.length % 2 === 0)
this.headers = []
this.headersSize = 0
if (this.shouldKeepAlive && client[kPipelining]) {
const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
if (keepAliveTimeout != null) {
const timeout = Math.min(
keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
client[kKeepAliveMaxTimeout]
)
if (timeout <= 0) {
socket[kReset] = true
} else {
client[kKeepAliveTimeoutValue] = timeout
}
} else {
client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
}
} else {
// Stop more requests from being dispatched.
socket[kReset] = true
}
const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
if (request.aborted) {
return -1
}
if (request.method === 'HEAD') {
return 1
}
if (statusCode < 200) {
return 1
}
if (socket[kBlocking]) {
socket[kBlocking] = false
resume(client)
}
return pause ? constants.ERROR.PAUSED : 0
}
onBody (buf) {
const { client, socket, statusCode, maxResponseSize } = this
if (socket.destroyed) {
return -1
}
const request = client[kQueue][client[kRunningIdx]]
assert(request)
assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
if (this.timeout) {
// istanbul ignore else: only for jest
if (this.timeout.refresh) {
this.timeout.refresh()
}
}
assert(statusCode >= 200)
if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
util.destroy(socket, new ResponseExceededMaxSizeError())
return -1
}
this.bytesRead += buf.length
if (request.onData(buf) === false) {
return constants.ERROR.PAUSED
}
}
onMessageComplete () {
const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
return -1
}
if (upgrade) {
return
}
const request = client[kQueue][client[kRunningIdx]]
assert(request)
assert(statusCode >= 100)
this.statusCode = null
this.statusText = ''
this.bytesRead = 0
this.contentLength = ''
this.keepAlive = ''
this.connection = ''
assert(this.headers.length % 2 === 0)
this.headers = []
this.headersSize = 0
if (statusCode < 200) {
return
}
/* istanbul ignore next: should be handled by llhttp? */
if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
util.destroy(socket, new ResponseContentLengthMismatchError())
return -1
}
request.onComplete(headers)
client[kQueue][client[kRunningIdx]++] = null
if (socket[kWriting]) {
assert.strictEqual(client[kRunning], 0)
// Response completed before request.
util.destroy(socket, new InformationalError('reset'))
return constants.ERROR.PAUSED
} else if (!shouldKeepAlive) {
util.destroy(socket, new InformationalError('reset'))
return constants.ERROR.PAUSED
} else if (socket[kReset] && client[kRunning] === 0) {
// Destroy socket once all requests have completed.
// The request at the tail of the pipeline is the one
// that requested reset and no further requests should
// have been queued since then.
util.destroy(socket, new InformationalError('reset'))
return constants.ERROR.PAUSED
} else if (client[kPipelining] === 1) {
// We must wait a full event loop cycle to reuse this socket to make sure
// that non-spec compliant servers are not closing the connection even if they
// said they won't.
setImmediate(resume, client)
} else {
resume(client)
}
}
}
function onParserTimeout (parser) {
const { socket, timeoutType, client } = parser
/* istanbul ignore else */
if (timeoutType === TIMEOUT_HEADERS) {
if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
assert(!parser.paused, 'cannot be paused while waiting for headers')
util.destroy(socket, new HeadersTimeoutError())
}
} else if (timeoutType === TIMEOUT_BODY) {
if (!parser.paused) {
util.destroy(socket, new BodyTimeoutError())
}
} else if (timeoutType === TIMEOUT_IDLE) {
assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
util.destroy(socket, new InformationalError('socket idle timeout'))
}
}
function onSocketReadable () {
const { [kParser]: parser } = this
if (parser) {
parser.readMore()
}
}
function onSocketError (err) {
const { [kClient]: client, [kParser]: parser } = this
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
if (client[kHTTPConnVersion] !== 'h2') {
// On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
// to the user.
if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so for as a valid response.
parser.onMessageComplete()
return
}
}
this[kError] = err
onError(this[kClient], err)
}
function onError (client, err) {
if (
client[kRunning] === 0 &&
err.code !== 'UND_ERR_INFO' &&
err.code !== 'UND_ERR_SOCKET'
) {
// Error is not caused by running request and not a recoverable
// socket error.
assert(client[kPendingIdx] === client[kRunningIdx])
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
errorRequest(client, request, err)
}
assert(client[kSize] === 0)
}
}
function onSocketEnd () {
const { [kParser]: parser, [kClient]: client } = this
if (client[kHTTPConnVersion] !== 'h2') {
if (parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so far as a valid response.
parser.onMessageComplete()
return
}
}
util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
}
function onSocketClose () {
const { [kClient]: client, [kParser]: parser } = this
if (client[kHTTPConnVersion] === 'h1' && parser) {
if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so far as a valid response.
parser.onMessageComplete()
}
this[kParser].destroy()
this[kParser] = null
}
const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
client[kSocket] = null
if (client.destroyed) {
assert(client[kPending] === 0)
// Fail entire queue.
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
errorRequest(client, request, err)
}
} else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
// Fail head of pipeline.
const request = client[kQueue][client[kRunningIdx]]
client[kQueue][client[kRunningIdx]++] = null
errorRequest(client, request, err)
}
client[kPendingIdx] = client[kRunningIdx]
assert(client[kRunning] === 0)
client.emit('disconnect', client[kUrl], [client], err)
resume(client)
}
async function connect (client) {
assert(!client[kConnecting])
assert(!client[kSocket])
let { host, hostname, protocol, port } = client[kUrl]
// Resolve ipv6
if (hostname[0] === '[') {
const idx = hostname.indexOf(']')
assert(idx !== -1)
const ip = hostname.substring(1, idx)
assert(net.isIP(ip))
hostname = ip
}
client[kConnecting] = true
if (channels.beforeConnect.hasSubscribers) {
channels.beforeConnect.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector]
})
}
try {
const socket = await new Promise((resolve, reject) => {
client[kConnector]({
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
}, (err, socket) => {
if (err) {
reject(err)
} else {
resolve(socket)
}
})
})
if (client.destroyed) {
util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
return
}
client[kConnecting] = false
assert(socket)
const isH2 = socket.alpnProtocol === 'h2'
if (isH2) {
if (!h2ExperimentalWarned) {
h2ExperimentalWarned = true
process.emitWarning('H2 support is experimental, expect them to change at any time.', {
code: 'UNDICI-H2'
})
}
const session = http2.connect(client[kUrl], {
createConnection: () => socket,
peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
})
client[kHTTPConnVersion] = 'h2'
session[kClient] = client
session[kSocket] = socket
session.on('error', onHttp2SessionError)
session.on('frameError', onHttp2FrameError)
session.on('end', onHttp2SessionEnd)
session.on('goaway', onHTTP2GoAway)
session.on('close', onSocketClose)
session.unref()
client[kHTTP2Session] = session
socket[kHTTP2Session] = session
} else {
if (!llhttpInstance) {
llhttpInstance = await llhttpPromise
llhttpPromise = null
}
socket[kNoRef] = false
socket[kWriting] = false
socket[kReset] = false
socket[kBlocking] = false
socket[kParser] = new Parser(client, socket, llhttpInstance)
}
socket[kCounter] = 0
socket[kMaxRequests] = client[kMaxRequests]
socket[kClient] = client
socket[kError] = null
socket
.on('error', onSocketError)
.on('readable', onSocketReadable)
.on('end', onSocketEnd)
.on('close', onSocketClose)
client[kSocket] = socket
if (channels.connected.hasSubscribers) {
channels.connected.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
socket
})
}
client.emit('connect', client[kUrl], [client])
} catch (err) {
if (client.destroyed) {
return
}
client[kConnecting] = false
if (channels.connectError.hasSubscribers) {
channels.connectError.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
error: err
})
}
if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
assert(client[kRunning] === 0)
while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
const request = client[kQueue][client[kPendingIdx]++]
errorRequest(client, request, err)
}
} else {
onError(client, err)
}
client.emit('connectionError', client[kUrl], [client], err)
}
resume(client)
}
function emitDrain (client) {
client[kNeedDrain] = 0
client.emit('drain', client[kUrl], [client])
}
function resume (client, sync) {
if (client[kResuming] === 2) {
return
}
client[kResuming] = 2
_resume(client, sync)
client[kResuming] = 0
if (client[kRunningIdx] > 256) {
client[kQueue].splice(0, client[kRunningIdx])
client[kPendingIdx] -= client[kRunningIdx]
client[kRunningIdx] = 0
}
}
function _resume (client, sync) {
while (true) {
if (client.destroyed) {
assert(client[kPending] === 0)
return
}
if (client[kClosedResolve] && !client[kSize]) {
client[kClosedResolve]()
client[kClosedResolve] = null
return
}
const socket = client[kSocket]
if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
if (client[kSize] === 0) {
if (!socket[kNoRef] && socket.unref) {
socket.unref()
socket[kNoRef] = true
}
} else if (socket[kNoRef] && socket.ref) {
socket.ref()
socket[kNoRef] = false
}
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
}
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
const request = client[kQueue][client[kRunningIdx]]
const headersTimeout = request.headersTimeout != null
? request.headersTimeout
: client[kHeadersTimeout]
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
}
}
}
if (client[kBusy]) {
client[kNeedDrain] = 2
} else if (client[kNeedDrain] === 2) {
if (sync) {
client[kNeedDrain] = 1
process.nextTick(emitDrain, client)
} else {
emitDrain(client)
}
continue
}
if (client[kPending] === 0) {
return
}
if (client[kRunning] >= (client[kPipelining] || 1)) {
return
}
const request = client[kQueue][client[kPendingIdx]]
if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
if (client[kRunning] > 0) {
return
}
client[kServerName] = request.servername
if (socket && socket.servername !== request.servername) {
util.destroy(socket, new InformationalError('servername changed'))
return
}
}
if (client[kConnecting]) {
return
}
if (!socket && !client[kHTTP2Session]) {
connect(client)
return
}
if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
return
}
if (client[kRunning] > 0 && !request.idempotent) {
// Non-idempotent request cannot be retried.
// Ensure that no other requests are inflight and
// could cause failure.
return
}
if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
// Don't dispatch an upgrade until all preceding requests have completed.
// A misbehaving server might upgrade the connection before all pipelined
// request has completed.
return
}
if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
(util.isStream(request.body) || util.isAsyncIterable(request.body))) {
// Request with stream or iterator body can error while other requests
// are inflight and indirectly error those as well.
// Ensure this doesn't happen by waiting for inflight
// to complete before dispatching.
// Request with stream or iterator body cannot be retried.
// Ensure that no other requests are inflight and
// could cause failure.
return
}
if (!request.aborted && write(client, request)) {
client[kPendingIdx]++
} else {
client[kQueue].splice(client[kPendingIdx], 1)
}
}
}
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
function shouldSendContentLength (method) {
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
}
function write (client, request) {
if (client[kHTTPConnVersion] === 'h2') {
writeH2(client, client[kHTTP2Session], request)
return
}
const { body, method, path, host, upgrade, headers, blocking, reset } = request
// https://tools.ietf.org/html/rfc7231#section-4.3.1
// https://tools.ietf.org/html/rfc7231#section-4.3.2
// https://tools.ietf.org/html/rfc7231#section-4.3.5
// Sending a payload body on a request that does not
// expect it can cause undefined behavior on some
// servers and corrupt connection state. Do not
// re-use the connection for further requests.
const expectsPayload = (
method === 'PUT' ||
method === 'POST' ||
method === 'PATCH'
)
if (body && typeof body.read === 'function') {
// Try to read EOF in order to get length.
body.read(0)
}
const bodyLength = util.bodyLength(body)
let contentLength = bodyLength
if (contentLength === null) {
contentLength = request.contentLength
}
if (contentLength === 0 && !expectsPayload) {
// https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD NOT send a Content-Length header field when
// the request message does not contain a payload body and the method
// semantics do not anticipate such a body.
contentLength = null
}
// https://github.com/nodejs/undici/issues/2046
// A user agent may send a Content-Length header with 0 value, this should be allowed.
if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
if (client[kStrictContentLength]) {
errorRequest(client, request, new RequestContentLengthMismatchError())
return false
}
process.emitWarning(new RequestContentLengthMismatchError())
}
const socket = client[kSocket]
try {
request.onConnect((err) => {
if (request.aborted || request.completed) {
return
}
errorRequest(client, request, err || new RequestAbortedError())
util.destroy(socket, new InformationalError('aborted'))
})
} catch (err) {
errorRequest(client, request, err)
}
if (request.aborted) {
return false
}
if (method === 'HEAD') {
// https://github.com/mcollina/undici/issues/258
// Close after a HEAD request to interop with misbehaving servers
// that may send a body in the response.
socket[kReset] = true
}
if (upgrade || method === 'CONNECT') {
// On CONNECT or upgrade, block pipeline from dispatching further
// requests on this connection.
socket[kReset] = true
}
if (reset != null) {
socket[kReset] = reset
}
if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
socket[kReset] = true
}
if (blocking) {
socket[kBlocking] = true
}
let header = `${method} ${path} HTTP/1.1\r\n`
if (typeof host === 'string') {
header += `host: ${host}\r\n`
} else {
header += client[kHostHeader]
}
if (upgrade) {
header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
} else if (client[kPipelining] && !socket[kReset]) {
header += 'connection: keep-alive\r\n'
} else {
header += 'connection: close\r\n'
}
if (headers) {
header += headers
}
if (channels.sendHeaders.hasSubscribers) {
channels.sendHeaders.publish({ request, headers: header, socket })
}
/* istanbul ignore else: assertion */
if (!body || bodyLength === 0) {
if (contentLength === 0) {
socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
} else {
assert(contentLength === null, 'no body must not have content length')
socket.write(`${header}\r\n`, 'latin1')
}
request.onRequestSent()
} else if (util.isBuffer(body)) {
assert(contentLength === body.byteLength, 'buffer body must have content length')
socket.cork()
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
socket.write(body)
socket.uncork()
request.onBodySent(body)
request.onRequestSent()
if (!expectsPayload) {
socket[kReset] = true
}
} else if (util.isBlobLike(body)) {
if (typeof body.stream === 'function') {
writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
} else {
writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
}
} else if (util.isStream(body)) {
writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
} else if (util.isIterable(body)) {
writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
} else {
assert(false)
}
return true
}
function writeH2 (client, session, request) {
const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
let headers
if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
else headers = reqHeaders
if (upgrade) {
errorRequest(client, request, new Error('Upgrade not supported for H2'))
return false
}
try {
// TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
request.onConnect((err) => {
if (request.aborted || request.completed) {
return
}
errorRequest(client, request, err || new RequestAbortedError())
})
} catch (err) {
errorRequest(client, request, err)
}
if (request.aborted) {
return false
}
/** @type {import('node:http2').ClientHttp2Stream} */
let stream
const h2State = client[kHTTP2SessionState]
headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
headers[HTTP2_HEADER_METHOD] = method
if (method === 'CONNECT') {
session.ref()
// we are already connected, streams are pending, first request
// will create a new stream. We trigger a request to create the stream and wait until
// `ready` event is triggered
// We disabled endStream to allow the user to write to the stream
stream = session.request(headers, { endStream: false, signal })
if (stream.id && !stream.pending) {
request.onUpgrade(null, null, stream)
++h2State.openStreams
} else {
stream.once('ready', () => {
request.onUpgrade(null, null, stream)
++h2State.openStreams
})
}
stream.once('close', () => {
h2State.openStreams -= 1
// TODO(HTTP/2): unref only if current streams count is 0
if (h2State.openStreams === 0) session.unref()
})
return true
}
// https://tools.ietf.org/html/rfc7540#section-8.3
// :path and :scheme headers must be omited when sending CONNECT
headers[HTTP2_HEADER_PATH] = path
headers[HTTP2_HEADER_SCHEME] = 'https'
// https://tools.ietf.org/html/rfc7231#section-4.3.1
// https://tools.ietf.org/html/rfc7231#section-4.3.2
// https://tools.ietf.org/html/rfc7231#section-4.3.5
// Sending a payload body on a request that does not
// expect it can cause undefined behavior on some
// servers and corrupt connection state. Do not
// re-use the connection for further requests.
const expectsPayload = (
method === 'PUT' ||
method === 'POST' ||
method === 'PATCH'
)
if (body && typeof body.read === 'function') {
// Try to read EOF in order to get length.
body.read(0)
}
let contentLength = util.bodyLength(body)
if (contentLength == null) {
contentLength = request.contentLength
}
if (contentLength === 0 || !expectsPayload) {
// https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD NOT send a Content-Length header field when
// the request message does not contain a payload body and the method
// semantics do not anticipate such a body.
contentLength = null
}
// https://github.com/nodejs/undici/issues/2046
// A user agent may send a Content-Length header with 0 value, this should be allowed.
if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
if (client[kStrictContentLength]) {
errorRequest(client, request, new RequestContentLengthMismatchError())
return false
}
process.emitWarning(new RequestContentLengthMismatchError())
}
if (contentLength != null) {
assert(body, 'no body must not have content length')
headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
}
session.ref()
const shouldEndStream = method === 'GET' || method === 'HEAD'
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = '100-continue'
stream = session.request(headers, { endStream: shouldEndStream, signal })
stream.once('continue', writeBodyH2)
} else {
stream = session.request(headers, {
endStream: shouldEndStream,
signal
})
writeBodyH2()
}
// Increment counter as we have new several streams open
++h2State.openStreams
stream.once('response', headers => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
stream.pause()
}
})
stream.once('end', () => {
request.onComplete([])
})
stream.on('data', (chunk) => {
if (request.onData(chunk) === false) {
stream.pause()
}
})
stream.once('close', () => {
h2State.openStreams -= 1
// TODO(HTTP/2): unref only if current streams count is 0
if (h2State.openStreams === 0) {
session.unref()
}
})
stream.once('error', function (err) {
if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
h2State.streams -= 1
util.destroy(stream, err)
}
})
stream.once('frameError', (type, code) => {
const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
errorRequest(client, request, err)
if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
h2State.streams -= 1
util.destroy(stream, err)
}
})
// stream.on('aborted', () => {
// // TODO(HTTP/2): Support aborted
// })
// stream.on('timeout', () => {
// // TODO(HTTP/2): Support timeout
// })
// stream.on('push', headers => {
// // TODO(HTTP/2): Suppor push
// })
// stream.on('trailers', headers => {
// // TODO(HTTP/2): Support trailers
// })
return true
function writeBodyH2 () {
/* istanbul ignore else: assertion */
if (!body) {
request.onRequestSent()
} else if (util.isBuffer(body)) {
assert(contentLength === body.byteLength, 'buffer body must have content length')
stream.cork()
stream.write(body)
stream.uncork()
stream.end()
request.onBodySent(body)
request.onRequestSent()
} else if (util.isBlobLike(body)) {
if (typeof body.stream === 'function') {
writeIterable({
client,
request,
contentLength,
h2stream: stream,
expectsPayload,
body: body.stream(),
socket: client[kSocket],
header: ''
})
} else {
writeBlob({
body,
client,
request,
contentLength,
expectsPayload,
h2stream: stream,
header: '',
socket: client[kSocket]
})
}
} else if (util.isStream(body)) {
writeStream({
body,
client,
request,
contentLength,
expectsPayload,
socket: client[kSocket],
h2stream: stream,
header: ''
})
} else if (util.isIterable(body)) {
writeIterable({
body,
client,
request,
contentLength,
expectsPayload,
header: '',
h2stream: stream,
socket: client[kSocket]
})
} else {
assert(false)
}
}
}
function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
if (client[kHTTPConnVersion] === 'h2') {
// For HTTP/2, is enough to pipe the stream
const pipe = pipeline(
body,
h2stream,
(err) => {
if (err) {
util.destroy(body, err)
util.destroy(h2stream, err)
} else {
request.onRequestSent()
}
}
)
pipe.on('data', onPipeData)
pipe.once('end', () => {
pipe.removeListener('data', onPipeData)
util.destroy(pipe)
})
function onPipeData (chunk) {
request.onBodySent(chunk)
}
return
}
let finished = false
const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
const onData = function (chunk) {
if (finished) {
return
}
try {
if (!writer.write(chunk) && this.pause) {
this.pause()
}
} catch (err) {
util.destroy(this, err)
}
}
const onDrain = function () {
if (finished) {
return
}
if (body.resume) {
body.resume()
}
}
const onAbort = function () {
if (finished) {
return
}
const err = new RequestAbortedError()
queueMicrotask(() => onFinished(err))
}
const onFinished = function (err) {
if (finished) {
return
}
finished = true
assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
socket
.off('drain', onDrain)
.off('error', onFinished)
body
.removeListener('data', onData)
.removeListener('end', onFinished)
.removeListener('error', onFinished)
.removeListener('close', onAbort)
if (!err) {
try {
writer.end()
} catch (er) {
err = er
}
}
writer.destroy(err)
if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
util.destroy(body, err)
} else {
util.destroy(body)
}
}
body
.on('data', onData)
.on('end', onFinished)
.on('error', onFinished)
.on('close', onAbort)
if (body.resume) {
body.resume()
}
socket
.on('drain', onDrain)
.on('error', onFinished)
}
async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength === body.size, 'blob body must have content length')
const isH2 = client[kHTTPConnVersion] === 'h2'
try {
if (contentLength != null && contentLength !== body.size) {
throw new RequestContentLengthMismatchError()
}
const buffer = Buffer.from(await body.arrayBuffer())
if (isH2) {
h2stream.cork()
h2stream.write(buffer)
h2stream.uncork()
} else {
socket.cork()
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
socket.write(buffer)
socket.uncork()
}
request.onBodySent(buffer)
request.onRequestSent()
if (!expectsPayload) {
socket[kReset] = true
}
resume(client)
} catch (err) {
util.destroy(isH2 ? h2stream : socket, err)
}
}
async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
let callback = null
function onDrain () {
if (callback) {
const cb = callback
callback = null
cb()
}
}
const waitForDrain = () => new Promise((resolve, reject) => {
assert(callback === null)
if (socket[kError]) {
reject(socket[kError])
} else {
callback = resolve
}
})
if (client[kHTTPConnVersion] === 'h2') {
h2stream
.on('close', onDrain)
.on('drain', onDrain)
try {
// It's up to the user to somehow abort the async iterable.
for await (const chunk of body) {
if (socket[kError]) {
throw socket[kError]
}
const res = h2stream.write(chunk)
request.onBodySent(chunk)
if (!res) {
await waitForDrain()
}
}
} catch (err) {
h2stream.destroy(err)
} finally {
request.onRequestSent()
h2stream.end()
h2stream
.off('close', onDrain)
.off('drain', onDrain)
}
return
}
socket
.on('close', onDrain)
.on('drain', onDrain)
const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
try {
// It's up to the user to somehow abort the async iterable.
for await (const chunk of body) {
if (socket[kError]) {
throw socket[kError]
}
if (!writer.write(chunk)) {
await waitForDrain()
}
}
writer.end()
} catch (err) {
writer.destroy(err)
} finally {
socket
.off('close', onDrain)
.off('drain', onDrain)
}
}
class AsyncWriter {
constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
this.socket = socket
this.request = request
this.contentLength = contentLength
this.client = client
this.bytesWritten = 0
this.expectsPayload = expectsPayload
this.header = header
socket[kWriting] = true
}
write (chunk) {
const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
if (socket[kError]) {
throw socket[kError]
}
if (socket.destroyed) {
return false
}
const len = Buffer.byteLength(chunk)
if (!len) {
return true
}
// We should defer writing chunks.
if (contentLength !== null && bytesWritten + len > contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError()
}
process.emitWarning(new RequestContentLengthMismatchError())
}
socket.cork()
if (bytesWritten === 0) {
if (!expectsPayload) {
socket[kReset] = true
}
if (contentLength === null) {
socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
} else {
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
}
}
if (contentLength === null) {
socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
}
this.bytesWritten += len
const ret = socket.write(chunk)
socket.uncork()
request.onBodySent(chunk)
if (!ret) {
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
// istanbul ignore else: only for jest
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh()
}
}
}
return ret
}
end () {
const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
request.onRequestSent()
socket[kWriting] = false
if (socket[kError]) {
throw socket[kError]
}
if (socket.destroyed) {
return
}
if (bytesWritten === 0) {
if (expectsPayload) {
// https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body.
socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
} else {
socket.write(`${header}\r\n`, 'latin1')
}
} else if (contentLength === null) {
socket.write('\r\n0\r\n\r\n', 'latin1')
}
if (contentLength !== null && bytesWritten !== contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError()
} else {
process.emitWarning(new RequestContentLengthMismatchError())
}
}
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
// istanbul ignore else: only for jest
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh()
}
}
resume(client)
}
destroy (err) {
const { socket, client } = this
socket[kWriting] = false
if (err) {
assert(client[kRunning] <= 1, 'pipeline should only contain this request')
util.destroy(socket, err)
}
}
}
function errorRequest (client, request, err) {
try {
request.onError(err)
assert(request.aborted)
} catch (err) {
client.emit('error', err)
}
}
module.exports = Client
/***/ }),
/***/ 56436:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* istanbul ignore file: only for Node 12 */
const { kConnected, kSize } = __nccwpck_require__(72785)
class CompatWeakRef {
constructor (value) {
this.value = value
}
deref () {
return this.value[kConnected] === 0 && this.value[kSize] === 0
? undefined
: this.value
}
}
class CompatFinalizer {
constructor (finalizer) {
this.finalizer = finalizer
}
register (dispatcher, key) {
if (dispatcher.on) {
dispatcher.on('disconnect', () => {
if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
this.finalizer(key)
}
})
}
}
}
module.exports = function () {
// FIXME: remove workaround when the Node bug is fixed
// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
if (process.env.NODE_V8_COVERAGE) {
return {
WeakRef: CompatWeakRef,
FinalizationRegistry: CompatFinalizer
}
}
return {
WeakRef: global.WeakRef || CompatWeakRef,
FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
}
}
/***/ }),
/***/ 20663:
/***/ ((module) => {
"use strict";
// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
const maxAttributeValueSize = 1024
// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
const maxNameValuePairSize = 4096
module.exports = {
maxAttributeValueSize,
maxNameValuePairSize
}
/***/ }),
/***/ 41724:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { parseSetCookie } = __nccwpck_require__(24408)
const { stringify, getHeadersList } = __nccwpck_require__(43121)
const { webidl } = __nccwpck_require__(21744)
const { Headers } = __nccwpck_require__(10554)
/**
* @typedef {Object} Cookie
* @property {string} name
* @property {string} value
* @property {Date|number|undefined} expires
* @property {number|undefined} maxAge
* @property {string|undefined} domain
* @property {string|undefined} path
* @property {boolean|undefined} secure
* @property {boolean|undefined} httpOnly
* @property {'Strict'|'Lax'|'None'} sameSite
* @property {string[]} unparsed
*/
/**
* @param {Headers} headers
* @returns {Record<string, string>}
*/
function getCookies (headers) {
webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
webidl.brandCheck(headers, Headers, { strict: false })
const cookie = headers.get('cookie')
const out = {}
if (!cookie) {
return out
}
for (const piece of cookie.split(';')) {
const [name, ...value] = piece.split('=')
out[name.trim()] = value.join('=')
}
return out
}
/**
* @param {Headers} headers
* @param {string} name
* @param {{ path?: string, domain?: string }|undefined} attributes
* @returns {void}
*/
function deleteCookie (headers, name, attributes) {
webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
webidl.brandCheck(headers, Headers, { strict: false })
name = webidl.converters.DOMString(name)
attributes = webidl.converters.DeleteCookieAttributes(attributes)
// Matches behavior of
// https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
setCookie(headers, {
name,
value: '',
expires: new Date(0),
...attributes
})
}
/**
* @param {Headers} headers
* @returns {Cookie[]}
*/
function getSetCookies (headers) {
webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
webidl.brandCheck(headers, Headers, { strict: false })
const cookies = getHeadersList(headers).cookies
if (!cookies) {
return []
}
// In older versions of undici, cookies is a list of name:value.
return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
}
/**
* @param {Headers} headers
* @param {Cookie} cookie
* @returns {void}
*/
function setCookie (headers, cookie) {
webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
webidl.brandCheck(headers, Headers, { strict: false })
cookie = webidl.converters.Cookie(cookie)
const str = stringify(cookie)
if (str) {
headers.append('Set-Cookie', stringify(cookie))
}
}
webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: 'path',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: 'domain',
defaultValue: null
}
])
webidl.converters.Cookie = webidl.dictionaryConverter([
{
converter: webidl.converters.DOMString,
key: 'name'
},
{
converter: webidl.converters.DOMString,
key: 'value'
},
{
converter: webidl.nullableConverter((value) => {
if (typeof value === 'number') {
return webidl.converters['unsigned long long'](value)
}
return new Date(value)
}),
key: 'expires',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters['long long']),
key: 'maxAge',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: 'domain',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: 'path',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters.boolean),
key: 'secure',
defaultValue: null
},
{
converter: webidl.nullableConverter(webidl.converters.boolean),
key: 'httpOnly',
defaultValue: null
},
{
converter: webidl.converters.USVString,
key: 'sameSite',
allowedValues: ['Strict', 'Lax', 'None']
},
{
converter: webidl.sequenceConverter(webidl.converters.DOMString),
key: 'unparsed',
defaultValue: []
}
])
module.exports = {
getCookies,
deleteCookie,
getSetCookies,
setCookie
}
/***/ }),
/***/ 24408:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(20663)
const { isCTLExcludingHtab } = __nccwpck_require__(43121)
const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685)
const assert = __nccwpck_require__(39491)
/**
* @description Parses the field-value attributes of a set-cookie header string.
* @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
* @param {string} header
* @returns if the header is invalid, null will be returned
*/
function parseSetCookie (header) {
// 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
// character (CTL characters excluding HTAB): Abort these steps and
// ignore the set-cookie-string entirely.
if (isCTLExcludingHtab(header)) {
return null
}
let nameValuePair = ''
let unparsedAttributes = ''
let name = ''
let value = ''
// 2. If the set-cookie-string contains a %x3B (";") character:
if (header.includes(';')) {
// 1. The name-value-pair string consists of the characters up to,
// but not including, the first %x3B (";"), and the unparsed-
// attributes consist of the remainder of the set-cookie-string
// (including the %x3B (";") in question).
const position = { position: 0 }
nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
unparsedAttributes = header.slice(position.position)
} else {
// Otherwise:
// 1. The name-value-pair string consists of all the characters
// contained in the set-cookie-string, and the unparsed-
// attributes is the empty string.
nameValuePair = header
}
// 3. If the name-value-pair string lacks a %x3D ("=") character, then
// the name string is empty, and the value string is the value of
// name-value-pair.
if (!nameValuePair.includes('=')) {
value = nameValuePair
} else {
// Otherwise, the name string consists of the characters up to, but
// not including, the first %x3D ("=") character, and the (possibly
// empty) value string consists of the characters after the first
// %x3D ("=") character.
const position = { position: 0 }
name = collectASequenceOfCodePointsFast(
'=',
nameValuePair,
position
)
value = nameValuePair.slice(position.position + 1)
}
// 4. Remove any leading or trailing WSP characters from the name
// string and the value string.
name = name.trim()
value = value.trim()
// 5. If the sum of the lengths of the name string and the value string
// is more than 4096 octets, abort these steps and ignore the set-
// cookie-string entirely.
if (name.length + value.length > maxNameValuePairSize) {
return null
}
// 6. The cookie-name is the name string, and the cookie-value is the
// value string.
return {
name, value, ...parseUnparsedAttributes(unparsedAttributes)
}
}
/**
* Parses the remaining attributes of a set-cookie header
* @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
* @param {string} unparsedAttributes
* @param {[Object.<string, unknown>]={}} cookieAttributeList
*/
function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
// 1. If the unparsed-attributes string is empty, skip the rest of
// these steps.
if (unparsedAttributes.length === 0) {
return cookieAttributeList
}
// 2. Discard the first character of the unparsed-attributes (which
// will be a %x3B (";") character).
assert(unparsedAttributes[0] === ';')
unparsedAttributes = unparsedAttributes.slice(1)
let cookieAv = ''
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
if (unparsedAttributes.includes(';')) {
// 1. Consume the characters of the unparsed-attributes up to, but
// not including, the first %x3B (";") character.
cookieAv = collectASequenceOfCodePointsFast(
';',
unparsedAttributes,
{ position: 0 }
)
unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
} else {
// Otherwise:
// 1. Consume the remainder of the unparsed-attributes.
cookieAv = unparsedAttributes
unparsedAttributes = ''
}
// Let the cookie-av string be the characters consumed in this step.
let attributeName = ''
let attributeValue = ''
// 4. If the cookie-av string contains a %x3D ("=") character:
if (cookieAv.includes('=')) {
// 1. The (possibly empty) attribute-name string consists of the
// characters up to, but not including, the first %x3D ("=")
// character, and the (possibly empty) attribute-value string
// consists of the characters after the first %x3D ("=")
// character.
const position = { position: 0 }
attributeName = collectASequenceOfCodePointsFast(
'=',
cookieAv,
position
)
attributeValue = cookieAv.slice(position.position + 1)
} else {
// Otherwise:
// 1. The attribute-name string consists of the entire cookie-av
// string, and the attribute-value string is empty.
attributeName = cookieAv
}
// 5. Remove any leading or trailing WSP characters from the attribute-
// name string and the attribute-value string.
attributeName = attributeName.trim()
attributeValue = attributeValue.trim()
// 6. If the attribute-value is longer than 1024 octets, ignore the
// cookie-av string and return to Step 1 of this algorithm.
if (attributeValue.length > maxAttributeValueSize) {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
// 7. Process the attribute-name and attribute-value according to the
// requirements in the following subsections. (Notice that
// attributes with unrecognized attribute-names are ignored.)
const attributeNameLowercase = attributeName.toLowerCase()
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
// If the attribute-name case-insensitively matches the string
// "Expires", the user agent MUST process the cookie-av as follows.
if (attributeNameLowercase === 'expires') {
// 1. Let the expiry-time be the result of parsing the attribute-value
// as cookie-date (see Section 5.1.1).
const expiryTime = new Date(attributeValue)
// 2. If the attribute-value failed to parse as a cookie date, ignore
// the cookie-av.
cookieAttributeList.expires = expiryTime
} else if (attributeNameLowercase === 'max-age') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
// If the attribute-name case-insensitively matches the string "Max-
// Age", the user agent MUST process the cookie-av as follows.
// 1. If the first character of the attribute-value is not a DIGIT or a
// "-" character, ignore the cookie-av.
const charCode = attributeValue.charCodeAt(0)
if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
// 2. If the remainder of attribute-value contains a non-DIGIT
// character, ignore the cookie-av.
if (!/^\d+$/.test(attributeValue)) {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
// 3. Let delta-seconds be the attribute-value converted to an integer.
const deltaSeconds = Number(attributeValue)
// 4. Let cookie-age-limit be the maximum age of the cookie (which
// SHOULD be 400 days or less, see Section 4.1.2.2).
// 5. Set delta-seconds to the smaller of its present value and cookie-
// age-limit.
// deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
// 6. If delta-seconds is less than or equal to zero (0), let expiry-
// time be the earliest representable date and time. Otherwise, let
// the expiry-time be the current date and time plus delta-seconds
// seconds.
// const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
// 7. Append an attribute to the cookie-attribute-list with an
// attribute-name of Max-Age and an attribute-value of expiry-time.
cookieAttributeList.maxAge = deltaSeconds
} else if (attributeNameLowercase === 'domain') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
// If the attribute-name case-insensitively matches the string "Domain",
// the user agent MUST process the cookie-av as follows.
// 1. Let cookie-domain be the attribute-value.
let cookieDomain = attributeValue
// 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
// cookie-domain without its leading %x2E (".").
if (cookieDomain[0] === '.') {
cookieDomain = cookieDomain.slice(1)
}
// 3. Convert the cookie-domain to lower case.
cookieDomain = cookieDomain.toLowerCase()
// 4. Append an attribute to the cookie-attribute-list with an
// attribute-name of Domain and an attribute-value of cookie-domain.
cookieAttributeList.domain = cookieDomain
} else if (attributeNameLowercase === 'path') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
// If the attribute-name case-insensitively matches the string "Path",
// the user agent MUST process the cookie-av as follows.
// 1. If the attribute-value is empty or if the first character of the
// attribute-value is not %x2F ("/"):
let cookiePath = ''
if (attributeValue.length === 0 || attributeValue[0] !== '/') {
// 1. Let cookie-path be the default-path.
cookiePath = '/'
} else {
// Otherwise:
// 1. Let cookie-path be the attribute-value.
cookiePath = attributeValue
}
// 2. Append an attribute to the cookie-attribute-list with an
// attribute-name of Path and an attribute-value of cookie-path.
cookieAttributeList.path = cookiePath
} else if (attributeNameLowercase === 'secure') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
// If the attribute-name case-insensitively matches the string "Secure",
// the user agent MUST append an attribute to the cookie-attribute-list
// with an attribute-name of Secure and an empty attribute-value.
cookieAttributeList.secure = true
} else if (attributeNameLowercase === 'httponly') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
// If the attribute-name case-insensitively matches the string
// "HttpOnly", the user agent MUST append an attribute to the cookie-
// attribute-list with an attribute-name of HttpOnly and an empty
// attribute-value.
cookieAttributeList.httpOnly = true
} else if (attributeNameLowercase === 'samesite') {
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
// If the attribute-name case-insensitively matches the string
// "SameSite", the user agent MUST process the cookie-av as follows:
// 1. Let enforcement be "Default".
let enforcement = 'Default'
const attributeValueLowercase = attributeValue.toLowerCase()
// 2. If cookie-av's attribute-value is a case-insensitive match for
// "None", set enforcement to "None".
if (attributeValueLowercase.includes('none')) {
enforcement = 'None'
}
// 3. If cookie-av's attribute-value is a case-insensitive match for
// "Strict", set enforcement to "Strict".
if (attributeValueLowercase.includes('strict')) {
enforcement = 'Strict'
}
// 4. If cookie-av's attribute-value is a case-insensitive match for
// "Lax", set enforcement to "Lax".
if (attributeValueLowercase.includes('lax')) {
enforcement = 'Lax'
}
// 5. Append an attribute to the cookie-attribute-list with an
// attribute-name of "SameSite" and an attribute-value of
// enforcement.
cookieAttributeList.sameSite = enforcement
} else {
cookieAttributeList.unparsed ??= []
cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
}
// 8. Return to Step 1 of this algorithm.
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
module.exports = {
parseSetCookie,
parseUnparsedAttributes
}
/***/ }),
/***/ 43121:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(39491)
const { kHeadersList } = __nccwpck_require__(72785)
function isCTLExcludingHtab (value) {
if (value.length === 0) {
return false
}
for (const char of value) {
const code = char.charCodeAt(0)
if (
(code >= 0x00 || code <= 0x08) ||
(code >= 0x0A || code <= 0x1F) ||
code === 0x7F
) {
return false
}
}
}
/**
CHAR = <any US-ASCII character (octets 0 - 127)>
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
* @param {string} name
*/
function validateCookieName (name) {
for (const char of name) {
const code = char.charCodeAt(0)
if (
(code <= 0x20 || code > 0x7F) ||
char === '(' ||
char === ')' ||
char === '>' ||
char === '<' ||
char === '@' ||
char === ',' ||
char === ';' ||
char === ':' ||
char === '\\' ||
char === '"' ||
char === '/' ||
char === '[' ||
char === ']' ||
char === '?' ||
char === '=' ||
char === '{' ||
char === '}'
) {
throw new Error('Invalid cookie name')
}
}
}
/**
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
* @param {string} value
*/
function validateCookieValue (value) {
for (const char of value) {
const code = char.charCodeAt(0)
if (
code < 0x21 || // exclude CTLs (0-31)
code === 0x22 ||
code === 0x2C ||
code === 0x3B ||
code === 0x5C ||
code > 0x7E // non-ascii
) {
throw new Error('Invalid header value')
}
}
}
/**
* path-value = <any CHAR except CTLs or ";">
* @param {string} path
*/
function validateCookiePath (path) {
for (const char of path) {
const code = char.charCodeAt(0)
if (code < 0x21 || char === ';') {
throw new Error('Invalid cookie path')
}
}
}
/**
* I have no idea why these values aren't allowed to be honest,
* but Deno tests these. - Khafra
* @param {string} domain
*/
function validateCookieDomain (domain) {
if (
domain.startsWith('-') ||
domain.endsWith('.') ||
domain.endsWith('-')
) {
throw new Error('Invalid cookie domain')
}
}
/**
* @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
* @param {number|Date} date
IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
; fixed length/zone/capitalization subset of the format
; see Section 3.3 of [RFC5322]
day-name = %x4D.6F.6E ; "Mon", case-sensitive
/ %x54.75.65 ; "Tue", case-sensitive
/ %x57.65.64 ; "Wed", case-sensitive
/ %x54.68.75 ; "Thu", case-sensitive
/ %x46.72.69 ; "Fri", case-sensitive
/ %x53.61.74 ; "Sat", case-sensitive
/ %x53.75.6E ; "Sun", case-sensitive
date1 = day SP month SP year
; e.g., 02 Jun 1982
day = 2DIGIT
month = %x4A.61.6E ; "Jan", case-sensitive
/ %x46.65.62 ; "Feb", case-sensitive
/ %x4D.61.72 ; "Mar", case-sensitive
/ %x41.70.72 ; "Apr", case-sensitive
/ %x4D.61.79 ; "May", case-sensitive
/ %x4A.75.6E ; "Jun", case-sensitive
/ %x4A.75.6C ; "Jul", case-sensitive
/ %x41.75.67 ; "Aug", case-sensitive
/ %x53.65.70 ; "Sep", case-sensitive
/ %x4F.63.74 ; "Oct", case-sensitive
/ %x4E.6F.76 ; "Nov", case-sensitive
/ %x44.65.63 ; "Dec", case-sensitive
year = 4DIGIT
GMT = %x47.4D.54 ; "GMT", case-sensitive
time-of-day = hour ":" minute ":" second
; 00:00:00 - 23:59:60 (leap second)
hour = 2DIGIT
minute = 2DIGIT
second = 2DIGIT
*/
function toIMFDate (date) {
if (typeof date === 'number') {
date = new Date(date)
}
const days = [
'Sun', 'Mon', 'Tue', 'Wed',
'Thu', 'Fri', 'Sat'
]
const months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
const dayName = days[date.getUTCDay()]
const day = date.getUTCDate().toString().padStart(2, '0')
const month = months[date.getUTCMonth()]
const year = date.getUTCFullYear()
const hour = date.getUTCHours().toString().padStart(2, '0')
const minute = date.getUTCMinutes().toString().padStart(2, '0')
const second = date.getUTCSeconds().toString().padStart(2, '0')
return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
}
/**
max-age-av = "Max-Age=" non-zero-digit *DIGIT
; In practice, both expires-av and max-age-av
; are limited to dates representable by the
; user agent.
* @param {number} maxAge
*/
function validateCookieMaxAge (maxAge) {
if (maxAge < 0) {
throw new Error('Invalid cookie max-age')
}
}
/**
* @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
* @param {import('./index').Cookie} cookie
*/
function stringify (cookie) {
if (cookie.name.length === 0) {
return null
}
validateCookieName(cookie.name)
validateCookieValue(cookie.value)
const out = [`${cookie.name}=${cookie.value}`]
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
if (cookie.name.startsWith('__Secure-')) {
cookie.secure = true
}
if (cookie.name.startsWith('__Host-')) {
cookie.secure = true
cookie.domain = null
cookie.path = '/'
}
if (cookie.secure) {
out.push('Secure')
}
if (cookie.httpOnly) {
out.push('HttpOnly')
}
if (typeof cookie.maxAge === 'number') {
validateCookieMaxAge(cookie.maxAge)
out.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.domain) {
validateCookieDomain(cookie.domain)
out.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
validateCookiePath(cookie.path)
out.push(`Path=${cookie.path}`)
}
if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
out.push(`Expires=${toIMFDate(cookie.expires)}`)
}
if (cookie.sameSite) {
out.push(`SameSite=${cookie.sameSite}`)
}
for (const part of cookie.unparsed) {
if (!part.includes('=')) {
throw new Error('Invalid unparsed')
}
const [key, ...value] = part.split('=')
out.push(`${key.trim()}=${value.join('=')}`)
}
return out.join('; ')
}
let kHeadersListNode
function getHeadersList (headers) {
if (headers[kHeadersList]) {
return headers[kHeadersList]
}
if (!kHeadersListNode) {
kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
(symbol) => symbol.description === 'headers list'
)
assert(kHeadersListNode, 'Headers cannot be parsed')
}
const headersList = headers[kHeadersListNode]
assert(headersList)
return headersList
}
module.exports = {
isCTLExcludingHtab,
stringify,
getHeadersList
}
/***/ }),
/***/ 82067:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const net = __nccwpck_require__(41808)
const assert = __nccwpck_require__(39491)
const util = __nccwpck_require__(83983)
const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(48045)
let tls // include tls conditionally since it is not always available
// TODO: session re-use does not wait for the first
// connection to resolve the session and might therefore
// resolve the same servername multiple times even when
// re-use is enabled.
let SessionCache
// FIXME: remove workaround when the Node bug is fixed
// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
SessionCache = class WeakSessionCache {
constructor (maxCachedSessions) {
this._maxCachedSessions = maxCachedSessions
this._sessionCache = new Map()
this._sessionRegistry = new global.FinalizationRegistry((key) => {
if (this._sessionCache.size < this._maxCachedSessions) {
return
}
const ref = this._sessionCache.get(key)
if (ref !== undefined && ref.deref() === undefined) {
this._sessionCache.delete(key)
}
})
}
get (sessionKey) {
const ref = this._sessionCache.get(sessionKey)
return ref ? ref.deref() : null
}
set (sessionKey, session) {
if (this._maxCachedSessions === 0) {
return
}
this._sessionCache.set(sessionKey, new WeakRef(session))
this._sessionRegistry.register(session, sessionKey)
}
}
} else {
SessionCache = class SimpleSessionCache {
constructor (maxCachedSessions) {
this._maxCachedSessions = maxCachedSessions
this._sessionCache = new Map()
}
get (sessionKey) {
return this._sessionCache.get(sessionKey)
}
set (sessionKey, session) {
if (this._maxCachedSessions === 0) {
return
}
if (this._sessionCache.size >= this._maxCachedSessions) {
// remove the oldest session
const { value: oldestKey } = this._sessionCache.keys().next()
this._sessionCache.delete(oldestKey)
}
this._sessionCache.set(sessionKey, session)
}
}
}
function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
}
const options = { path: socketPath, ...opts }
const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
timeout = timeout == null ? 10e3 : timeout
allowH2 = allowH2 != null ? allowH2 : false
return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
let socket
if (protocol === 'https:') {
if (!tls) {
tls = __nccwpck_require__(24404)
}
servername = servername || options.servername || util.getServerName(host) || null
const sessionKey = servername || hostname
const session = sessionCache.get(sessionKey) || null
assert(sessionKey)
socket = tls.connect({
highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
...options,
servername,
session,
localAddress,
// TODO(HTTP/2): Add support for h2c
ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
socket: httpSocket, // upgrade socket connection
port: port || 443,
host: hostname
})
socket
.on('session', function (session) {
// TODO (fix): Can a session become invalid once established? Don't think so?
sessionCache.set(sessionKey, session)
})
} else {
assert(!httpSocket, 'httpSocket can only be sent on TLS update')
socket = net.connect({
highWaterMark: 64 * 1024, // Same as nodejs fs streams.
...options,
localAddress,
port: port || 80,
host: hostname
})
}
// Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
if (options.keepAlive == null || options.keepAlive) {
const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
socket.setKeepAlive(true, keepAliveInitialDelay)
}
const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
socket
.setNoDelay(true)
.once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
cancelTimeout()
if (callback) {
const cb = callback
callback = null
cb(null, this)
}
})
.on('error', function (err) {
cancelTimeout()
if (callback) {
const cb = callback
callback = null
cb(err)
}
})
return socket
}
}
function setupTimeout (onConnectTimeout, timeout) {
if (!timeout) {
return () => {}
}
let s1 = null
let s2 = null
const timeoutId = setTimeout(() => {
// setImmediate is added to make sure that we priotorise socket error events over timeouts
s1 = setImmediate(() => {
if (process.platform === 'win32') {
// Windows needs an extra setImmediate probably due to implementation differences in the socket logic
s2 = setImmediate(() => onConnectTimeout())
} else {
onConnectTimeout()
}
})
}, timeout)
return () => {
clearTimeout(timeoutId)
clearImmediate(s1)
clearImmediate(s2)
}
}
function onConnectTimeout (socket) {
util.destroy(socket, new ConnectTimeoutError())
}
module.exports = buildConnector
/***/ }),
/***/ 14462:
/***/ ((module) => {
"use strict";
/** @type {Record<string, string | undefined>} */
const headerNameLowerCasedRecord = {}
// https://developer.mozilla.org/docs/Web/HTTP/Headers
const wellknownHeaderNames = [
'Accept',
'Accept-Encoding',
'Accept-Language',
'Accept-Ranges',
'Access-Control-Allow-Credentials',
'Access-Control-Allow-Headers',
'Access-Control-Allow-Methods',
'Access-Control-Allow-Origin',
'Access-Control-Expose-Headers',
'Access-Control-Max-Age',
'Access-Control-Request-Headers',
'Access-Control-Request-Method',
'Age',
'Allow',
'Alt-Svc',
'Alt-Used',
'Authorization',
'Cache-Control',
'Clear-Site-Data',
'Connection',
'Content-Disposition',
'Content-Encoding',
'Content-Language',
'Content-Length',
'Content-Location',
'Content-Range',
'Content-Security-Policy',
'Content-Security-Policy-Report-Only',
'Content-Type',
'Cookie',
'Cross-Origin-Embedder-Policy',
'Cross-Origin-Opener-Policy',
'Cross-Origin-Resource-Policy',
'Date',
'Device-Memory',
'Downlink',
'ECT',
'ETag',
'Expect',
'Expect-CT',
'Expires',
'Forwarded',
'From',
'Host',
'If-Match',
'If-Modified-Since',
'If-None-Match',
'If-Range',
'If-Unmodified-Since',
'Keep-Alive',
'Last-Modified',
'Link',
'Location',
'Max-Forwards',
'Origin',
'Permissions-Policy',
'Pragma',
'Proxy-Authenticate',
'Proxy-Authorization',
'RTT',
'Range',
'Referer',
'Referrer-Policy',
'Refresh',
'Retry-After',
'Sec-WebSocket-Accept',
'Sec-WebSocket-Extensions',
'Sec-WebSocket-Key',
'Sec-WebSocket-Protocol',
'Sec-WebSocket-Version',
'Server',
'Server-Timing',
'Service-Worker-Allowed',
'Service-Worker-Navigation-Preload',
'Set-Cookie',
'SourceMap',
'Strict-Transport-Security',
'Supports-Loading-Mode',
'TE',
'Timing-Allow-Origin',
'Trailer',
'Transfer-Encoding',
'Upgrade',
'Upgrade-Insecure-Requests',
'User-Agent',
'Vary',
'Via',
'WWW-Authenticate',
'X-Content-Type-Options',
'X-DNS-Prefetch-Control',
'X-Frame-Options',
'X-Permitted-Cross-Domain-Policies',
'X-Powered-By',
'X-Requested-With',
'X-XSS-Protection'
]
for (let i = 0; i < wellknownHeaderNames.length; ++i) {
const key = wellknownHeaderNames[i]
const lowerCasedKey = key.toLowerCase()
headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
lowerCasedKey
}
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
Object.setPrototypeOf(headerNameLowerCasedRecord, null)
module.exports = {
wellknownHeaderNames,
headerNameLowerCasedRecord
}
/***/ }),
/***/ 48045:
/***/ ((module) => {
"use strict";
class UndiciError extends Error {
constructor (message) {
super(message)
this.name = 'UndiciError'
this.code = 'UND_ERR'
}
}
class ConnectTimeoutError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, ConnectTimeoutError)
this.name = 'ConnectTimeoutError'
this.message = message || 'Connect Timeout Error'
this.code = 'UND_ERR_CONNECT_TIMEOUT'
}
}
class HeadersTimeoutError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, HeadersTimeoutError)
this.name = 'HeadersTimeoutError'
this.message = message || 'Headers Timeout Error'
this.code = 'UND_ERR_HEADERS_TIMEOUT'
}
}
class HeadersOverflowError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, HeadersOverflowError)
this.name = 'HeadersOverflowError'
this.message = message || 'Headers Overflow Error'
this.code = 'UND_ERR_HEADERS_OVERFLOW'
}
}
class BodyTimeoutError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, BodyTimeoutError)
this.name = 'BodyTimeoutError'
this.message = message || 'Body Timeout Error'
this.code = 'UND_ERR_BODY_TIMEOUT'
}
}
class ResponseStatusCodeError extends UndiciError {
constructor (message, statusCode, headers, body) {
super(message)
Error.captureStackTrace(this, ResponseStatusCodeError)
this.name = 'ResponseStatusCodeError'
this.message = message || 'Response Status Code Error'
this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
this.body = body
this.status = statusCode
this.statusCode = statusCode
this.headers = headers
}
}
class InvalidArgumentError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, InvalidArgumentError)
this.name = 'InvalidArgumentError'
this.message = message || 'Invalid Argument Error'
this.code = 'UND_ERR_INVALID_ARG'
}
}
class InvalidReturnValueError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, InvalidReturnValueError)
this.name = 'InvalidReturnValueError'
this.message = message || 'Invalid Return Value Error'
this.code = 'UND_ERR_INVALID_RETURN_VALUE'
}
}
class RequestAbortedError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, RequestAbortedError)
this.name = 'AbortError'
this.message = message || 'Request aborted'
this.code = 'UND_ERR_ABORTED'
}
}
class InformationalError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, InformationalError)
this.name = 'InformationalError'
this.message = message || 'Request information'
this.code = 'UND_ERR_INFO'
}
}
class RequestContentLengthMismatchError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, RequestContentLengthMismatchError)
this.name = 'RequestContentLengthMismatchError'
this.message = message || 'Request body length does not match content-length header'
this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
}
}
class ResponseContentLengthMismatchError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, ResponseContentLengthMismatchError)
this.name = 'ResponseContentLengthMismatchError'
this.message = message || 'Response body length does not match content-length header'
this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
}
}
class ClientDestroyedError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, ClientDestroyedError)
this.name = 'ClientDestroyedError'
this.message = message || 'The client is destroyed'
this.code = 'UND_ERR_DESTROYED'
}
}
class ClientClosedError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, ClientClosedError)
this.name = 'ClientClosedError'
this.message = message || 'The client is closed'
this.code = 'UND_ERR_CLOSED'
}
}
class SocketError extends UndiciError {
constructor (message, socket) {
super(message)
Error.captureStackTrace(this, SocketError)
this.name = 'SocketError'
this.message = message || 'Socket error'
this.code = 'UND_ERR_SOCKET'
this.socket = socket
}
}
class NotSupportedError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, NotSupportedError)
this.name = 'NotSupportedError'
this.message = message || 'Not supported error'
this.code = 'UND_ERR_NOT_SUPPORTED'
}
}
class BalancedPoolMissingUpstreamError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, NotSupportedError)
this.name = 'MissingUpstreamError'
this.message = message || 'No upstream has been added to the BalancedPool'
this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
}
}
class HTTPParserError extends Error {
constructor (message, code, data) {
super(message)
Error.captureStackTrace(this, HTTPParserError)
this.name = 'HTTPParserError'
this.code = code ? `HPE_${code}` : undefined
this.data = data ? data.toString() : undefined
}
}
class ResponseExceededMaxSizeError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, ResponseExceededMaxSizeError)
this.name = 'ResponseExceededMaxSizeError'
this.message = message || 'Response content exceeded max size'
this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
}
}
class RequestRetryError extends UndiciError {
constructor (message, code, { headers, data }) {
super(message)
Error.captureStackTrace(this, RequestRetryError)
this.name = 'RequestRetryError'
this.message = message || 'Request retry error'
this.code = 'UND_ERR_REQ_RETRY'
this.statusCode = code
this.data = data
this.headers = headers
}
}
module.exports = {
HTTPParserError,
UndiciError,
HeadersTimeoutError,
HeadersOverflowError,
BodyTimeoutError,
RequestContentLengthMismatchError,
ConnectTimeoutError,
ResponseStatusCodeError,
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError,
ClientDestroyedError,
ClientClosedError,
InformationalError,
SocketError,
NotSupportedError,
ResponseContentLengthMismatchError,
BalancedPoolMissingUpstreamError,
ResponseExceededMaxSizeError,
RequestRetryError
}
/***/ }),
/***/ 62905:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
InvalidArgumentError,
NotSupportedError
} = __nccwpck_require__(48045)
const assert = __nccwpck_require__(39491)
const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(72785)
const util = __nccwpck_require__(83983)
// tokenRegExp and headerCharRegex have been lifted from
// https://github.com/nodejs/node/blob/main/lib/_http_common.js
/**
* Verifies that the given val is a valid HTTP token
* per the rules defined in RFC 7230
* See https://tools.ietf.org/html/rfc7230#section-3.2.6
*/
const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
/**
* Matches if val contains an invalid field-vchar
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
*/
const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
// Verifies that a given path is valid does not contain control chars \x00 to \x20
const invalidPathRegex = /[^\u0021-\u00ff]/
const kHandler = Symbol('handler')
const channels = {}
let extractBody
try {
const diagnosticsChannel = __nccwpck_require__(67643)
channels.create = diagnosticsChannel.channel('undici:request:create')
channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
channels.headers = diagnosticsChannel.channel('undici:request:headers')
channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
channels.error = diagnosticsChannel.channel('undici:request:error')
} catch {
channels.create = { hasSubscribers: false }
channels.bodySent = { hasSubscribers: false }
channels.headers = { hasSubscribers: false }
channels.trailers = { hasSubscribers: false }
channels.error = { hasSubscribers: false }
}
class Request {
constructor (origin, {
path,
method,
body,
headers,
query,
idempotent,
blocking,
upgrade,
headersTimeout,
bodyTimeout,
reset,
throwOnError,
expectContinue
}, handler) {
if (typeof path !== 'string') {
throw new InvalidArgumentError('path must be a string')
} else if (
path[0] !== '/' &&
!(path.startsWith('http://') || path.startsWith('https://')) &&
method !== 'CONNECT'
) {
throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
} else if (invalidPathRegex.exec(path) !== null) {
throw new InvalidArgumentError('invalid request path')
}
if (typeof method !== 'string') {
throw new InvalidArgumentError('method must be a string')
} else if (tokenRegExp.exec(method) === null) {
throw new InvalidArgumentError('invalid request method')
}
if (upgrade && typeof upgrade !== 'string') {
throw new InvalidArgumentError('upgrade must be a string')
}
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError('invalid headersTimeout')
}
if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError('invalid bodyTimeout')
}
if (reset != null && typeof reset !== 'boolean') {
throw new InvalidArgumentError('invalid reset')
}
if (expectContinue != null && typeof expectContinue !== 'boolean') {
throw new InvalidArgumentError('invalid expectContinue')
}
this.headersTimeout = headersTimeout
this.bodyTimeout = bodyTimeout
this.throwOnError = throwOnError === true
this.method = method
this.abort = null
if (body == null) {
this.body = null
} else if (util.isStream(body)) {
this.body = body
const rState = this.body._readableState
if (!rState || !rState.autoDestroy) {
this.endHandler = function autoDestroy () {
util.destroy(this)
}
this.body.on('end', this.endHandler)
}
this.errorHandler = err => {
if (this.abort) {
this.abort(err)
} else {
this.error = err
}
}
this.body.on('error', this.errorHandler)
} else if (util.isBuffer(body)) {
this.body = body.byteLength ? body : null
} else if (ArrayBuffer.isView(body)) {
this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
} else if (body instanceof ArrayBuffer) {
this.body = body.byteLength ? Buffer.from(body) : null
} else if (typeof body === 'string') {
this.body = body.length ? Buffer.from(body) : null
} else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
this.body = body
} else {
throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
}
this.completed = false
this.aborted = false
this.upgrade = upgrade || null
this.path = query ? util.buildURL(path, query) : path
this.origin = origin
this.idempotent = idempotent == null
? method === 'HEAD' || method === 'GET'
: idempotent
this.blocking = blocking == null ? false : blocking
this.reset = reset == null ? null : reset
this.host = null
this.contentLength = null
this.contentType = null
this.headers = ''
// Only for H2
this.expectContinue = expectContinue != null ? expectContinue : false
if (Array.isArray(headers)) {
if (headers.length % 2 !== 0) {
throw new InvalidArgumentError('headers array must be even')
}
for (let i = 0; i < headers.length; i += 2) {
processHeader(this, headers[i], headers[i + 1])
}
} else if (headers && typeof headers === 'object') {
const keys = Object.keys(headers)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
processHeader(this, key, headers[key])
}
} else if (headers != null) {
throw new InvalidArgumentError('headers must be an object or an array')
}
if (util.isFormDataLike(this.body)) {
if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
}
if (!extractBody) {
extractBody = (__nccwpck_require__(41472).extractBody)
}
const [bodyStream, contentType] = extractBody(body)
if (this.contentType == null) {
this.contentType = contentType
this.headers += `content-type: ${contentType}\r\n`
}
this.body = bodyStream.stream
this.contentLength = bodyStream.length
} else if (util.isBlobLike(body) && this.contentType == null && body.type) {
this.contentType = body.type
this.headers += `content-type: ${body.type}\r\n`
}
util.validateHandler(handler, method, upgrade)
this.servername = util.getServerName(this.host)
this[kHandler] = handler
if (channels.create.hasSubscribers) {
channels.create.publish({ request: this })
}
}
onBodySent (chunk) {
if (this[kHandler].onBodySent) {
try {
return this[kHandler].onBodySent(chunk)
} catch (err) {
this.abort(err)
}
}
}
onRequestSent () {
if (channels.bodySent.hasSubscribers) {
channels.bodySent.publish({ request: this })
}
if (this[kHandler].onRequestSent) {
try {
return this[kHandler].onRequestSent()
} catch (err) {
this.abort(err)
}
}
}
onConnect (abort) {
assert(!this.aborted)
assert(!this.completed)
if (this.error) {
abort(this.error)
} else {
this.abort = abort
return this[kHandler].onConnect(abort)
}
}
onHeaders (statusCode, headers, resume, statusText) {
assert(!this.aborted)
assert(!this.completed)
if (channels.headers.hasSubscribers) {
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
}
try {
return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
} catch (err) {
this.abort(err)
}
}
onData (chunk) {
assert(!this.aborted)
assert(!this.completed)
try {
return this[kHandler].onData(chunk)
} catch (err) {
this.abort(err)
return false
}
}
onUpgrade (statusCode, headers, socket) {
assert(!this.aborted)
assert(!this.completed)
return this[kHandler].onUpgrade(statusCode, headers, socket)
}
onComplete (trailers) {
this.onFinally()
assert(!this.aborted)
this.completed = true
if (channels.trailers.hasSubscribers) {
channels.trailers.publish({ request: this, trailers })
}
try {
return this[kHandler].onComplete(trailers)
} catch (err) {
// TODO (fix): This might be a bad idea?
this.onError(err)
}
}
onError (error) {
this.onFinally()
if (channels.error.hasSubscribers) {
channels.error.publish({ request: this, error })
}
if (this.aborted) {
return
}
this.aborted = true
return this[kHandler].onError(error)
}
onFinally () {
if (this.errorHandler) {
this.body.off('error', this.errorHandler)
this.errorHandler = null
}
if (this.endHandler) {
this.body.off('end', this.endHandler)
this.endHandler = null
}
}
// TODO: adjust to support H2
addHeader (key, value) {
processHeader(this, key, value)
return this
}
static [kHTTP1BuildRequest] (origin, opts, handler) {
// TODO: Migrate header parsing here, to make Requests
// HTTP agnostic
return new Request(origin, opts, handler)
}
static [kHTTP2BuildRequest] (origin, opts, handler) {
const headers = opts.headers
opts = { ...opts, headers: null }
const request = new Request(origin, opts, handler)
request.headers = {}
if (Array.isArray(headers)) {
if (headers.length % 2 !== 0) {
throw new InvalidArgumentError('headers array must be even')
}
for (let i = 0; i < headers.length; i += 2) {
processHeader(request, headers[i], headers[i + 1], true)
}
} else if (headers && typeof headers === 'object') {
const keys = Object.keys(headers)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
processHeader(request, key, headers[key], true)
}
} else if (headers != null) {
throw new InvalidArgumentError('headers must be an object or an array')
}
return request
}
static [kHTTP2CopyHeaders] (raw) {
const rawHeaders = raw.split('\r\n')
const headers = {}
for (const header of rawHeaders) {
const [key, value] = header.split(': ')
if (value == null || value.length === 0) continue
if (headers[key]) headers[key] += `,${value}`
else headers[key] = value
}
return headers
}
}
function processHeaderValue (key, val, skipAppend) {
if (val && typeof val === 'object') {
throw new InvalidArgumentError(`invalid ${key} header`)
}
val = val != null ? `${val}` : ''
if (headerCharRegex.exec(val) !== null) {
throw new InvalidArgumentError(`invalid ${key} header`)
}
return skipAppend ? val : `${key}: ${val}\r\n`
}
function processHeader (request, key, val, skipAppend = false) {
if (val && (typeof val === 'object' && !Array.isArray(val))) {
throw new InvalidArgumentError(`invalid ${key} header`)
} else if (val === undefined) {
return
}
if (
request.host === null &&
key.length === 4 &&
key.toLowerCase() === 'host'
) {
if (headerCharRegex.exec(val) !== null) {
throw new InvalidArgumentError(`invalid ${key} header`)
}
// Consumed by Client
request.host = val
} else if (
request.contentLength === null &&
key.length === 14 &&
key.toLowerCase() === 'content-length'
) {
request.contentLength = parseInt(val, 10)
if (!Number.isFinite(request.contentLength)) {
throw new InvalidArgumentError('invalid content-length header')
}
} else if (
request.contentType === null &&
key.length === 12 &&
key.toLowerCase() === 'content-type'
) {
request.contentType = val
if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
else request.headers += processHeaderValue(key, val)
} else if (
key.length === 17 &&
key.toLowerCase() === 'transfer-encoding'
) {
throw new InvalidArgumentError('invalid transfer-encoding header')
} else if (
key.length === 10 &&
key.toLowerCase() === 'connection'
) {
const value = typeof val === 'string' ? val.toLowerCase() : null
if (value !== 'close' && value !== 'keep-alive') {
throw new InvalidArgumentError('invalid connection header')
} else if (value === 'close') {
request.reset = true
}
} else if (
key.length === 10 &&
key.toLowerCase() === 'keep-alive'
) {
throw new InvalidArgumentError('invalid keep-alive header')
} else if (
key.length === 7 &&
key.toLowerCase() === 'upgrade'
) {
throw new InvalidArgumentError('invalid upgrade header')
} else if (
key.length === 6 &&
key.toLowerCase() === 'expect'
) {
throw new NotSupportedError('expect header not supported')
} else if (tokenRegExp.exec(key) === null) {
throw new InvalidArgumentError('invalid header key')
} else {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
if (skipAppend) {
if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
} else {
request.headers += processHeaderValue(key, val[i])
}
}
} else {
if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
else request.headers += processHeaderValue(key, val)
}
}
}
module.exports = Request
/***/ }),
/***/ 72785:
/***/ ((module) => {
module.exports = {
kClose: Symbol('close'),
kDestroy: Symbol('destroy'),
kDispatch: Symbol('dispatch'),
kUrl: Symbol('url'),
kWriting: Symbol('writing'),
kResuming: Symbol('resuming'),
kQueue: Symbol('queue'),
kConnect: Symbol('connect'),
kConnecting: Symbol('connecting'),
kHeadersList: Symbol('headers list'),
kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
kKeepAlive: Symbol('keep alive'),
kHeadersTimeout: Symbol('headers timeout'),
kBodyTimeout: Symbol('body timeout'),
kServerName: Symbol('server name'),
kLocalAddress: Symbol('local address'),
kHost: Symbol('host'),
kNoRef: Symbol('no ref'),
kBodyUsed: Symbol('used'),
kRunning: Symbol('running'),
kBlocking: Symbol('blocking'),
kPending: Symbol('pending'),
kSize: Symbol('size'),
kBusy: Symbol('busy'),
kQueued: Symbol('queued'),
kFree: Symbol('free'),
kConnected: Symbol('connected'),
kClosed: Symbol('closed'),
kNeedDrain: Symbol('need drain'),
kReset: Symbol('reset'),
kDestroyed: Symbol.for('nodejs.stream.destroyed'),
kMaxHeadersSize: Symbol('max headers size'),
kRunningIdx: Symbol('running index'),
kPendingIdx: Symbol('pending index'),
kError: Symbol('error'),
kClients: Symbol('clients'),
kClient: Symbol('client'),
kParser: Symbol('parser'),
kOnDestroyed: Symbol('destroy callbacks'),
kPipelining: Symbol('pipelining'),
kSocket: Symbol('socket'),
kHostHeader: Symbol('host header'),
kConnector: Symbol('connector'),
kStrictContentLength: Symbol('strict content length'),
kMaxRedirections: Symbol('maxRedirections'),
kMaxRequests: Symbol('maxRequestsPerClient'),
kProxy: Symbol('proxy agent options'),
kCounter: Symbol('socket request counter'),
kInterceptors: Symbol('dispatch interceptors'),
kMaxResponseSize: Symbol('max response size'),
kHTTP2Session: Symbol('http2Session'),
kHTTP2SessionState: Symbol('http2Session state'),
kHTTP2BuildRequest: Symbol('http2 build request'),
kHTTP1BuildRequest: Symbol('http1 build request'),
kHTTP2CopyHeaders: Symbol('http2 copy headers'),
kHTTPConnVersion: Symbol('http connection version'),
kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
kConstruct: Symbol('constructable')
}
/***/ }),
/***/ 83983:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(39491)
const { kDestroyed, kBodyUsed } = __nccwpck_require__(72785)
const { IncomingMessage } = __nccwpck_require__(13685)
const stream = __nccwpck_require__(12781)
const net = __nccwpck_require__(41808)
const { InvalidArgumentError } = __nccwpck_require__(48045)
const { Blob } = __nccwpck_require__(14300)
const nodeUtil = __nccwpck_require__(73837)
const { stringify } = __nccwpck_require__(63477)
const { headerNameLowerCasedRecord } = __nccwpck_require__(14462)
const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
function nop () {}
function isStream (obj) {
return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
}
// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
function isBlobLike (object) {
return (Blob && object instanceof Blob) || (
object &&
typeof object === 'object' &&
(typeof object.stream === 'function' ||
typeof object.arrayBuffer === 'function') &&
/^(Blob|File)$/.test(object[Symbol.toStringTag])
)
}
function buildURL (url, queryParams) {
if (url.includes('?') || url.includes('#')) {
throw new Error('Query params cannot be passed when url already contains "?" or "#".')
}
const stringified = stringify(queryParams)
if (stringified) {
url += '?' + stringified
}
return url
}
function parseURL (url) {
if (typeof url === 'string') {
url = new URL(url)
if (!/^https?:/.test(url.origin || url.protocol)) {
throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
return url
}
if (!url || typeof url !== 'object') {
throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
}
if (!/^https?:/.test(url.origin || url.protocol)) {
throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
if (!(url instanceof URL)) {
if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
}
if (url.path != null && typeof url.path !== 'string') {
throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
}
if (url.pathname != null && typeof url.pathname !== 'string') {
throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
}
if (url.hostname != null && typeof url.hostname !== 'string') {
throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
}
if (url.origin != null && typeof url.origin !== 'string') {
throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
}
const port = url.port != null
? url.port
: (url.protocol === 'https:' ? 443 : 80)
let origin = url.origin != null
? url.origin
: `${url.protocol}//${url.hostname}:${port}`
let path = url.path != null
? url.path
: `${url.pathname || ''}${url.search || ''}`
if (origin.endsWith('/')) {
origin = origin.substring(0, origin.length - 1)
}
if (path && !path.startsWith('/')) {
path = `/${path}`
}
// new URL(path, origin) is unsafe when `path` contains an absolute URL
// From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
// If first parameter is a relative URL, second param is required, and will be used as the base URL.
// If first parameter is an absolute URL, a given second param will be ignored.
url = new URL(origin + path)
}
return url
}
function parseOrigin (url) {
url = parseURL(url)
if (url.pathname !== '/' || url.search || url.hash) {
throw new InvalidArgumentError('invalid url')
}
return url
}
function getHostname (host) {
if (host[0] === '[') {
const idx = host.indexOf(']')
assert(idx !== -1)
return host.substring(1, idx)
}
const idx = host.indexOf(':')
if (idx === -1) return host
return host.substring(0, idx)
}
// IP addresses are not valid server names per RFC6066
// > Currently, the only server names supported are DNS hostnames
function getServerName (host) {
if (!host) {
return null
}
assert.strictEqual(typeof host, 'string')
const servername = getHostname(host)
if (net.isIP(servername)) {
return ''
}
return servername
}
function deepClone (obj) {
return JSON.parse(JSON.stringify(obj))
}
function isAsyncIterable (obj) {
return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
}
function isIterable (obj) {
return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
}
function bodyLength (body) {
if (body == null) {
return 0
} else if (isStream(body)) {
const state = body._readableState
return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
? state.length
: null
} else if (isBlobLike(body)) {
return body.size != null ? body.size : null
} else if (isBuffer(body)) {
return body.byteLength
}
return null
}
function isDestroyed (stream) {
return !stream || !!(stream.destroyed || stream[kDestroyed])
}
function isReadableAborted (stream) {
const state = stream && stream._readableState
return isDestroyed(stream) && state && !state.endEmitted
}
function destroy (stream, err) {
if (stream == null || !isStream(stream) || isDestroyed(stream)) {
return
}
if (typeof stream.destroy === 'function') {
if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
// See: https://github.com/nodejs/node/pull/38505/files
stream.socket = null
}
stream.destroy(err)
} else if (err) {
process.nextTick((stream, err) => {
stream.emit('error', err)
}, stream, err)
}
if (stream.destroyed !== true) {
stream[kDestroyed] = true
}
}
const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
function parseKeepAliveTimeout (val) {
const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
return m ? parseInt(m[1], 10) * 1000 : null
}
/**
* Retrieves a header name and returns its lowercase value.
* @param {string | Buffer} value Header name
* @returns {string}
*/
function headerNameToString (value) {
return headerNameLowerCasedRecord[value] || value.toLowerCase()
}
function parseHeaders (headers, obj = {}) {
// For H2 support
if (!Array.isArray(headers)) return headers
for (let i = 0; i < headers.length; i += 2) {
const key = headers[i].toString().toLowerCase()
let val = obj[key]
if (!val) {
if (Array.isArray(headers[i + 1])) {
obj[key] = headers[i + 1].map(x => x.toString('utf8'))
} else {
obj[key] = headers[i + 1].toString('utf8')
}
} else {
if (!Array.isArray(val)) {
val = [val]
obj[key] = val
}
val.push(headers[i + 1].toString('utf8'))
}
}
// See https://github.com/nodejs/node/pull/46528
if ('content-length' in obj && 'content-disposition' in obj) {
obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
}
return obj
}
function parseRawHeaders (headers) {
const ret = []
let hasContentLength = false
let contentDispositionIdx = -1
for (let n = 0; n < headers.length; n += 2) {
const key = headers[n + 0].toString()
const val = headers[n + 1].toString('utf8')
if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
ret.push(key, val)
hasContentLength = true
} else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
contentDispositionIdx = ret.push(key, val) - 1
} else {
ret.push(key, val)
}
}
// See https://github.com/nodejs/node/pull/46528
if (hasContentLength && contentDispositionIdx !== -1) {
ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
}
return ret
}
function isBuffer (buffer) {
// See, https://github.com/mcollina/undici/pull/319
return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
}
function validateHandler (handler, method, upgrade) {
if (!handler || typeof handler !== 'object') {
throw new InvalidArgumentError('handler must be an object')
}
if (typeof handler.onConnect !== 'function') {
throw new InvalidArgumentError('invalid onConnect method')
}
if (typeof handler.onError !== 'function') {
throw new InvalidArgumentError('invalid onError method')
}
if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
throw new InvalidArgumentError('invalid onBodySent method')
}
if (upgrade || method === 'CONNECT') {
if (typeof handler.onUpgrade !== 'function') {
throw new InvalidArgumentError('invalid onUpgrade method')
}
} else {
if (typeof handler.onHeaders !== 'function') {
throw new InvalidArgumentError('invalid onHeaders method')
}
if (typeof handler.onData !== 'function') {
throw new InvalidArgumentError('invalid onData method')
}
if (typeof handler.onComplete !== 'function') {
throw new InvalidArgumentError('invalid onComplete method')
}
}
}
// A body is disturbed if it has been read from and it cannot
// be re-used without losing state or data.
function isDisturbed (body) {
return !!(body && (
stream.isDisturbed
? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
: body[kBodyUsed] ||
body.readableDidRead ||
(body._readableState && body._readableState.dataEmitted) ||
isReadableAborted(body)
))
}
function isErrored (body) {
return !!(body && (
stream.isErrored
? stream.isErrored(body)
: /state: 'errored'/.test(nodeUtil.inspect(body)
)))
}
function isReadable (body) {
return !!(body && (
stream.isReadable
? stream.isReadable(body)
: /state: 'readable'/.test(nodeUtil.inspect(body)
)))
}
function getSocketInfo (socket) {
return {
localAddress: socket.localAddress,
localPort: socket.localPort,
remoteAddress: socket.remoteAddress,
remotePort: socket.remotePort,
remoteFamily: socket.remoteFamily,
timeout: socket.timeout,
bytesWritten: socket.bytesWritten,
bytesRead: socket.bytesRead
}
}
async function * convertIterableToBuffer (iterable) {
for await (const chunk of iterable) {
yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
}
}
let ReadableStream
function ReadableStreamFrom (iterable) {
if (!ReadableStream) {
ReadableStream = (__nccwpck_require__(35356).ReadableStream)
}
if (ReadableStream.from) {
return ReadableStream.from(convertIterableToBuffer(iterable))
}
let iterator
return new ReadableStream(
{
async start () {
iterator = iterable[Symbol.asyncIterator]()
},
async pull (controller) {
const { done, value } = await iterator.next()
if (done) {
queueMicrotask(() => {
controller.close()
})
} else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
controller.enqueue(new Uint8Array(buf))
}
return controller.desiredSize > 0
},
async cancel (reason) {
await iterator.return()
}
},
0
)
}
// The chunk should be a FormData instance and contains
// all the required methods.
function isFormDataLike (object) {
return (
object &&
typeof object === 'object' &&
typeof object.append === 'function' &&
typeof object.delete === 'function' &&
typeof object.get === 'function' &&
typeof object.getAll === 'function' &&
typeof object.has === 'function' &&
typeof object.set === 'function' &&
object[Symbol.toStringTag] === 'FormData'
)
}
function throwIfAborted (signal) {
if (!signal) { return }
if (typeof signal.throwIfAborted === 'function') {
signal.throwIfAborted()
} else {
if (signal.aborted) {
// DOMException not available < v17.0.0
const err = new Error('The operation was aborted')
err.name = 'AbortError'
throw err
}
}
}
function addAbortListener (signal, listener) {
if ('addEventListener' in signal) {
signal.addEventListener('abort', listener, { once: true })
return () => signal.removeEventListener('abort', listener)
}
signal.addListener('abort', listener)
return () => signal.removeListener('abort', listener)
}
const hasToWellFormed = !!String.prototype.toWellFormed
/**
* @param {string} val
*/
function toUSVString (val) {
if (hasToWellFormed) {
return `${val}`.toWellFormed()
} else if (nodeUtil.toUSVString) {
return nodeUtil.toUSVString(val)
}
return `${val}`
}
// Parsed accordingly to RFC 9110
// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
function parseRangeHeader (range) {
if (range == null || range === '') return { start: 0, end: null, size: null }
const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
return m
? {
start: parseInt(m[1]),
end: m[2] ? parseInt(m[2]) : null,
size: m[3] ? parseInt(m[3]) : null
}
: null
}
const kEnumerableProperty = Object.create(null)
kEnumerableProperty.enumerable = true
module.exports = {
kEnumerableProperty,
nop,
isDisturbed,
isErrored,
isReadable,
toUSVString,
isReadableAborted,
isBlobLike,
parseOrigin,
parseURL,
getServerName,
isStream,
isIterable,
isAsyncIterable,
isDestroyed,
headerNameToString,
parseRawHeaders,
parseHeaders,
parseKeepAliveTimeout,
destroy,
bodyLength,
deepClone,
ReadableStreamFrom,
isBuffer,
validateHandler,
getSocketInfo,
isFormDataLike,
buildURL,
throwIfAborted,
addAbortListener,
parseRangeHeader,
nodeMajor,
nodeMinor,
nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
}
/***/ }),
/***/ 74839:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Dispatcher = __nccwpck_require__(60412)
const {
ClientDestroyedError,
ClientClosedError,
InvalidArgumentError
} = __nccwpck_require__(48045)
const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(72785)
const kDestroyed = Symbol('destroyed')
const kClosed = Symbol('closed')
const kOnDestroyed = Symbol('onDestroyed')
const kOnClosed = Symbol('onClosed')
const kInterceptedDispatch = Symbol('Intercepted Dispatch')
class DispatcherBase extends Dispatcher {
constructor () {
super()
this[kDestroyed] = false
this[kOnDestroyed] = null
this[kClosed] = false
this[kOnClosed] = []
}
get destroyed () {
return this[kDestroyed]
}
get closed () {
return this[kClosed]
}
get interceptors () {
return this[kInterceptors]
}
set interceptors (newInterceptors) {
if (newInterceptors) {
for (let i = newInterceptors.length - 1; i >= 0; i--) {
const interceptor = this[kInterceptors][i]
if (typeof interceptor !== 'function') {
throw new InvalidArgumentError('interceptor must be an function')
}
}
}
this[kInterceptors] = newInterceptors
}
close (callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
this.close((err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
if (this[kDestroyed]) {
queueMicrotask(() => callback(new ClientDestroyedError(), null))
return
}
if (this[kClosed]) {
if (this[kOnClosed]) {
this[kOnClosed].push(callback)
} else {
queueMicrotask(() => callback(null, null))
}
return
}
this[kClosed] = true
this[kOnClosed].push(callback)
const onClosed = () => {
const callbacks = this[kOnClosed]
this[kOnClosed] = null
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](null, null)
}
}
// Should not error.
this[kClose]()
.then(() => this.destroy())
.then(() => {
queueMicrotask(onClosed)
})
}
destroy (err, callback) {
if (typeof err === 'function') {
callback = err
err = null
}
if (callback === undefined) {
return new Promise((resolve, reject) => {
this.destroy(err, (err, data) => {
return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
})
})
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
if (this[kDestroyed]) {
if (this[kOnDestroyed]) {
this[kOnDestroyed].push(callback)
} else {
queueMicrotask(() => callback(null, null))
}
return
}
if (!err) {
err = new ClientDestroyedError()
}
this[kDestroyed] = true
this[kOnDestroyed] = this[kOnDestroyed] || []
this[kOnDestroyed].push(callback)
const onDestroyed = () => {
const callbacks = this[kOnDestroyed]
this[kOnDestroyed] = null
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](null, null)
}
}
// Should not error.
this[kDestroy](err).then(() => {
queueMicrotask(onDestroyed)
})
}
[kInterceptedDispatch] (opts, handler) {
if (!this[kInterceptors] || this[kInterceptors].length === 0) {
this[kInterceptedDispatch] = this[kDispatch]
return this[kDispatch](opts, handler)
}
let dispatch = this[kDispatch].bind(this)
for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
dispatch = this[kInterceptors][i](dispatch)
}
this[kInterceptedDispatch] = dispatch
return dispatch(opts, handler)
}
dispatch (opts, handler) {
if (!handler || typeof handler !== 'object') {
throw new InvalidArgumentError('handler must be an object')
}
try {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('opts must be an object.')
}
if (this[kDestroyed] || this[kOnDestroyed]) {
throw new ClientDestroyedError()
}
if (this[kClosed]) {
throw new ClientClosedError()
}
return this[kInterceptedDispatch](opts, handler)
} catch (err) {
if (typeof handler.onError !== 'function') {
throw new InvalidArgumentError('invalid onError method')
}
handler.onError(err)
return false
}
}
}
module.exports = DispatcherBase
/***/ }),
/***/ 60412:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const EventEmitter = __nccwpck_require__(82361)
class Dispatcher extends EventEmitter {
dispatch () {
throw new Error('not implemented')
}
close () {
throw new Error('not implemented')
}
destroy () {
throw new Error('not implemented')
}
}
module.exports = Dispatcher
/***/ }),
/***/ 41472:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Busboy = __nccwpck_require__(50727)
const util = __nccwpck_require__(83983)
const {
ReadableStreamFrom,
isBlobLike,
isReadableStreamLike,
readableStreamClose,
createDeferredPromise,
fullyReadBody
} = __nccwpck_require__(52538)
const { FormData } = __nccwpck_require__(72015)
const { kState } = __nccwpck_require__(15861)
const { webidl } = __nccwpck_require__(21744)
const { DOMException, structuredClone } = __nccwpck_require__(41037)
const { Blob, File: NativeFile } = __nccwpck_require__(14300)
const { kBodyUsed } = __nccwpck_require__(72785)
const assert = __nccwpck_require__(39491)
const { isErrored } = __nccwpck_require__(83983)
const { isUint8Array, isArrayBuffer } = __nccwpck_require__(29830)
const { File: UndiciFile } = __nccwpck_require__(78511)
const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685)
let ReadableStream = globalThis.ReadableStream
/** @type {globalThis['File']} */
const File = NativeFile ?? UndiciFile
const textEncoder = new TextEncoder()
const textDecoder = new TextDecoder()
// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
function extractBody (object, keepalive = false) {
if (!ReadableStream) {
ReadableStream = (__nccwpck_require__(35356).ReadableStream)
}
// 1. Let stream be null.
let stream = null
// 2. If object is a ReadableStream object, then set stream to object.
if (object instanceof ReadableStream) {
stream = object
} else if (isBlobLike(object)) {
// 3. Otherwise, if object is a Blob object, set stream to the
// result of running objects get stream.
stream = object.stream()
} else {
// 4. Otherwise, set stream to a new ReadableStream object, and set
// up stream.
stream = new ReadableStream({
async pull (controller) {
controller.enqueue(
typeof source === 'string' ? textEncoder.encode(source) : source
)
queueMicrotask(() => readableStreamClose(controller))
},
start () {},
type: undefined
})
}
// 5. Assert: stream is a ReadableStream object.
assert(isReadableStreamLike(stream))
// 6. Let action be null.
let action = null
// 7. Let source be null.
let source = null
// 8. Let length be null.
let length = null
// 9. Let type be null.
let type = null
// 10. Switch on object:
if (typeof object === 'string') {
// Set source to the UTF-8 encoding of object.
// Note: setting source to a Uint8Array here breaks some mocking assumptions.
source = object
// Set type to `text/plain;charset=UTF-8`.
type = 'text/plain;charset=UTF-8'
} else if (object instanceof URLSearchParams) {
// URLSearchParams
// spec says to run application/x-www-form-urlencoded on body.list
// this is implemented in Node.js as apart of an URLSearchParams instance toString method
// See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
// and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
// Set source to the result of running the application/x-www-form-urlencoded serializer with objects list.
source = object.toString()
// Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
type = 'application/x-www-form-urlencoded;charset=UTF-8'
} else if (isArrayBuffer(object)) {
// BufferSource/ArrayBuffer
// Set source to a copy of the bytes held by object.
source = new Uint8Array(object.slice())
} else if (ArrayBuffer.isView(object)) {
// BufferSource/ArrayBufferView
// Set source to a copy of the bytes held by object.
source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
} else if (util.isFormDataLike(object)) {
const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
const prefix = `--${boundary}\r\nContent-Disposition: form-data`
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
const escape = (str) =>
str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
// Set action to this step: run the multipart/form-data
// encoding algorithm, with objects entry list and UTF-8.
// - This ensures that the body is immutable and can't be changed afterwords
// - That the content-length is calculated in advance.
// - And that all parts are pre-encoded and ready to be sent.
const blobParts = []
const rn = new Uint8Array([13, 10]) // '\r\n'
length = 0
let hasUnknownSizeValue = false
for (const [name, value] of object) {
if (typeof value === 'string') {
const chunk = textEncoder.encode(prefix +
`; name="${escape(normalizeLinefeeds(name))}"` +
`\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
blobParts.push(chunk)
length += chunk.byteLength
} else {
const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
(value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
`Content-Type: ${
value.type || 'application/octet-stream'
}\r\n\r\n`)
blobParts.push(chunk, value, rn)
if (typeof value.size === 'number') {
length += chunk.byteLength + value.size + rn.byteLength
} else {
hasUnknownSizeValue = true
}
}
}
const chunk = textEncoder.encode(`--${boundary}--`)
blobParts.push(chunk)
length += chunk.byteLength
if (hasUnknownSizeValue) {
length = null
}
// Set source to object.
source = object
action = async function * () {
for (const part of blobParts) {
if (part.stream) {
yield * part.stream()
} else {
yield part
}
}
}
// Set type to `multipart/form-data; boundary=`,
// followed by the multipart/form-data boundary string generated
// by the multipart/form-data encoding algorithm.
type = 'multipart/form-data; boundary=' + boundary
} else if (isBlobLike(object)) {
// Blob
// Set source to object.
source = object
// Set length to objects size.
length = object.size
// If objects type attribute is not the empty byte sequence, set
// type to its value.
if (object.type) {
type = object.type
}
} else if (typeof object[Symbol.asyncIterator] === 'function') {
// If keepalive is true, then throw a TypeError.
if (keepalive) {
throw new TypeError('keepalive')
}
// If object is disturbed or locked, then throw a TypeError.
if (util.isDisturbed(object) || object.locked) {
throw new TypeError(
'Response body object should not be disturbed or locked'
)
}
stream =
object instanceof ReadableStream ? object : ReadableStreamFrom(object)
}
// 11. If source is a byte sequence, then set action to a
// step that returns source and length to sources length.
if (typeof source === 'string' || util.isBuffer(source)) {
length = Buffer.byteLength(source)
}
// 12. If action is non-null, then run these steps in in parallel:
if (action != null) {
// Run action.
let iterator
stream = new ReadableStream({
async start () {
iterator = action(object)[Symbol.asyncIterator]()
},
async pull (controller) {
const { value, done } = await iterator.next()
if (done) {
// When running action is done, close stream.
queueMicrotask(() => {
controller.close()
})
} else {
// Whenever one or more bytes are available and stream is not errored,
// enqueue a Uint8Array wrapping an ArrayBuffer containing the available
// bytes into stream.
if (!isErrored(stream)) {
controller.enqueue(new Uint8Array(value))
}
}
return controller.desiredSize > 0
},
async cancel (reason) {
await iterator.return()
},
type: undefined
})
}
// 13. Let body be a body whose stream is stream, source is source,
// and length is length.
const body = { stream, source, length }
// 14. Return (body, type).
return [body, type]
}
// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
function safelyExtractBody (object, keepalive = false) {
if (!ReadableStream) {
// istanbul ignore next
ReadableStream = (__nccwpck_require__(35356).ReadableStream)
}
// To safely extract a body and a `Content-Type` value from
// a byte sequence or BodyInit object object, run these steps:
// 1. If object is a ReadableStream object, then:
if (object instanceof ReadableStream) {
// Assert: object is neither disturbed nor locked.
// istanbul ignore next
assert(!util.isDisturbed(object), 'The body has already been consumed.')
// istanbul ignore next
assert(!object.locked, 'The stream is locked.')
}
// 2. Return the results of extracting object.
return extractBody(object, keepalive)
}
function cloneBody (body) {
// To clone a body body, run these steps:
// https://fetch.spec.whatwg.org/#concept-body-clone
// 1. Let « out1, out2 » be the result of teeing bodys stream.
const [out1, out2] = body.stream.tee()
const out2Clone = structuredClone(out2, { transfer: [out2] })
// This, for whatever reasons, unrefs out2Clone which allows
// the process to exit by itself.
const [, finalClone] = out2Clone.tee()
// 2. Set bodys stream to out1.
body.stream = out1
// 3. Return a body whose stream is out2 and other members are copied from body.
return {
stream: finalClone,
length: body.length,
source: body.source
}
}
async function * consumeBody (body) {
if (body) {
if (isUint8Array(body)) {
yield body
} else {
const stream = body.stream
if (util.isDisturbed(stream)) {
throw new TypeError('The body has already been consumed.')
}
if (stream.locked) {
throw new TypeError('The stream is locked.')
}
// Compat.
stream[kBodyUsed] = true
yield * stream
}
}
}
function throwIfAborted (state) {
if (state.aborted) {
throw new DOMException('The operation was aborted.', 'AbortError')
}
}
function bodyMixinMethods (instance) {
const methods = {
blob () {
// The blob() method steps are to return the result of
// running consume body with this and the following step
// given a byte sequence bytes: return a Blob whose
// contents are bytes and whose type attribute is thiss
// MIME type.
return specConsumeBody(this, (bytes) => {
let mimeType = bodyMimeType(this)
if (mimeType === 'failure') {
mimeType = ''
} else if (mimeType) {
mimeType = serializeAMimeType(mimeType)
}
// Return a Blob whose contents are bytes and type attribute
// is mimeType.
return new Blob([bytes], { type: mimeType })
}, instance)
},
arrayBuffer () {
// The arrayBuffer() method steps are to return the result
// of running consume body with this and the following step
// given a byte sequence bytes: return a new ArrayBuffer
// whose contents are bytes.
return specConsumeBody(this, (bytes) => {
return new Uint8Array(bytes).buffer
}, instance)
},
text () {
// The text() method steps are to return the result of running
// consume body with this and UTF-8 decode.
return specConsumeBody(this, utf8DecodeBytes, instance)
},
json () {
// The json() method steps are to return the result of running
// consume body with this and parse JSON from bytes.
return specConsumeBody(this, parseJSONFromBytes, instance)
},
async formData () {
webidl.brandCheck(this, instance)
throwIfAborted(this[kState])
const contentType = this.headers.get('Content-Type')
// If mimeTypes essence is "multipart/form-data", then:
if (/multipart\/form-data/.test(contentType)) {
const headers = {}
for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
const responseFormData = new FormData()
let busboy
try {
busboy = new Busboy({
headers,
preservePath: true
})
} catch (err) {
throw new DOMException(`${err}`, 'AbortError')
}
busboy.on('field', (name, value) => {
responseFormData.append(name, value)
})
busboy.on('file', (name, value, filename, encoding, mimeType) => {
const chunks = []
if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
let base64chunk = ''
value.on('data', (chunk) => {
base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
const end = base64chunk.length - base64chunk.length % 4
chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
base64chunk = base64chunk.slice(end)
})
value.on('end', () => {
chunks.push(Buffer.from(base64chunk, 'base64'))
responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
})
} else {
value.on('data', (chunk) => {
chunks.push(chunk)
})
value.on('end', () => {
responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
})
}
})
const busboyResolve = new Promise((resolve, reject) => {
busboy.on('finish', resolve)
busboy.on('error', (err) => reject(new TypeError(err)))
})
if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
busboy.end()
await busboyResolve
return responseFormData
} else if (/application\/x-www-form-urlencoded/.test(contentType)) {
// Otherwise, if mimeTypes essence is "application/x-www-form-urlencoded", then:
// 1. Let entries be the result of parsing bytes.
let entries
try {
let text = ''
// application/x-www-form-urlencoded parser will keep the BOM.
// https://url.spec.whatwg.org/#concept-urlencoded-parser
// Note that streaming decoder is stateful and cannot be reused
const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError('Expected Uint8Array chunk')
}
text += streamingDecoder.decode(chunk, { stream: true })
}
text += streamingDecoder.decode()
entries = new URLSearchParams(text)
} catch (err) {
// istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
// 2. If entries is failure, then throw a TypeError.
throw Object.assign(new TypeError(), { cause: err })
}
// 3. Return a new FormData object whose entries are entries.
const formData = new FormData()
for (const [name, value] of entries) {
formData.append(name, value)
}
return formData
} else {
// Wait a tick before checking if the request has been aborted.
// Otherwise, a TypeError can be thrown when an AbortError should.
await Promise.resolve()
throwIfAborted(this[kState])
// Otherwise, throw a TypeError.
throw webidl.errors.exception({
header: `${instance.name}.formData`,
message: 'Could not parse content as FormData.'
})
}
}
}
return methods
}
function mixinBody (prototype) {
Object.assign(prototype.prototype, bodyMixinMethods(prototype))
}
/**
* @see https://fetch.spec.whatwg.org/#concept-body-consume-body
* @param {Response|Request} object
* @param {(value: unknown) => unknown} convertBytesToJSValue
* @param {Response|Request} instance
*/
async function specConsumeBody (object, convertBytesToJSValue, instance) {
webidl.brandCheck(object, instance)
throwIfAborted(object[kState])
// 1. If object is unusable, then return a promise rejected
// with a TypeError.
if (bodyUnusable(object[kState].body)) {
throw new TypeError('Body is unusable')
}
// 2. Let promise be a new promise.
const promise = createDeferredPromise()
// 3. Let errorSteps given error be to reject promise with error.
const errorSteps = (error) => promise.reject(error)
// 4. Let successSteps given a byte sequence data be to resolve
// promise with the result of running convertBytesToJSValue
// with data. If that threw an exception, then run errorSteps
// with that exception.
const successSteps = (data) => {
try {
promise.resolve(convertBytesToJSValue(data))
} catch (e) {
errorSteps(e)
}
}
// 5. If objects body is null, then run successSteps with an
// empty byte sequence.
if (object[kState].body == null) {
successSteps(new Uint8Array())
return promise.promise
}
// 6. Otherwise, fully read objects body given successSteps,
// errorSteps, and objects relevant global object.
await fullyReadBody(object[kState].body, successSteps, errorSteps)
// 7. Return promise.
return promise.promise
}
// https://fetch.spec.whatwg.org/#body-unusable
function bodyUnusable (body) {
// An object including the Body interface mixin is
// said to be unusable if its body is non-null and
// its bodys stream is disturbed or locked.
return body != null && (body.stream.locked || util.isDisturbed(body.stream))
}
/**
* @see https://encoding.spec.whatwg.org/#utf-8-decode
* @param {Buffer} buffer
*/
function utf8DecodeBytes (buffer) {
if (buffer.length === 0) {
return ''
}
// 1. Let buffer be the result of peeking three bytes from
// ioQueue, converted to a byte sequence.
// 2. If buffer is 0xEF 0xBB 0xBF, then read three
// bytes from ioQueue. (Do nothing with those bytes.)
if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
buffer = buffer.subarray(3)
}
// 3. Process a queue with an instance of UTF-8s
// decoder, ioQueue, output, and "replacement".
const output = textDecoder.decode(buffer)
// 4. Return output.
return output
}
/**
* @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
* @param {Uint8Array} bytes
*/
function parseJSONFromBytes (bytes) {
return JSON.parse(utf8DecodeBytes(bytes))
}
/**
* @see https://fetch.spec.whatwg.org/#concept-body-mime-type
* @param {import('./response').Response|import('./request').Request} object
*/
function bodyMimeType (object) {
const { headersList } = object[kState]
const contentType = headersList.get('content-type')
if (contentType === null) {
return 'failure'
}
return parseMIMEType(contentType)
}
module.exports = {
extractBody,
safelyExtractBody,
cloneBody,
mixinBody
}
/***/ }),
/***/ 41037:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(71267)
const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
const nullBodyStatus = [101, 204, 205, 304]
const redirectStatus = [301, 302, 303, 307, 308]
const redirectStatusSet = new Set(redirectStatus)
// https://fetch.spec.whatwg.org/#block-bad-port
const badPorts = [
'1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
'87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
'139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
'540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
'2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
'10080'
]
const badPortsSet = new Set(badPorts)
// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
const referrerPolicy = [
'',
'no-referrer',
'no-referrer-when-downgrade',
'same-origin',
'origin',
'strict-origin',
'origin-when-cross-origin',
'strict-origin-when-cross-origin',
'unsafe-url'
]
const referrerPolicySet = new Set(referrerPolicy)
const requestRedirect = ['follow', 'manual', 'error']
const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
const safeMethodsSet = new Set(safeMethods)
const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
const requestCredentials = ['omit', 'same-origin', 'include']
const requestCache = [
'default',
'no-store',
'reload',
'no-cache',
'force-cache',
'only-if-cached'
]
// https://fetch.spec.whatwg.org/#request-body-header-name
const requestBodyHeader = [
'content-encoding',
'content-language',
'content-location',
'content-type',
// See https://github.com/nodejs/undici/issues/2021
// 'Content-Length' is a forbidden header name, which is typically
// removed in the Headers implementation. However, undici doesn't
// filter out headers, so we add it here.
'content-length'
]
// https://fetch.spec.whatwg.org/#enumdef-requestduplex
const requestDuplex = [
'half'
]
// http://fetch.spec.whatwg.org/#forbidden-method
const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
const forbiddenMethodsSet = new Set(forbiddenMethods)
const subresource = [
'audio',
'audioworklet',
'font',
'image',
'manifest',
'paintworklet',
'script',
'style',
'track',
'video',
'xslt',
''
]
const subresourceSet = new Set(subresource)
/** @type {globalThis['DOMException']} */
const DOMException = globalThis.DOMException ?? (() => {
// DOMException was only made a global in Node v17.0.0,
// but fetch supports >= v16.8.
try {
atob('~')
} catch (err) {
return Object.getPrototypeOf(err).constructor
}
})()
let channel
/** @type {globalThis['structuredClone']} */
const structuredClone =
globalThis.structuredClone ??
// https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
// structuredClone was added in v17.0.0, but fetch supports v16.8
function structuredClone (value, options = undefined) {
if (arguments.length === 0) {
throw new TypeError('missing argument')
}
if (!channel) {
channel = new MessageChannel()
}
channel.port1.unref()
channel.port2.unref()
channel.port1.postMessage(value, options?.transfer)
return receiveMessageOnPort(channel.port2).message
}
module.exports = {
DOMException,
structuredClone,
subresource,
forbiddenMethods,
requestBodyHeader,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache,
redirectStatus,
corsSafeListedMethods,
nullBodyStatus,
safeMethods,
badPorts,
requestDuplex,
subresourceSet,
badPortsSet,
redirectStatusSet,
corsSafeListedMethodsSet,
safeMethodsSet,
forbiddenMethodsSet,
referrerPolicySet
}
/***/ }),
/***/ 685:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const assert = __nccwpck_require__(39491)
const { atob } = __nccwpck_require__(14300)
const { isomorphicDecode } = __nccwpck_require__(52538)
const encoder = new TextEncoder()
/**
* @see https://mimesniff.spec.whatwg.org/#http-token-code-point
*/
const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
/**
* @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
*/
const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
// https://fetch.spec.whatwg.org/#data-url-processor
/** @param {URL} dataURL */
function dataURLProcessor (dataURL) {
// 1. Assert: dataURLs scheme is "data".
assert(dataURL.protocol === 'data:')
// 2. Let input be the result of running the URL
// serializer on dataURL with exclude fragment
// set to true.
let input = URLSerializer(dataURL, true)
// 3. Remove the leading "data:" string from input.
input = input.slice(5)
// 4. Let position point at the start of input.
const position = { position: 0 }
// 5. Let mimeType be the result of collecting a
// sequence of code points that are not equal
// to U+002C (,), given position.
let mimeType = collectASequenceOfCodePointsFast(
',',
input,
position
)
// 6. Strip leading and trailing ASCII whitespace
// from mimeType.
// Undici implementation note: we need to store the
// length because if the mimetype has spaces removed,
// the wrong amount will be sliced from the input in
// step #9
const mimeTypeLength = mimeType.length
mimeType = removeASCIIWhitespace(mimeType, true, true)
// 7. If position is past the end of input, then
// return failure
if (position.position >= input.length) {
return 'failure'
}
// 8. Advance position by 1.
position.position++
// 9. Let encodedBody be the remainder of input.
const encodedBody = input.slice(mimeTypeLength + 1)
// 10. Let body be the percent-decoding of encodedBody.
let body = stringPercentDecode(encodedBody)
// 11. If mimeType ends with U+003B (;), followed by
// zero or more U+0020 SPACE, followed by an ASCII
// case-insensitive match for "base64", then:
if (/;(\u0020){0,}base64$/i.test(mimeType)) {
// 1. Let stringBody be the isomorphic decode of body.
const stringBody = isomorphicDecode(body)
// 2. Set body to the forgiving-base64 decode of
// stringBody.
body = forgivingBase64(stringBody)
// 3. If body is failure, then return failure.
if (body === 'failure') {
return 'failure'
}
// 4. Remove the last 6 code points from mimeType.
mimeType = mimeType.slice(0, -6)
// 5. Remove trailing U+0020 SPACE code points from mimeType,
// if any.
mimeType = mimeType.replace(/(\u0020)+$/, '')
// 6. Remove the last U+003B (;) code point from mimeType.
mimeType = mimeType.slice(0, -1)
}
// 12. If mimeType starts with U+003B (;), then prepend
// "text/plain" to mimeType.
if (mimeType.startsWith(';')) {
mimeType = 'text/plain' + mimeType
}
// 13. Let mimeTypeRecord be the result of parsing
// mimeType.
let mimeTypeRecord = parseMIMEType(mimeType)
// 14. If mimeTypeRecord is failure, then set
// mimeTypeRecord to text/plain;charset=US-ASCII.
if (mimeTypeRecord === 'failure') {
mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
}
// 15. Return a new data: URL struct whose MIME
// type is mimeTypeRecord and body is body.
// https://fetch.spec.whatwg.org/#data-url-struct
return { mimeType: mimeTypeRecord, body }
}
// https://url.spec.whatwg.org/#concept-url-serializer
/**
* @param {URL} url
* @param {boolean} excludeFragment
*/
function URLSerializer (url, excludeFragment = false) {
if (!excludeFragment) {
return url.href
}
const href = url.href
const hashLength = url.hash.length
return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
}
// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
/**
* @param {(char: string) => boolean} condition
* @param {string} input
* @param {{ position: number }} position
*/
function collectASequenceOfCodePoints (condition, input, position) {
// 1. Let result be the empty string.
let result = ''
// 2. While position doesnt point past the end of input and the
// code point at position within input meets the condition condition:
while (position.position < input.length && condition(input[position.position])) {
// 1. Append that code point to the end of result.
result += input[position.position]
// 2. Advance position by 1.
position.position++
}
// 3. Return result.
return result
}
/**
* A faster collectASequenceOfCodePoints that only works when comparing a single character.
* @param {string} char
* @param {string} input
* @param {{ position: number }} position
*/
function collectASequenceOfCodePointsFast (char, input, position) {
const idx = input.indexOf(char, position.position)
const start = position.position
if (idx === -1) {
position.position = input.length
return input.slice(start)
}
position.position = idx
return input.slice(start, position.position)
}
// https://url.spec.whatwg.org/#string-percent-decode
/** @param {string} input */
function stringPercentDecode (input) {
// 1. Let bytes be the UTF-8 encoding of input.
const bytes = encoder.encode(input)
// 2. Return the percent-decoding of bytes.
return percentDecode(bytes)
}
// https://url.spec.whatwg.org/#percent-decode
/** @param {Uint8Array} input */
function percentDecode (input) {
// 1. Let output be an empty byte sequence.
/** @type {number[]} */
const output = []
// 2. For each byte byte in input:
for (let i = 0; i < input.length; i++) {
const byte = input[i]
// 1. If byte is not 0x25 (%), then append byte to output.
if (byte !== 0x25) {
output.push(byte)
// 2. Otherwise, if byte is 0x25 (%) and the next two bytes
// after byte in input are not in the ranges
// 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
// and 0x61 (a) to 0x66 (f), all inclusive, append byte
// to output.
} else if (
byte === 0x25 &&
!/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
) {
output.push(0x25)
// 3. Otherwise:
} else {
// 1. Let bytePoint be the two bytes after byte in input,
// decoded, and then interpreted as hexadecimal number.
const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
const bytePoint = Number.parseInt(nextTwoBytes, 16)
// 2. Append a byte whose value is bytePoint to output.
output.push(bytePoint)
// 3. Skip the next two bytes in input.
i += 2
}
}
// 3. Return output.
return Uint8Array.from(output)
}
// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
/** @param {string} input */
function parseMIMEType (input) {
// 1. Remove any leading and trailing HTTP whitespace
// from input.
input = removeHTTPWhitespace(input, true, true)
// 2. Let position be a position variable for input,
// initially pointing at the start of input.
const position = { position: 0 }
// 3. Let type be the result of collecting a sequence
// of code points that are not U+002F (/) from
// input, given position.
const type = collectASequenceOfCodePointsFast(
'/',
input,
position
)
// 4. If type is the empty string or does not solely
// contain HTTP token code points, then return failure.
// https://mimesniff.spec.whatwg.org/#http-token-code-point
if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
return 'failure'
}
// 5. If position is past the end of input, then return
// failure
if (position.position > input.length) {
return 'failure'
}
// 6. Advance position by 1. (This skips past U+002F (/).)
position.position++
// 7. Let subtype be the result of collecting a sequence of
// code points that are not U+003B (;) from input, given
// position.
let subtype = collectASequenceOfCodePointsFast(
';',
input,
position
)
// 8. Remove any trailing HTTP whitespace from subtype.
subtype = removeHTTPWhitespace(subtype, false, true)
// 9. If subtype is the empty string or does not solely
// contain HTTP token code points, then return failure.
if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
return 'failure'
}
const typeLowercase = type.toLowerCase()
const subtypeLowercase = subtype.toLowerCase()
// 10. Let mimeType be a new MIME type record whose type
// is type, in ASCII lowercase, and subtype is subtype,
// in ASCII lowercase.
// https://mimesniff.spec.whatwg.org/#mime-type
const mimeType = {
type: typeLowercase,
subtype: subtypeLowercase,
/** @type {Map<string, string>} */
parameters: new Map(),
// https://mimesniff.spec.whatwg.org/#mime-type-essence
essence: `${typeLowercase}/${subtypeLowercase}`
}
// 11. While position is not past the end of input:
while (position.position < input.length) {
// 1. Advance position by 1. (This skips past U+003B (;).)
position.position++
// 2. Collect a sequence of code points that are HTTP
// whitespace from input given position.
collectASequenceOfCodePoints(
// https://fetch.spec.whatwg.org/#http-whitespace
char => HTTP_WHITESPACE_REGEX.test(char),
input,
position
)
// 3. Let parameterName be the result of collecting a
// sequence of code points that are not U+003B (;)
// or U+003D (=) from input, given position.
let parameterName = collectASequenceOfCodePoints(
(char) => char !== ';' && char !== '=',
input,
position
)
// 4. Set parameterName to parameterName, in ASCII
// lowercase.
parameterName = parameterName.toLowerCase()
// 5. If position is not past the end of input, then:
if (position.position < input.length) {
// 1. If the code point at position within input is
// U+003B (;), then continue.
if (input[position.position] === ';') {
continue
}
// 2. Advance position by 1. (This skips past U+003D (=).)
position.position++
}
// 6. If position is past the end of input, then break.
if (position.position > input.length) {
break
}
// 7. Let parameterValue be null.
let parameterValue = null
// 8. If the code point at position within input is
// U+0022 ("), then:
if (input[position.position] === '"') {
// 1. Set parameterValue to the result of collecting
// an HTTP quoted string from input, given position
// and the extract-value flag.
parameterValue = collectAnHTTPQuotedString(input, position, true)
// 2. Collect a sequence of code points that are not
// U+003B (;) from input, given position.
collectASequenceOfCodePointsFast(
';',
input,
position
)
// 9. Otherwise:
} else {
// 1. Set parameterValue to the result of collecting
// a sequence of code points that are not U+003B (;)
// from input, given position.
parameterValue = collectASequenceOfCodePointsFast(
';',
input,
position
)
// 2. Remove any trailing HTTP whitespace from parameterValue.
parameterValue = removeHTTPWhitespace(parameterValue, false, true)
// 3. If parameterValue is the empty string, then continue.
if (parameterValue.length === 0) {
continue
}
}
// 10. If all of the following are true
// - parameterName is not the empty string
// - parameterName solely contains HTTP token code points
// - parameterValue solely contains HTTP quoted-string token code points
// - mimeTypes parameters[parameterName] does not exist
// then set mimeTypes parameters[parameterName] to parameterValue.
if (
parameterName.length !== 0 &&
HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
(parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
!mimeType.parameters.has(parameterName)
) {
mimeType.parameters.set(parameterName, parameterValue)
}
}
// 12. Return mimeType.
return mimeType
}
// https://infra.spec.whatwg.org/#forgiving-base64-decode
/** @param {string} data */
function forgivingBase64 (data) {
// 1. Remove all ASCII whitespace from data.
data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
// 2. If datas code point length divides by 4 leaving
// no remainder, then:
if (data.length % 4 === 0) {
// 1. If data ends with one or two U+003D (=) code points,
// then remove them from data.
data = data.replace(/=?=$/, '')
}
// 3. If datas code point length divides by 4 leaving
// a remainder of 1, then return failure.
if (data.length % 4 === 1) {
return 'failure'
}
// 4. If data contains a code point that is not one of
// U+002B (+)
// U+002F (/)
// ASCII alphanumeric
// then return failure.
if (/[^+/0-9A-Za-z]/.test(data)) {
return 'failure'
}
const binary = atob(data)
const bytes = new Uint8Array(binary.length)
for (let byte = 0; byte < binary.length; byte++) {
bytes[byte] = binary.charCodeAt(byte)
}
return bytes
}
// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
/**
* @param {string} input
* @param {{ position: number }} position
* @param {boolean?} extractValue
*/
function collectAnHTTPQuotedString (input, position, extractValue) {
// 1. Let positionStart be position.
const positionStart = position.position
// 2. Let value be the empty string.
let value = ''
// 3. Assert: the code point at position within input
// is U+0022 (").
assert(input[position.position] === '"')
// 4. Advance position by 1.
position.position++
// 5. While true:
while (true) {
// 1. Append the result of collecting a sequence of code points
// that are not U+0022 (") or U+005C (\) from input, given
// position, to value.
value += collectASequenceOfCodePoints(
(char) => char !== '"' && char !== '\\',
input,
position
)
// 2. If position is past the end of input, then break.
if (position.position >= input.length) {
break
}
// 3. Let quoteOrBackslash be the code point at position within
// input.
const quoteOrBackslash = input[position.position]
// 4. Advance position by 1.
position.position++
// 5. If quoteOrBackslash is U+005C (\), then:
if (quoteOrBackslash === '\\') {
// 1. If position is past the end of input, then append
// U+005C (\) to value and break.
if (position.position >= input.length) {
value += '\\'
break
}
// 2. Append the code point at position within input to value.
value += input[position.position]
// 3. Advance position by 1.
position.position++
// 6. Otherwise:
} else {
// 1. Assert: quoteOrBackslash is U+0022 (").
assert(quoteOrBackslash === '"')
// 2. Break.
break
}
}
// 6. If the extract-value flag is set, then return value.
if (extractValue) {
return value
}
// 7. Return the code points from positionStart to position,
// inclusive, within input.
return input.slice(positionStart, position.position)
}
/**
* @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
*/
function serializeAMimeType (mimeType) {
assert(mimeType !== 'failure')
const { parameters, essence } = mimeType
// 1. Let serialization be the concatenation of mimeTypes
// type, U+002F (/), and mimeTypes subtype.
let serialization = essence
// 2. For each name → value of mimeTypes parameters:
for (let [name, value] of parameters.entries()) {
// 1. Append U+003B (;) to serialization.
serialization += ';'
// 2. Append name to serialization.
serialization += name
// 3. Append U+003D (=) to serialization.
serialization += '='
// 4. If value does not solely contain HTTP token code
// points or value is the empty string, then:
if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
// 1. Precede each occurence of U+0022 (") or
// U+005C (\) in value with U+005C (\).
value = value.replace(/(\\|")/g, '\\$1')
// 2. Prepend U+0022 (") to value.
value = '"' + value
// 3. Append U+0022 (") to value.
value += '"'
}
// 5. Append value to serialization.
serialization += value
}
// 3. Return serialization.
return serialization
}
/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {string} char
*/
function isHTTPWhiteSpace (char) {
return char === '\r' || char === '\n' || char === '\t' || char === ' '
}
/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {string} str
*/
function removeHTTPWhitespace (str, leading = true, trailing = true) {
let lead = 0
let trail = str.length - 1
if (leading) {
for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
}
if (trailing) {
for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
}
return str.slice(lead, trail + 1)
}
/**
* @see https://infra.spec.whatwg.org/#ascii-whitespace
* @param {string} char
*/
function isASCIIWhitespace (char) {
return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
}
/**
* @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
*/
function removeASCIIWhitespace (str, leading = true, trailing = true) {
let lead = 0
let trail = str.length - 1
if (leading) {
for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
}
if (trailing) {
for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
}
return str.slice(lead, trail + 1)
}
module.exports = {
dataURLProcessor,
URLSerializer,
collectASequenceOfCodePoints,
collectASequenceOfCodePointsFast,
stringPercentDecode,
parseMIMEType,
collectAnHTTPQuotedString,
serializeAMimeType
}
/***/ }),
/***/ 78511:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { Blob, File: NativeFile } = __nccwpck_require__(14300)
const { types } = __nccwpck_require__(73837)
const { kState } = __nccwpck_require__(15861)
const { isBlobLike } = __nccwpck_require__(52538)
const { webidl } = __nccwpck_require__(21744)
const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685)
const { kEnumerableProperty } = __nccwpck_require__(83983)
const encoder = new TextEncoder()
class File extends Blob {
constructor (fileBits, fileName, options = {}) {
// The File constructor is invoked with two or three parameters, depending
// on whether the optional dictionary parameter is used. When the File()
// constructor is invoked, user agents must run the following steps:
webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
fileBits = webidl.converters['sequence<BlobPart>'](fileBits)
fileName = webidl.converters.USVString(fileName)
options = webidl.converters.FilePropertyBag(options)
// 1. Let bytes be the result of processing blob parts given fileBits and
// options.
// Note: Blob handles this for us
// 2. Let n be the fileName argument to the constructor.
const n = fileName
// 3. Process FilePropertyBag dictionary argument by running the following
// substeps:
// 1. If the type member is provided and is not the empty string, let t
// be set to the type dictionary member. If t contains any characters
// outside the range U+0020 to U+007E, then set t to the empty string
// and return from these substeps.
// 2. Convert every character in t to ASCII lowercase.
let t = options.type
let d
// eslint-disable-next-line no-labels
substep: {
if (t) {
t = parseMIMEType(t)
if (t === 'failure') {
t = ''
// eslint-disable-next-line no-labels
break substep
}
t = serializeAMimeType(t).toLowerCase()
}
// 3. If the lastModified member is provided, let d be set to the
// lastModified dictionary member. If it is not provided, set d to the
// current date and time represented as the number of milliseconds since
// the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
d = options.lastModified
}
// 4. Return a new File object F such that:
// F refers to the bytes byte sequence.
// F.size is set to the number of total bytes in bytes.
// F.name is set to n.
// F.type is set to t.
// F.lastModified is set to d.
super(processBlobParts(fileBits, options), { type: t })
this[kState] = {
name: n,
lastModified: d,
type: t
}
}
get name () {
webidl.brandCheck(this, File)
return this[kState].name
}
get lastModified () {
webidl.brandCheck(this, File)
return this[kState].lastModified
}
get type () {
webidl.brandCheck(this, File)
return this[kState].type
}
}
class FileLike {
constructor (blobLike, fileName, options = {}) {
// TODO: argument idl type check
// The File constructor is invoked with two or three parameters, depending
// on whether the optional dictionary parameter is used. When the File()
// constructor is invoked, user agents must run the following steps:
// 1. Let bytes be the result of processing blob parts given fileBits and
// options.
// 2. Let n be the fileName argument to the constructor.
const n = fileName
// 3. Process FilePropertyBag dictionary argument by running the following
// substeps:
// 1. If the type member is provided and is not the empty string, let t
// be set to the type dictionary member. If t contains any characters
// outside the range U+0020 to U+007E, then set t to the empty string
// and return from these substeps.
// TODO
const t = options.type
// 2. Convert every character in t to ASCII lowercase.
// TODO
// 3. If the lastModified member is provided, let d be set to the
// lastModified dictionary member. If it is not provided, set d to the
// current date and time represented as the number of milliseconds since
// the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
const d = options.lastModified ?? Date.now()
// 4. Return a new File object F such that:
// F refers to the bytes byte sequence.
// F.size is set to the number of total bytes in bytes.
// F.name is set to n.
// F.type is set to t.
// F.lastModified is set to d.
this[kState] = {
blobLike,
name: n,
type: t,
lastModified: d
}
}
stream (...args) {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.stream(...args)
}
arrayBuffer (...args) {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.arrayBuffer(...args)
}
slice (...args) {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.slice(...args)
}
text (...args) {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.text(...args)
}
get size () {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.size
}
get type () {
webidl.brandCheck(this, FileLike)
return this[kState].blobLike.type
}
get name () {
webidl.brandCheck(this, FileLike)
return this[kState].name
}
get lastModified () {
webidl.brandCheck(this, FileLike)
return this[kState].lastModified
}
get [Symbol.toStringTag] () {
return 'File'
}
}
Object.defineProperties(File.prototype, {
[Symbol.toStringTag]: {
value: 'File',
configurable: true
},
name: kEnumerableProperty,
lastModified: kEnumerableProperty
})
webidl.converters.Blob = webidl.interfaceConverter(Blob)
webidl.converters.BlobPart = function (V, opts) {
if (webidl.util.Type(V) === 'Object') {
if (isBlobLike(V)) {
return webidl.converters.Blob(V, { strict: false })
}
if (
ArrayBuffer.isView(V) ||
types.isAnyArrayBuffer(V)
) {
return webidl.converters.BufferSource(V, opts)
}
}
return webidl.converters.USVString(V, opts)
}
webidl.converters['sequence<BlobPart>'] = webidl.sequenceConverter(
webidl.converters.BlobPart
)
// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
{
key: 'lastModified',
converter: webidl.converters['long long'],
get defaultValue () {
return Date.now()
}
},
{
key: 'type',
converter: webidl.converters.DOMString,
defaultValue: ''
},
{
key: 'endings',
converter: (value) => {
value = webidl.converters.DOMString(value)
value = value.toLowerCase()
if (value !== 'native') {
value = 'transparent'
}
return value
},
defaultValue: 'transparent'
}
])
/**
* @see https://www.w3.org/TR/FileAPI/#process-blob-parts
* @param {(NodeJS.TypedArray|Blob|string)[]} parts
* @param {{ type: string, endings: string }} options
*/
function processBlobParts (parts, options) {
// 1. Let bytes be an empty sequence of bytes.
/** @type {NodeJS.TypedArray[]} */
const bytes = []
// 2. For each element in parts:
for (const element of parts) {
// 1. If element is a USVString, run the following substeps:
if (typeof element === 'string') {
// 1. Let s be element.
let s = element
// 2. If the endings member of options is "native", set s
// to the result of converting line endings to native
// of element.
if (options.endings === 'native') {
s = convertLineEndingsNative(s)
}
// 3. Append the result of UTF-8 encoding s to bytes.
bytes.push(encoder.encode(s))
} else if (
types.isAnyArrayBuffer(element) ||
types.isTypedArray(element)
) {
// 2. If element is a BufferSource, get a copy of the
// bytes held by the buffer source, and append those
// bytes to bytes.
if (!element.buffer) { // ArrayBuffer
bytes.push(new Uint8Array(element))
} else {
bytes.push(
new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
)
}
} else if (isBlobLike(element)) {
// 3. If element is a Blob, append the bytes it represents
// to bytes.
bytes.push(element)
}
}
// 3. Return bytes.
return bytes
}
/**
* @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
* @param {string} s
*/
function convertLineEndingsNative (s) {
// 1. Let native line ending be be the code point U+000A LF.
let nativeLineEnding = '\n'
// 2. If the underlying platforms conventions are to
// represent newlines as a carriage return and line feed
// sequence, set native line ending to the code point
// U+000D CR followed by the code point U+000A LF.
if (process.platform === 'win32') {
nativeLineEnding = '\r\n'
}
return s.replace(/\r?\n/g, nativeLineEnding)
}
// If this function is moved to ./util.js, some tools (such as
// rollup) will warn about circular dependencies. See:
// https://github.com/nodejs/undici/issues/1629
function isFileLike (object) {
return (
(NativeFile && object instanceof NativeFile) ||
object instanceof File || (
object &&
(typeof object.stream === 'function' ||
typeof object.arrayBuffer === 'function') &&
object[Symbol.toStringTag] === 'File'
)
)
}
module.exports = { File, FileLike, isFileLike }
/***/ }),
/***/ 72015:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(52538)
const { kState } = __nccwpck_require__(15861)
const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(78511)
const { webidl } = __nccwpck_require__(21744)
const { Blob, File: NativeFile } = __nccwpck_require__(14300)
/** @type {globalThis['File']} */
const File = NativeFile ?? UndiciFile
// https://xhr.spec.whatwg.org/#formdata
class FormData {
constructor (form) {
if (form !== undefined) {
throw webidl.errors.conversionFailed({
prefix: 'FormData constructor',
argument: 'Argument 1',
types: ['undefined']
})
}
this[kState] = []
}
append (name, value, filename = undefined) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
if (arguments.length === 3 && !isBlobLike(value)) {
throw new TypeError(
"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
)
}
// 1. Let value be value if given; otherwise blobValue.
name = webidl.converters.USVString(name)
value = isBlobLike(value)
? webidl.converters.Blob(value, { strict: false })
: webidl.converters.USVString(value)
filename = arguments.length === 3
? webidl.converters.USVString(filename)
: undefined
// 2. Let entry be the result of creating an entry with
// name, value, and filename if given.
const entry = makeEntry(name, value, filename)
// 3. Append entry to thiss entry list.
this[kState].push(entry)
}
delete (name) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
name = webidl.converters.USVString(name)
// The delete(name) method steps are to remove all entries whose name
// is name from thiss entry list.
this[kState] = this[kState].filter(entry => entry.name !== name)
}
get (name) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
name = webidl.converters.USVString(name)
// 1. If there is no entry whose name is name in thiss entry list,
// then return null.
const idx = this[kState].findIndex((entry) => entry.name === name)
if (idx === -1) {
return null
}
// 2. Return the value of the first entry whose name is name from
// thiss entry list.
return this[kState][idx].value
}
getAll (name) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
name = webidl.converters.USVString(name)
// 1. If there is no entry whose name is name in thiss entry list,
// then return the empty list.
// 2. Return the values of all entries whose name is name, in order,
// from thiss entry list.
return this[kState]
.filter((entry) => entry.name === name)
.map((entry) => entry.value)
}
has (name) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
name = webidl.converters.USVString(name)
// The has(name) method steps are to return true if there is an entry
// whose name is name in thiss entry list; otherwise false.
return this[kState].findIndex((entry) => entry.name === name) !== -1
}
set (name, value, filename = undefined) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
if (arguments.length === 3 && !isBlobLike(value)) {
throw new TypeError(
"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
)
}
// The set(name, value) and set(name, blobValue, filename) method steps
// are:
// 1. Let value be value if given; otherwise blobValue.
name = webidl.converters.USVString(name)
value = isBlobLike(value)
? webidl.converters.Blob(value, { strict: false })
: webidl.converters.USVString(value)
filename = arguments.length === 3
? toUSVString(filename)
: undefined
// 2. Let entry be the result of creating an entry with name, value, and
// filename if given.
const entry = makeEntry(name, value, filename)
// 3. If there are entries in thiss entry list whose name is name, then
// replace the first such entry with entry and remove the others.
const idx = this[kState].findIndex((entry) => entry.name === name)
if (idx !== -1) {
this[kState] = [
...this[kState].slice(0, idx),
entry,
...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
]
} else {
// 4. Otherwise, append entry to thiss entry list.
this[kState].push(entry)
}
}
entries () {
webidl.brandCheck(this, FormData)
return makeIterator(
() => this[kState].map(pair => [pair.name, pair.value]),
'FormData',
'key+value'
)
}
keys () {
webidl.brandCheck(this, FormData)
return makeIterator(
() => this[kState].map(pair => [pair.name, pair.value]),
'FormData',
'key'
)
}
values () {
webidl.brandCheck(this, FormData)
return makeIterator(
() => this[kState].map(pair => [pair.name, pair.value]),
'FormData',
'value'
)
}
/**
* @param {(value: string, key: string, self: FormData) => void} callbackFn
* @param {unknown} thisArg
*/
forEach (callbackFn, thisArg = globalThis) {
webidl.brandCheck(this, FormData)
webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
if (typeof callbackFn !== 'function') {
throw new TypeError(
"Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
)
}
for (const [key, value] of this) {
callbackFn.apply(thisArg, [value, key, this])
}
}
}
FormData.prototype[Symbol.iterator] = FormData.prototype.entries
Object.defineProperties(FormData.prototype, {
[Symbol.toStringTag]: {
value: 'FormData',
configurable: true
}
})
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
* @param {string} name
* @param {string|Blob} value
* @param {?string} filename
* @returns
*/
function makeEntry (name, value, filename) {
// 1. Set name to the result of converting name into a scalar value string.
// "To convert a string into a scalar value string, replace any surrogates
// with U+FFFD."
// see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
name = Buffer.from(name).toString('utf8')
// 2. If value is a string, then set value to the result of converting
// value into a scalar value string.
if (typeof value === 'string') {
value = Buffer.from(value).toString('utf8')
} else {
// 3. Otherwise:
// 1. If value is not a File object, then set value to a new File object,
// representing the same bytes, whose name attribute value is "blob"
if (!isFileLike(value)) {
value = value instanceof Blob
? new File([value], 'blob', { type: value.type })
: new FileLike(value, 'blob', { type: value.type })
}
// 2. If filename is given, then set value to a new File object,
// representing the same bytes, whose name attribute is filename.
if (filename !== undefined) {
/** @type {FilePropertyBag} */
const options = {
type: value.type,
lastModified: value.lastModified
}
value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
? new File([value], filename, options)
: new FileLike(value, filename, options)
}
}
// 4. Return an entry whose name is name and whose value is value.
return { name, value }
}
module.exports = { FormData }
/***/ }),
/***/ 71246:
/***/ ((module) => {
"use strict";
// In case of breaking changes, increase the version
// number to avoid conflicts.
const globalOrigin = Symbol.for('undici.globalOrigin.1')
function getGlobalOrigin () {
return globalThis[globalOrigin]
}
function setGlobalOrigin (newOrigin) {
if (newOrigin === undefined) {
Object.defineProperty(globalThis, globalOrigin, {
value: undefined,
writable: true,
enumerable: false,
configurable: false
})
return
}
const parsedURL = new URL(newOrigin)
if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
}
Object.defineProperty(globalThis, globalOrigin, {
value: parsedURL,
writable: true,
enumerable: false,
configurable: false
})
}
module.exports = {
getGlobalOrigin,
setGlobalOrigin
}
/***/ }),
/***/ 10554:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// https://github.com/Ethan-Arrowood/undici-fetch
const { kHeadersList, kConstruct } = __nccwpck_require__(72785)
const { kGuard } = __nccwpck_require__(15861)
const { kEnumerableProperty } = __nccwpck_require__(83983)
const {
makeIterator,
isValidHeaderName,
isValidHeaderValue
} = __nccwpck_require__(52538)
const { webidl } = __nccwpck_require__(21744)
const assert = __nccwpck_require__(39491)
const kHeadersMap = Symbol('headers map')
const kHeadersSortedMap = Symbol('headers map sorted')
/**
* @param {number} code
*/
function isHTTPWhiteSpaceCharCode (code) {
return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
* @param {string} potentialValue
*/
function headerValueNormalize (potentialValue) {
// To normalize a byte sequence potentialValue, remove
// any leading and trailing HTTP whitespace bytes from
// potentialValue.
let i = 0; let j = potentialValue.length
while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
}
function fill (headers, object) {
// To fill a Headers object headers with a given object object, run these steps:
// 1. If object is a sequence, then for each header in object:
// Note: webidl conversion to array has already been done.
if (Array.isArray(object)) {
for (let i = 0; i < object.length; ++i) {
const header = object[i]
// 1. If header does not contain exactly two items, then throw a TypeError.
if (header.length !== 2) {
throw webidl.errors.exception({
header: 'Headers constructor',
message: `expected name/value pair to be length 2, found ${header.length}.`
})
}
// 2. Append (headers first item, headers second item) to headers.
appendHeader(headers, header[0], header[1])
}
} else if (typeof object === 'object' && object !== null) {
// Note: null should throw
// 2. Otherwise, object is a record, then for each key → value in object,
// append (key, value) to headers
const keys = Object.keys(object)
for (let i = 0; i < keys.length; ++i) {
appendHeader(headers, keys[i], object[keys[i]])
}
} else {
throw webidl.errors.conversionFailed({
prefix: 'Headers constructor',
argument: 'Argument 1',
types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>']
})
}
}
/**
* @see https://fetch.spec.whatwg.org/#concept-headers-append
*/
function appendHeader (headers, name, value) {
// 1. Normalize value.
value = headerValueNormalize(value)
// 2. If name is not a header name or value is not a
// header value, then throw a TypeError.
if (!isValidHeaderName(name)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.append',
value: name,
type: 'header name'
})
} else if (!isValidHeaderValue(value)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.append',
value,
type: 'header value'
})
}
// 3. If headerss guard is "immutable", then throw a TypeError.
// 4. Otherwise, if headerss guard is "request" and name is a
// forbidden header name, return.
// Note: undici does not implement forbidden header names
if (headers[kGuard] === 'immutable') {
throw new TypeError('immutable')
} else if (headers[kGuard] === 'request-no-cors') {
// 5. Otherwise, if headerss guard is "request-no-cors":
// TODO
}
// 6. Otherwise, if headerss guard is "response" and name is a
// forbidden response-header name, return.
// 7. Append (name, value) to headerss header list.
return headers[kHeadersList].append(name, value)
// 8. If headerss guard is "request-no-cors", then remove
// privileged no-CORS request headers from headers
}
class HeadersList {
/** @type {[string, string][]|null} */
cookies = null
constructor (init) {
if (init instanceof HeadersList) {
this[kHeadersMap] = new Map(init[kHeadersMap])
this[kHeadersSortedMap] = init[kHeadersSortedMap]
this.cookies = init.cookies === null ? null : [...init.cookies]
} else {
this[kHeadersMap] = new Map(init)
this[kHeadersSortedMap] = null
}
}
// https://fetch.spec.whatwg.org/#header-list-contains
contains (name) {
// A header list list contains a header name name if list
// contains a header whose name is a byte-case-insensitive
// match for name.
name = name.toLowerCase()
return this[kHeadersMap].has(name)
}
clear () {
this[kHeadersMap].clear()
this[kHeadersSortedMap] = null
this.cookies = null
}
// https://fetch.spec.whatwg.org/#concept-header-list-append
append (name, value) {
this[kHeadersSortedMap] = null
// 1. If list contains name, then set name to the first such
// headers name.
const lowercaseName = name.toLowerCase()
const exists = this[kHeadersMap].get(lowercaseName)
// 2. Append (name, value) to list.
if (exists) {
const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
this[kHeadersMap].set(lowercaseName, {
name: exists.name,
value: `${exists.value}${delimiter}${value}`
})
} else {
this[kHeadersMap].set(lowercaseName, { name, value })
}
if (lowercaseName === 'set-cookie') {
this.cookies ??= []
this.cookies.push(value)
}
}
// https://fetch.spec.whatwg.org/#concept-header-list-set
set (name, value) {
this[kHeadersSortedMap] = null
const lowercaseName = name.toLowerCase()
if (lowercaseName === 'set-cookie') {
this.cookies = [value]
}
// 1. If list contains name, then set the value of
// the first such header to value and remove the
// others.
// 2. Otherwise, append header (name, value) to list.
this[kHeadersMap].set(lowercaseName, { name, value })
}
// https://fetch.spec.whatwg.org/#concept-header-list-delete
delete (name) {
this[kHeadersSortedMap] = null
name = name.toLowerCase()
if (name === 'set-cookie') {
this.cookies = null
}
this[kHeadersMap].delete(name)
}
// https://fetch.spec.whatwg.org/#concept-header-list-get
get (name) {
const value = this[kHeadersMap].get(name.toLowerCase())
// 1. If list does not contain name, then return null.
// 2. Return the values of all headers in list whose name
// is a byte-case-insensitive match for name,
// separated from each other by 0x2C 0x20, in order.
return value === undefined ? null : value.value
}
* [Symbol.iterator] () {
// use the lowercased name
for (const [name, { value }] of this[kHeadersMap]) {
yield [name, value]
}
}
get entries () {
const headers = {}
if (this[kHeadersMap].size) {
for (const { name, value } of this[kHeadersMap].values()) {
headers[name] = value
}
}
return headers
}
}
// https://fetch.spec.whatwg.org/#headers-class
class Headers {
constructor (init = undefined) {
if (init === kConstruct) {
return
}
this[kHeadersList] = new HeadersList()
// The new Headers(init) constructor steps are:
// 1. Set thiss guard to "none".
this[kGuard] = 'none'
// 2. If init is given, then fill this with init.
if (init !== undefined) {
init = webidl.converters.HeadersInit(init)
fill(this, init)
}
}
// https://fetch.spec.whatwg.org/#dom-headers-append
append (name, value) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
name = webidl.converters.ByteString(name)
value = webidl.converters.ByteString(value)
return appendHeader(this, name, value)
}
// https://fetch.spec.whatwg.org/#dom-headers-delete
delete (name) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
name = webidl.converters.ByteString(name)
// 1. If name is not a header name, then throw a TypeError.
if (!isValidHeaderName(name)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.delete',
value: name,
type: 'header name'
})
}
// 2. If thiss guard is "immutable", then throw a TypeError.
// 3. Otherwise, if thiss guard is "request" and name is a
// forbidden header name, return.
// 4. Otherwise, if thiss guard is "request-no-cors", name
// is not a no-CORS-safelisted request-header name, and
// name is not a privileged no-CORS request-header name,
// return.
// 5. Otherwise, if thiss guard is "response" and name is
// a forbidden response-header name, return.
// Note: undici does not implement forbidden header names
if (this[kGuard] === 'immutable') {
throw new TypeError('immutable')
} else if (this[kGuard] === 'request-no-cors') {
// TODO
}
// 6. If thiss header list does not contain name, then
// return.
if (!this[kHeadersList].contains(name)) {
return
}
// 7. Delete name from thiss header list.
// 8. If thiss guard is "request-no-cors", then remove
// privileged no-CORS request headers from this.
this[kHeadersList].delete(name)
}
// https://fetch.spec.whatwg.org/#dom-headers-get
get (name) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
name = webidl.converters.ByteString(name)
// 1. If name is not a header name, then throw a TypeError.
if (!isValidHeaderName(name)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.get',
value: name,
type: 'header name'
})
}
// 2. Return the result of getting name from thiss header
// list.
return this[kHeadersList].get(name)
}
// https://fetch.spec.whatwg.org/#dom-headers-has
has (name) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
name = webidl.converters.ByteString(name)
// 1. If name is not a header name, then throw a TypeError.
if (!isValidHeaderName(name)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.has',
value: name,
type: 'header name'
})
}
// 2. Return true if thiss header list contains name;
// otherwise false.
return this[kHeadersList].contains(name)
}
// https://fetch.spec.whatwg.org/#dom-headers-set
set (name, value) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
name = webidl.converters.ByteString(name)
value = webidl.converters.ByteString(value)
// 1. Normalize value.
value = headerValueNormalize(value)
// 2. If name is not a header name or value is not a
// header value, then throw a TypeError.
if (!isValidHeaderName(name)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.set',
value: name,
type: 'header name'
})
} else if (!isValidHeaderValue(value)) {
throw webidl.errors.invalidArgument({
prefix: 'Headers.set',
value,
type: 'header value'
})
}
// 3. If thiss guard is "immutable", then throw a TypeError.
// 4. Otherwise, if thiss guard is "request" and name is a
// forbidden header name, return.
// 5. Otherwise, if thiss guard is "request-no-cors" and
// name/value is not a no-CORS-safelisted request-header,
// return.
// 6. Otherwise, if thiss guard is "response" and name is a
// forbidden response-header name, return.
// Note: undici does not implement forbidden header names
if (this[kGuard] === 'immutable') {
throw new TypeError('immutable')
} else if (this[kGuard] === 'request-no-cors') {
// TODO
}
// 7. Set (name, value) in thiss header list.
// 8. If thiss guard is "request-no-cors", then remove
// privileged no-CORS request headers from this
this[kHeadersList].set(name, value)
}
// https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
getSetCookie () {
webidl.brandCheck(this, Headers)
// 1. If thiss header list does not contain `Set-Cookie`, then return « ».
// 2. Return the values of all headers in thiss header list whose name is
// a byte-case-insensitive match for `Set-Cookie`, in order.
const list = this[kHeadersList].cookies
if (list) {
return [...list]
}
return []
}
// https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
get [kHeadersSortedMap] () {
if (this[kHeadersList][kHeadersSortedMap]) {
return this[kHeadersList][kHeadersSortedMap]
}
// 1. Let headers be an empty list of headers with the key being the name
// and value the value.
const headers = []
// 2. Let names be the result of convert header names to a sorted-lowercase
// set with all the names of the headers in list.
const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
const cookies = this[kHeadersList].cookies
// 3. For each name of names:
for (let i = 0; i < names.length; ++i) {
const [name, value] = names[i]
// 1. If name is `set-cookie`, then:
if (name === 'set-cookie') {
// 1. Let values be a list of all values of headers in list whose name
// is a byte-case-insensitive match for name, in order.
// 2. For each value of values:
// 1. Append (name, value) to headers.
for (let j = 0; j < cookies.length; ++j) {
headers.push([name, cookies[j]])
}
} else {
// 2. Otherwise:
// 1. Let value be the result of getting name from list.
// 2. Assert: value is non-null.
assert(value !== null)
// 3. Append (name, value) to headers.
headers.push([name, value])
}
}
this[kHeadersList][kHeadersSortedMap] = headers
// 4. Return headers.
return headers
}
keys () {
webidl.brandCheck(this, Headers)
if (this[kGuard] === 'immutable') {
const value = this[kHeadersSortedMap]
return makeIterator(() => value, 'Headers',
'key')
}
return makeIterator(
() => [...this[kHeadersSortedMap].values()],
'Headers',
'key'
)
}
values () {
webidl.brandCheck(this, Headers)
if (this[kGuard] === 'immutable') {
const value = this[kHeadersSortedMap]
return makeIterator(() => value, 'Headers',
'value')
}
return makeIterator(
() => [...this[kHeadersSortedMap].values()],
'Headers',
'value'
)
}
entries () {
webidl.brandCheck(this, Headers)
if (this[kGuard] === 'immutable') {
const value = this[kHeadersSortedMap]
return makeIterator(() => value, 'Headers',
'key+value')
}
return makeIterator(
() => [...this[kHeadersSortedMap].values()],
'Headers',
'key+value'
)
}
/**
* @param {(value: string, key: string, self: Headers) => void} callbackFn
* @param {unknown} thisArg
*/
forEach (callbackFn, thisArg = globalThis) {
webidl.brandCheck(this, Headers)
webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
if (typeof callbackFn !== 'function') {
throw new TypeError(
"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
)
}
for (const [key, value] of this) {
callbackFn.apply(thisArg, [value, key, this])
}
}
[Symbol.for('nodejs.util.inspect.custom')] () {
webidl.brandCheck(this, Headers)
return this[kHeadersList]
}
}
Headers.prototype[Symbol.iterator] = Headers.prototype.entries
Object.defineProperties(Headers.prototype, {
append: kEnumerableProperty,
delete: kEnumerableProperty,
get: kEnumerableProperty,
has: kEnumerableProperty,
set: kEnumerableProperty,
getSetCookie: kEnumerableProperty,
keys: kEnumerableProperty,
values: kEnumerableProperty,
entries: kEnumerableProperty,
forEach: kEnumerableProperty,
[Symbol.iterator]: { enumerable: false },
[Symbol.toStringTag]: {
value: 'Headers',
configurable: true
}
})
webidl.converters.HeadersInit = function (V) {
if (webidl.util.Type(V) === 'Object') {
if (V[Symbol.iterator]) {
return webidl.converters['sequence<sequence<ByteString>>'](V)
}
return webidl.converters['record<ByteString, ByteString>'](V)
}
throw webidl.errors.conversionFailed({
prefix: 'Headers constructor',
argument: 'Argument 1',
types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>']
})
}
module.exports = {
fill,
Headers,
HeadersList
}
/***/ }),
/***/ 74881:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// https://github.com/Ethan-Arrowood/undici-fetch
const {
Response,
makeNetworkError,
makeAppropriateNetworkError,
filterResponse,
makeResponse
} = __nccwpck_require__(27823)
const { Headers } = __nccwpck_require__(10554)
const { Request, makeRequest } = __nccwpck_require__(48359)
const zlib = __nccwpck_require__(59796)
const {
bytesMatch,
makePolicyContainer,
clonePolicyContainer,
requestBadPort,
TAOCheck,
appendRequestOriginHeader,
responseLocationURL,
requestCurrentURL,
setRequestReferrerPolicyOnRedirect,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
createOpaqueTimingInfo,
appendFetchMetadata,
corsCheck,
crossOriginResourcePolicyCheck,
determineRequestsReferrer,
coarsenedSharedCurrentTime,
createDeferredPromise,
isBlobLike,
sameOrigin,
isCancelled,
isAborted,
isErrorLike,
fullyReadBody,
readableStreamClose,
isomorphicEncode,
urlIsLocal,
urlIsHttpHttpsScheme,
urlHasHttpsScheme
} = __nccwpck_require__(52538)
const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861)
const assert = __nccwpck_require__(39491)
const { safelyExtractBody } = __nccwpck_require__(41472)
const {
redirectStatusSet,
nullBodyStatus,
safeMethodsSet,
requestBodyHeader,
subresourceSet,
DOMException
} = __nccwpck_require__(41037)
const { kHeadersList } = __nccwpck_require__(72785)
const EE = __nccwpck_require__(82361)
const { Readable, pipeline } = __nccwpck_require__(12781)
const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(83983)
const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685)
const { TransformStream } = __nccwpck_require__(35356)
const { getGlobalDispatcher } = __nccwpck_require__(21892)
const { webidl } = __nccwpck_require__(21744)
const { STATUS_CODES } = __nccwpck_require__(13685)
const GET_OR_HEAD = ['GET', 'HEAD']
/** @type {import('buffer').resolveObjectURL} */
let resolveObjectURL
let ReadableStream = globalThis.ReadableStream
class Fetch extends EE {
constructor (dispatcher) {
super()
this.dispatcher = dispatcher
this.connection = null
this.dump = false
this.state = 'ongoing'
// 2 terminated listeners get added per request,
// but only 1 gets removed. If there are 20 redirects,
// 21 listeners will be added.
// See https://github.com/nodejs/undici/issues/1711
// TODO (fix): Find and fix root cause for leaked listener.
this.setMaxListeners(21)
}
terminate (reason) {
if (this.state !== 'ongoing') {
return
}
this.state = 'terminated'
this.connection?.destroy(reason)
this.emit('terminated', reason)
}
// https://fetch.spec.whatwg.org/#fetch-controller-abort
abort (error) {
if (this.state !== 'ongoing') {
return
}
// 1. Set controllers state to "aborted".
this.state = 'aborted'
// 2. Let fallbackError be an "AbortError" DOMException.
// 3. Set error to fallbackError if it is not given.
if (!error) {
error = new DOMException('The operation was aborted.', 'AbortError')
}
// 4. Let serializedError be StructuredSerialize(error).
// If that threw an exception, catch it, and let
// serializedError be StructuredSerialize(fallbackError).
// 5. Set controllers serialized abort reason to serializedError.
this.serializedAbortReason = error
this.connection?.destroy(error)
this.emit('terminated', error)
}
}
// https://fetch.spec.whatwg.org/#fetch-method
function fetch (input, init = {}) {
webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
// 1. Let p be a new promise.
const p = createDeferredPromise()
// 2. Let requestObject be the result of invoking the initial value of
// Request as constructor with input and init as arguments. If this throws
// an exception, reject p with it and return p.
let requestObject
try {
requestObject = new Request(input, init)
} catch (e) {
p.reject(e)
return p.promise
}
// 3. Let request be requestObjects request.
const request = requestObject[kState]
// 4. If requestObjects signals aborted flag is set, then:
if (requestObject.signal.aborted) {
// 1. Abort the fetch() call with p, request, null, and
// requestObjects signals abort reason.
abortFetch(p, request, null, requestObject.signal.reason)
// 2. Return p.
return p.promise
}
// 5. Let globalObject be requests clients global object.
const globalObject = request.client.globalObject
// 6. If globalObject is a ServiceWorkerGlobalScope object, then set
// requests service-workers mode to "none".
if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
request.serviceWorkers = 'none'
}
// 7. Let responseObject be null.
let responseObject = null
// 8. Let relevantRealm be thiss relevant Realm.
const relevantRealm = null
// 9. Let locallyAborted be false.
let locallyAborted = false
// 10. Let controller be null.
let controller = null
// 11. Add the following abort steps to requestObjects signal:
addAbortListener(
requestObject.signal,
() => {
// 1. Set locallyAborted to true.
locallyAborted = true
// 2. Assert: controller is non-null.
assert(controller != null)
// 3. Abort controller with requestObjects signals abort reason.
controller.abort(requestObject.signal.reason)
// 4. Abort the fetch() call with p, request, responseObject,
// and requestObjects signals abort reason.
abortFetch(p, request, responseObject, requestObject.signal.reason)
}
)
// 12. Let handleFetchDone given response response be to finalize and
// report timing with response, globalObject, and "fetch".
const handleFetchDone = (response) =>
finalizeAndReportTiming(response, 'fetch')
// 13. Set controller to the result of calling fetch given request,
// with processResponseEndOfBody set to handleFetchDone, and processResponse
// given response being these substeps:
const processResponse = (response) => {
// 1. If locallyAborted is true, terminate these substeps.
if (locallyAborted) {
return Promise.resolve()
}
// 2. If responses aborted flag is set, then:
if (response.aborted) {
// 1. Let deserializedError be the result of deserialize a serialized
// abort reason given controllers serialized abort reason and
// relevantRealm.
// 2. Abort the fetch() call with p, request, responseObject, and
// deserializedError.
abortFetch(p, request, responseObject, controller.serializedAbortReason)
return Promise.resolve()
}
// 3. If response is a network error, then reject p with a TypeError
// and terminate these substeps.
if (response.type === 'error') {
p.reject(
Object.assign(new TypeError('fetch failed'), { cause: response.error })
)
return Promise.resolve()
}
// 4. Set responseObject to the result of creating a Response object,
// given response, "immutable", and relevantRealm.
responseObject = new Response()
responseObject[kState] = response
responseObject[kRealm] = relevantRealm
responseObject[kHeaders][kHeadersList] = response.headersList
responseObject[kHeaders][kGuard] = 'immutable'
responseObject[kHeaders][kRealm] = relevantRealm
// 5. Resolve p with responseObject.
p.resolve(responseObject)
}
controller = fetching({
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
})
// 14. Return p.
return p.promise
}
// https://fetch.spec.whatwg.org/#finalize-and-report-timing
function finalizeAndReportTiming (response, initiatorType = 'other') {
// 1. If response is an aborted network error, then return.
if (response.type === 'error' && response.aborted) {
return
}
// 2. If responses URL list is null or empty, then return.
if (!response.urlList?.length) {
return
}
// 3. Let originalURL be responses URL list[0].
const originalURL = response.urlList[0]
// 4. Let timingInfo be responses timing info.
let timingInfo = response.timingInfo
// 5. Let cacheState be responses cache state.
let cacheState = response.cacheState
// 6. If originalURLs scheme is not an HTTP(S) scheme, then return.
if (!urlIsHttpHttpsScheme(originalURL)) {
return
}
// 7. If timingInfo is null, then return.
if (timingInfo === null) {
return
}
// 8. If responses timing allow passed flag is not set, then:
if (!response.timingAllowPassed) {
// 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
timingInfo = createOpaqueTimingInfo({
startTime: timingInfo.startTime
})
// 2. Set cacheState to the empty string.
cacheState = ''
}
// 9. Set timingInfos end time to the coarsened shared current time
// given globals relevant settings objects cross-origin isolated
// capability.
// TODO: given globals relevant settings objects cross-origin isolated
// capability?
timingInfo.endTime = coarsenedSharedCurrentTime()
// 10. Set responses timing info to timingInfo.
response.timingInfo = timingInfo
// 11. Mark resource timing for timingInfo, originalURL, initiatorType,
// global, and cacheState.
markResourceTiming(
timingInfo,
originalURL,
initiatorType,
globalThis,
cacheState
)
}
// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
}
}
// https://fetch.spec.whatwg.org/#abort-fetch
function abortFetch (p, request, responseObject, error) {
// Note: AbortSignal.reason was added in node v17.2.0
// which would give us an undefined error to reject with.
// Remove this once node v16 is no longer supported.
if (!error) {
error = new DOMException('The operation was aborted.', 'AbortError')
}
// 1. Reject promise with error.
p.reject(error)
// 2. If requests body is not null and is readable, then cancel requests
// body with error.
if (request.body != null && isReadable(request.body?.stream)) {
request.body.stream.cancel(error).catch((err) => {
if (err.code === 'ERR_INVALID_STATE') {
// Node bug?
return
}
throw err
})
}
// 3. If responseObject is null, then return.
if (responseObject == null) {
return
}
// 4. Let response be responseObjects response.
const response = responseObject[kState]
// 5. If responses body is not null and is readable, then error responses
// body with error.
if (response.body != null && isReadable(response.body?.stream)) {
response.body.stream.cancel(error).catch((err) => {
if (err.code === 'ERR_INVALID_STATE') {
// Node bug?
return
}
throw err
})
}
}
// https://fetch.spec.whatwg.org/#fetching
function fetching ({
request,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseEndOfBody,
processResponseConsumeBody,
useParallelQueue = false,
dispatcher // undici
}) {
// 1. Let taskDestination be null.
let taskDestination = null
// 2. Let crossOriginIsolatedCapability be false.
let crossOriginIsolatedCapability = false
// 3. If requests client is non-null, then:
if (request.client != null) {
// 1. Set taskDestination to requests clients global object.
taskDestination = request.client.globalObject
// 2. Set crossOriginIsolatedCapability to requests clients cross-origin
// isolated capability.
crossOriginIsolatedCapability =
request.client.crossOriginIsolatedCapability
}
// 4. If useParallelQueue is true, then set taskDestination to the result of
// starting a new parallel queue.
// TODO
// 5. Let timingInfo be a new fetch timing info whose start time and
// post-redirect start time are the coarsened shared current time given
// crossOriginIsolatedCapability.
const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
const timingInfo = createOpaqueTimingInfo({
startTime: currenTime
})
// 6. Let fetchParams be a new fetch params whose
// request is request,
// timing info is timingInfo,
// process request body chunk length is processRequestBodyChunkLength,
// process request end-of-body is processRequestEndOfBody,
// process response is processResponse,
// process response consume body is processResponseConsumeBody,
// process response end-of-body is processResponseEndOfBody,
// task destination is taskDestination,
// and cross-origin isolated capability is crossOriginIsolatedCapability.
const fetchParams = {
controller: new Fetch(dispatcher),
request,
timingInfo,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseConsumeBody,
processResponseEndOfBody,
taskDestination,
crossOriginIsolatedCapability
}
// 7. If requests body is a byte sequence, then set requests body to
// requests body as a body.
// NOTE: Since fetching is only called from fetch, body should already be
// extracted.
assert(!request.body || request.body.stream)
// 8. If requests window is "client", then set requests window to requests
// client, if requests clients global object is a Window object; otherwise
// "no-window".
if (request.window === 'client') {
// TODO: What if request.client is null?
request.window =
request.client?.globalObject?.constructor?.name === 'Window'
? request.client
: 'no-window'
}
// 9. If requests origin is "client", then set requests origin to requests
// clients origin.
if (request.origin === 'client') {
// TODO: What if request.client is null?
request.origin = request.client?.origin
}
// 10. If all of the following conditions are true:
// TODO
// 11. If requests policy container is "client", then:
if (request.policyContainer === 'client') {
// 1. If requests client is non-null, then set requests policy
// container to a clone of requests clients policy container. [HTML]
if (request.client != null) {
request.policyContainer = clonePolicyContainer(
request.client.policyContainer
)
} else {
// 2. Otherwise, set requests policy container to a new policy
// container.
request.policyContainer = makePolicyContainer()
}
}
// 12. If requests header list does not contain `Accept`, then:
if (!request.headersList.contains('accept')) {
// 1. Let value be `*/*`.
const value = '*/*'
// 2. A user agent should set value to the first matching statement, if
// any, switching on requests destination:
// "document"
// "frame"
// "iframe"
// `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
// "image"
// `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
// "style"
// `text/css,*/*;q=0.1`
// TODO
// 3. Append `Accept`/value to requests header list.
request.headersList.append('accept', value)
}
// 13. If requests header list does not contain `Accept-Language`, then
// user agents should append `Accept-Language`/an appropriate value to
// requests header list.
if (!request.headersList.contains('accept-language')) {
request.headersList.append('accept-language', '*')
}
// 14. If requests priority is null, then use requests initiator and
// destination appropriately in setting requests priority to a
// user-agent-defined object.
if (request.priority === null) {
// TODO
}
// 15. If request is a subresource request, then:
if (subresourceSet.has(request.destination)) {
// TODO
}
// 16. Run main fetch given fetchParams.
mainFetch(fetchParams)
.catch(err => {
fetchParams.controller.terminate(err)
})
// 17. Return fetchParam's controller
return fetchParams.controller
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
async function mainFetch (fetchParams, recursive = false) {
// 1. Let request be fetchParamss request.
const request = fetchParams.request
// 2. Let response be null.
let response = null
// 3. If requests local-URLs-only flag is set and requests current URL is
// not local, then set response to a network error.
if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
response = makeNetworkError('local URLs only')
}
// 4. Run report Content Security Policy violations for request.
// TODO
// 5. Upgrade request to a potentially trustworthy URL, if appropriate.
tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
// 6. If should request be blocked due to a bad port, should fetching request
// be blocked as mixed content, or should request be blocked by Content
// Security Policy returns blocked, then set response to a network error.
if (requestBadPort(request) === 'blocked') {
response = makeNetworkError('bad port')
}
// TODO: should fetching request be blocked as mixed content?
// TODO: should request be blocked by Content Security Policy?
// 7. If requests referrer policy is the empty string, then set requests
// referrer policy to requests policy containers referrer policy.
if (request.referrerPolicy === '') {
request.referrerPolicy = request.policyContainer.referrerPolicy
}
// 8. If requests referrer is not "no-referrer", then set requests
// referrer to the result of invoking determine requests referrer.
if (request.referrer !== 'no-referrer') {
request.referrer = determineRequestsReferrer(request)
}
// 9. Set requests current URLs scheme to "https" if all of the following
// conditions are true:
// - requests current URLs scheme is "http"
// - requests current URLs host is a domain
// - Matching requests current URLs host per Known HSTS Host Domain Name
// Matching results in either a superdomain match with an asserted
// includeSubDomains directive or a congruent match (with or without an
// asserted includeSubDomains directive). [HSTS]
// TODO
// 10. If recursive is false, then run the remaining steps in parallel.
// TODO
// 11. If response is null, then set response to the result of running
// the steps corresponding to the first matching statement:
if (response === null) {
response = await (async () => {
const currentURL = requestCurrentURL(request)
if (
// - requests current URLs origin is same origin with requests origin,
// and requests response tainting is "basic"
(sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
// requests current URLs scheme is "data"
(currentURL.protocol === 'data:') ||
// - requests mode is "navigate" or "websocket"
(request.mode === 'navigate' || request.mode === 'websocket')
) {
// 1. Set requests response tainting to "basic".
request.responseTainting = 'basic'
// 2. Return the result of running scheme fetch given fetchParams.
return await schemeFetch(fetchParams)
}
// requests mode is "same-origin"
if (request.mode === 'same-origin') {
// 1. Return a network error.
return makeNetworkError('request mode cannot be "same-origin"')
}
// requests mode is "no-cors"
if (request.mode === 'no-cors') {
// 1. If requests redirect mode is not "follow", then return a network
// error.
if (request.redirect !== 'follow') {
return makeNetworkError(
'redirect mode cannot be "follow" for "no-cors" request'
)
}
// 2. Set requests response tainting to "opaque".
request.responseTainting = 'opaque'
// 3. Return the result of running scheme fetch given fetchParams.
return await schemeFetch(fetchParams)
}
// requests current URLs scheme is not an HTTP(S) scheme
if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
// Return a network error.
return makeNetworkError('URL scheme must be a HTTP(S) scheme')
}
// - requests use-CORS-preflight flag is set
// - requests unsafe-request flag is set and either requests method is
// not a CORS-safelisted method or CORS-unsafe request-header names with
// requests header list is not empty
// 1. Set requests response tainting to "cors".
// 2. Let corsWithPreflightResponse be the result of running HTTP fetch
// given fetchParams and true.
// 3. If corsWithPreflightResponse is a network error, then clear cache
// entries using request.
// 4. Return corsWithPreflightResponse.
// TODO
// Otherwise
// 1. Set requests response tainting to "cors".
request.responseTainting = 'cors'
// 2. Return the result of running HTTP fetch given fetchParams.
return await httpFetch(fetchParams)
})()
}
// 12. If recursive is true, then return response.
if (recursive) {
return response
}
// 13. If response is not a network error and response is not a filtered
// response, then:
if (response.status !== 0 && !response.internalResponse) {
// If requests response tainting is "cors", then:
if (request.responseTainting === 'cors') {
// 1. Let headerNames be the result of extracting header list values
// given `Access-Control-Expose-Headers` and responses header list.
// TODO
// 2. If requests credentials mode is not "include" and headerNames
// contains `*`, then set responses CORS-exposed header-name list to
// all unique header names in responses header list.
// TODO
// 3. Otherwise, if headerNames is not null or failure, then set
// responses CORS-exposed header-name list to headerNames.
// TODO
}
// Set response to the following filtered response with response as its
// internal response, depending on requests response tainting:
if (request.responseTainting === 'basic') {
response = filterResponse(response, 'basic')
} else if (request.responseTainting === 'cors') {
response = filterResponse(response, 'cors')
} else if (request.responseTainting === 'opaque') {
response = filterResponse(response, 'opaque')
} else {
assert(false)
}
}
// 14. Let internalResponse be response, if response is a network error,
// and responses internal response otherwise.
let internalResponse =
response.status === 0 ? response : response.internalResponse
// 15. If internalResponses URL list is empty, then set it to a clone of
// requests URL list.
if (internalResponse.urlList.length === 0) {
internalResponse.urlList.push(...request.urlList)
}
// 16. If requests timing allow failed flag is unset, then set
// internalResponses timing allow passed flag.
if (!request.timingAllowFailed) {
response.timingAllowPassed = true
}
// 17. If response is not a network error and any of the following returns
// blocked
// - should internalResponse to request be blocked as mixed content
// - should internalResponse to request be blocked by Content Security Policy
// - should internalResponse to request be blocked due to its MIME type
// - should internalResponse to request be blocked due to nosniff
// TODO
// 18. If responses type is "opaque", internalResponses status is 206,
// internalResponses range-requested flag is set, and requests header
// list does not contain `Range`, then set response and internalResponse
// to a network error.
if (
response.type === 'opaque' &&
internalResponse.status === 206 &&
internalResponse.rangeRequested &&
!request.headers.contains('range')
) {
response = internalResponse = makeNetworkError()
}
// 19. If response is not a network error and either requests method is
// `HEAD` or `CONNECT`, or internalResponses status is a null body status,
// set internalResponses body to null and disregard any enqueuing toward
// it (if any).
if (
response.status !== 0 &&
(request.method === 'HEAD' ||
request.method === 'CONNECT' ||
nullBodyStatus.includes(internalResponse.status))
) {
internalResponse.body = null
fetchParams.controller.dump = true
}
// 20. If requests integrity metadata is not the empty string, then:
if (request.integrity) {
// 1. Let processBodyError be this step: run fetch finale given fetchParams
// and a network error.
const processBodyError = (reason) =>
fetchFinale(fetchParams, makeNetworkError(reason))
// 2. If requests response tainting is "opaque", or responses body is null,
// then run processBodyError and abort these steps.
if (request.responseTainting === 'opaque' || response.body == null) {
processBodyError(response.error)
return
}
// 3. Let processBody given bytes be these steps:
const processBody = (bytes) => {
// 1. If bytes do not match requests integrity metadata,
// then run processBodyError and abort these steps. [SRI]
if (!bytesMatch(bytes, request.integrity)) {
processBodyError('integrity mismatch')
return
}
// 2. Set responses body to bytes as a body.
response.body = safelyExtractBody(bytes)[0]
// 3. Run fetch finale given fetchParams and response.
fetchFinale(fetchParams, response)
}
// 4. Fully read responses body given processBody and processBodyError.
await fullyReadBody(response.body, processBody, processBodyError)
} else {
// 21. Otherwise, run fetch finale given fetchParams and response.
fetchFinale(fetchParams, response)
}
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
// given a fetch params fetchParams
function schemeFetch (fetchParams) {
// Note: since the connection is destroyed on redirect, which sets fetchParams to a
// cancelled state, we do not want this condition to trigger *unless* there have been
// no redirects. See https://github.com/nodejs/undici/issues/1776
// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
return Promise.resolve(makeAppropriateNetworkError(fetchParams))
}
// 2. Let request be fetchParamss request.
const { request } = fetchParams
const { protocol: scheme } = requestCurrentURL(request)
// 3. Switch on requests current URLs scheme and run the associated steps:
switch (scheme) {
case 'about:': {
// If requests current URLs path is the string "blank", then return a new response
// whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
// and body is the empty byte sequence as a body.
// Otherwise, return a network error.
return Promise.resolve(makeNetworkError('about scheme is not supported'))
}
case 'blob:': {
if (!resolveObjectURL) {
resolveObjectURL = (__nccwpck_require__(14300).resolveObjectURL)
}
// 1. Let blobURLEntry be requests current URLs blob URL entry.
const blobURLEntry = requestCurrentURL(request)
// https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
// Buffer.resolveObjectURL does not ignore URL queries.
if (blobURLEntry.search.length !== 0) {
return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
}
const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
// 2. If requests method is not `GET`, blobURLEntry is null, or blobURLEntrys
// object is not a Blob object, then return a network error.
if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
return Promise.resolve(makeNetworkError('invalid method'))
}
// 3. Let bodyWithType be the result of safely extracting blobURLEntrys object.
const bodyWithType = safelyExtractBody(blobURLEntryObject)
// 4. Let body be bodyWithTypes body.
const body = bodyWithType[0]
// 5. Let length be bodys length, serialized and isomorphic encoded.
const length = isomorphicEncode(`${body.length}`)
// 6. Let type be bodyWithTypes type if it is non-null; otherwise the empty byte sequence.
const type = bodyWithType[1] ?? ''
// 7. Return a new response whose status message is `OK`, header list is
// « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
const response = makeResponse({
statusText: 'OK',
headersList: [
['content-length', { name: 'Content-Length', value: length }],
['content-type', { name: 'Content-Type', value: type }]
]
})
response.body = body
return Promise.resolve(response)
}
case 'data:': {
// 1. Let dataURLStruct be the result of running the
// data: URL processor on requests current URL.
const currentURL = requestCurrentURL(request)
const dataURLStruct = dataURLProcessor(currentURL)
// 2. If dataURLStruct is failure, then return a
// network error.
if (dataURLStruct === 'failure') {
return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
}
// 3. Let mimeType be dataURLStructs MIME type, serialized.
const mimeType = serializeAMimeType(dataURLStruct.mimeType)
// 4. Return a response whose status message is `OK`,
// header list is « (`Content-Type`, mimeType) »,
// and body is dataURLStructs body as a body.
return Promise.resolve(makeResponse({
statusText: 'OK',
headersList: [
['content-type', { name: 'Content-Type', value: mimeType }]
],
body: safelyExtractBody(dataURLStruct.body)[0]
}))
}
case 'file:': {
// For now, unfortunate as it is, file URLs are left as an exercise for the reader.
// When in doubt, return a network error.
return Promise.resolve(makeNetworkError('not implemented... yet...'))
}
case 'http:':
case 'https:': {
// Return the result of running HTTP fetch given fetchParams.
return httpFetch(fetchParams)
.catch((err) => makeNetworkError(err))
}
default: {
return Promise.resolve(makeNetworkError('unknown scheme'))
}
}
}
// https://fetch.spec.whatwg.org/#finalize-response
function finalizeResponse (fetchParams, response) {
// 1. Set fetchParamss requests done flag.
fetchParams.request.done = true
// 2, If fetchParamss process response done is not null, then queue a fetch
// task to run fetchParamss process response done given response, with
// fetchParamss task destination.
if (fetchParams.processResponseDone != null) {
queueMicrotask(() => fetchParams.processResponseDone(response))
}
}
// https://fetch.spec.whatwg.org/#fetch-finale
function fetchFinale (fetchParams, response) {
// 1. If response is a network error, then:
if (response.type === 'error') {
// 1. Set responses URL list to « fetchParamss requests URL list[0] ».
response.urlList = [fetchParams.request.urlList[0]]
// 2. Set responses timing info to the result of creating an opaque timing
// info for fetchParamss timing info.
response.timingInfo = createOpaqueTimingInfo({
startTime: fetchParams.timingInfo.startTime
})
}
// 2. Let processResponseEndOfBody be the following steps:
const processResponseEndOfBody = () => {
// 1. Set fetchParamss requests done flag.
fetchParams.request.done = true
// If fetchParamss process response end-of-body is not null,
// then queue a fetch task to run fetchParamss process response
// end-of-body given response with fetchParamss task destination.
if (fetchParams.processResponseEndOfBody != null) {
queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
}
}
// 3. If fetchParamss process response is non-null, then queue a fetch task
// to run fetchParamss process response given response, with fetchParamss
// task destination.
if (fetchParams.processResponse != null) {
queueMicrotask(() => fetchParams.processResponse(response))
}
// 4. If responses body is null, then run processResponseEndOfBody.
if (response.body == null) {
processResponseEndOfBody()
} else {
// 5. Otherwise:
// 1. Let transformStream be a new a TransformStream.
// 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
// enqueues chunk in transformStream.
const identityTransformAlgorithm = (chunk, controller) => {
controller.enqueue(chunk)
}
// 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
// and flushAlgorithm set to processResponseEndOfBody.
const transformStream = new TransformStream({
start () {},
transform: identityTransformAlgorithm,
flush: processResponseEndOfBody
}, {
size () {
return 1
}
}, {
size () {
return 1
}
})
// 4. Set responses body to the result of piping responses body through transformStream.
response.body = { stream: response.body.stream.pipeThrough(transformStream) }
}
// 6. If fetchParamss process response consume body is non-null, then:
if (fetchParams.processResponseConsumeBody != null) {
// 1. Let processBody given nullOrBytes be this step: run fetchParamss
// process response consume body given response and nullOrBytes.
const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
// 2. Let processBodyError be this step: run fetchParamss process
// response consume body given response and failure.
const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
// 3. If responses body is null, then queue a fetch task to run processBody
// given null, with fetchParamss task destination.
if (response.body == null) {
queueMicrotask(() => processBody(null))
} else {
// 4. Otherwise, fully read responses body given processBody, processBodyError,
// and fetchParamss task destination.
return fullyReadBody(response.body, processBody, processBodyError)
}
return Promise.resolve()
}
}
// https://fetch.spec.whatwg.org/#http-fetch
async function httpFetch (fetchParams) {
// 1. Let request be fetchParamss request.
const request = fetchParams.request
// 2. Let response be null.
let response = null
// 3. Let actualResponse be null.
let actualResponse = null
// 4. Let timingInfo be fetchParamss timing info.
const timingInfo = fetchParams.timingInfo
// 5. If requests service-workers mode is "all", then:
if (request.serviceWorkers === 'all') {
// TODO
}
// 6. If response is null, then:
if (response === null) {
// 1. If makeCORSPreflight is true and one of these conditions is true:
// TODO
// 2. If requests redirect mode is "follow", then set requests
// service-workers mode to "none".
if (request.redirect === 'follow') {
request.serviceWorkers = 'none'
}
// 3. Set response and actualResponse to the result of running
// HTTP-network-or-cache fetch given fetchParams.
actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
// 4. If requests response tainting is "cors" and a CORS check
// for request and response returns failure, then return a network error.
if (
request.responseTainting === 'cors' &&
corsCheck(request, response) === 'failure'
) {
return makeNetworkError('cors failure')
}
// 5. If the TAO check for request and response returns failure, then set
// requests timing allow failed flag.
if (TAOCheck(request, response) === 'failure') {
request.timingAllowFailed = true
}
}
// 7. If either requests response tainting or responses type
// is "opaque", and the cross-origin resource policy check with
// requests origin, requests client, requests destination,
// and actualResponse returns blocked, then return a network error.
if (
(request.responseTainting === 'opaque' || response.type === 'opaque') &&
crossOriginResourcePolicyCheck(
request.origin,
request.client,
request.destination,
actualResponse
) === 'blocked'
) {
return makeNetworkError('blocked')
}
// 8. If actualResponses status is a redirect status, then:
if (redirectStatusSet.has(actualResponse.status)) {
// 1. If actualResponses status is not 303, requests body is not null,
// and the connection uses HTTP/2, then user agents may, and are even
// encouraged to, transmit an RST_STREAM frame.
// See, https://github.com/whatwg/fetch/issues/1288
if (request.redirect !== 'manual') {
fetchParams.controller.connection.destroy()
}
// 2. Switch on requests redirect mode:
if (request.redirect === 'error') {
// Set response to a network error.
response = makeNetworkError('unexpected redirect')
} else if (request.redirect === 'manual') {
// Set response to an opaque-redirect filtered response whose internal
// response is actualResponse.
// NOTE(spec): On the web this would return an `opaqueredirect` response,
// but that doesn't make sense server side.
// See https://github.com/nodejs/undici/issues/1193.
response = actualResponse
} else if (request.redirect === 'follow') {
// Set response to the result of running HTTP-redirect fetch given
// fetchParams and response.
response = await httpRedirectFetch(fetchParams, response)
} else {
assert(false)
}
}
// 9. Set responses timing info to timingInfo.
response.timingInfo = timingInfo
// 10. Return response.
return response
}
// https://fetch.spec.whatwg.org/#http-redirect-fetch
function httpRedirectFetch (fetchParams, response) {
// 1. Let request be fetchParamss request.
const request = fetchParams.request
// 2. Let actualResponse be response, if response is not a filtered response,
// and responses internal response otherwise.
const actualResponse = response.internalResponse
? response.internalResponse
: response
// 3. Let locationURL be actualResponses location URL given requests current
// URLs fragment.
let locationURL
try {
locationURL = responseLocationURL(
actualResponse,
requestCurrentURL(request).hash
)
// 4. If locationURL is null, then return response.
if (locationURL == null) {
return response
}
} catch (err) {
// 5. If locationURL is failure, then return a network error.
return Promise.resolve(makeNetworkError(err))
}
// 6. If locationURLs scheme is not an HTTP(S) scheme, then return a network
// error.
if (!urlIsHttpHttpsScheme(locationURL)) {
return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
}
// 7. If requests redirect count is 20, then return a network error.
if (request.redirectCount === 20) {
return Promise.resolve(makeNetworkError('redirect count exceeded'))
}
// 8. Increase requests redirect count by 1.
request.redirectCount += 1
// 9. If requests mode is "cors", locationURL includes credentials, and
// requests origin is not same origin with locationURLs origin, then return
// a network error.
if (
request.mode === 'cors' &&
(locationURL.username || locationURL.password) &&
!sameOrigin(request, locationURL)
) {
return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
}
// 10. If requests response tainting is "cors" and locationURL includes
// credentials, then return a network error.
if (
request.responseTainting === 'cors' &&
(locationURL.username || locationURL.password)
) {
return Promise.resolve(makeNetworkError(
'URL cannot contain credentials for request mode "cors"'
))
}
// 11. If actualResponses status is not 303, requests body is non-null,
// and requests bodys source is null, then return a network error.
if (
actualResponse.status !== 303 &&
request.body != null &&
request.body.source == null
) {
return Promise.resolve(makeNetworkError())
}
// 12. If one of the following is true
// - actualResponses status is 301 or 302 and requests method is `POST`
// - actualResponses status is 303 and requests method is not `GET` or `HEAD`
if (
([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
(actualResponse.status === 303 &&
!GET_OR_HEAD.includes(request.method))
) {
// then:
// 1. Set requests method to `GET` and requests body to null.
request.method = 'GET'
request.body = null
// 2. For each headerName of request-body-header name, delete headerName from
// requests header list.
for (const headerName of requestBodyHeader) {
request.headersList.delete(headerName)
}
}
// 13. If requests current URLs origin is not same origin with locationURLs
// origin, then for each headerName of CORS non-wildcard request-header name,
// delete headerName from requests header list.
if (!sameOrigin(requestCurrentURL(request), locationURL)) {
// https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
request.headersList.delete('authorization')
// https://fetch.spec.whatwg.org/#authentication-entries
request.headersList.delete('proxy-authorization', true)
// "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
request.headersList.delete('cookie')
request.headersList.delete('host')
}
// 14. If requests body is non-null, then set requests body to the first return
// value of safely extracting requests bodys source.
if (request.body != null) {
assert(request.body.source != null)
request.body = safelyExtractBody(request.body.source)[0]
}
// 15. Let timingInfo be fetchParamss timing info.
const timingInfo = fetchParams.timingInfo
// 16. Set timingInfos redirect end time and post-redirect start time to the
// coarsened shared current time given fetchParamss cross-origin isolated
// capability.
timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
// 17. If timingInfos redirect start time is 0, then set timingInfos
// redirect start time to timingInfos start time.
if (timingInfo.redirectStartTime === 0) {
timingInfo.redirectStartTime = timingInfo.startTime
}
// 18. Append locationURL to requests URL list.
request.urlList.push(locationURL)
// 19. Invoke set requests referrer policy on redirect on request and
// actualResponse.
setRequestReferrerPolicyOnRedirect(request, actualResponse)
// 20. Return the result of running main fetch given fetchParams and true.
return mainFetch(fetchParams, true)
}
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
async function httpNetworkOrCacheFetch (
fetchParams,
isAuthenticationFetch = false,
isNewConnectionFetch = false
) {
// 1. Let request be fetchParamss request.
const request = fetchParams.request
// 2. Let httpFetchParams be null.
let httpFetchParams = null
// 3. Let httpRequest be null.
let httpRequest = null
// 4. Let response be null.
let response = null
// 5. Let storedResponse be null.
// TODO: cache
// 6. Let httpCache be null.
const httpCache = null
// 7. Let the revalidatingFlag be unset.
const revalidatingFlag = false
// 8. Run these steps, but abort when the ongoing fetch is terminated:
// 1. If requests window is "no-window" and requests redirect mode is
// "error", then set httpFetchParams to fetchParams and httpRequest to
// request.
if (request.window === 'no-window' && request.redirect === 'error') {
httpFetchParams = fetchParams
httpRequest = request
} else {
// Otherwise:
// 1. Set httpRequest to a clone of request.
httpRequest = makeRequest(request)
// 2. Set httpFetchParams to a copy of fetchParams.
httpFetchParams = { ...fetchParams }
// 3. Set httpFetchParamss request to httpRequest.
httpFetchParams.request = httpRequest
}
// 3. Let includeCredentials be true if one of
const includeCredentials =
request.credentials === 'include' ||
(request.credentials === 'same-origin' &&
request.responseTainting === 'basic')
// 4. Let contentLength be httpRequests bodys length, if httpRequests
// body is non-null; otherwise null.
const contentLength = httpRequest.body ? httpRequest.body.length : null
// 5. Let contentLengthHeaderValue be null.
let contentLengthHeaderValue = null
// 6. If httpRequests body is null and httpRequests method is `POST` or
// `PUT`, then set contentLengthHeaderValue to `0`.
if (
httpRequest.body == null &&
['POST', 'PUT'].includes(httpRequest.method)
) {
contentLengthHeaderValue = '0'
}
// 7. If contentLength is non-null, then set contentLengthHeaderValue to
// contentLength, serialized and isomorphic encoded.
if (contentLength != null) {
contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
}
// 8. If contentLengthHeaderValue is non-null, then append
// `Content-Length`/contentLengthHeaderValue to httpRequests header
// list.
if (contentLengthHeaderValue != null) {
httpRequest.headersList.append('content-length', contentLengthHeaderValue)
}
// 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
// contentLengthHeaderValue) to httpRequests header list.
// 10. If contentLength is non-null and httpRequests keepalive is true,
// then:
if (contentLength != null && httpRequest.keepalive) {
// NOTE: keepalive is a noop outside of browser context.
}
// 11. If httpRequests referrer is a URL, then append
// `Referer`/httpRequests referrer, serialized and isomorphic encoded,
// to httpRequests header list.
if (httpRequest.referrer instanceof URL) {
httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
}
// 12. Append a request `Origin` header for httpRequest.
appendRequestOriginHeader(httpRequest)
// 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
appendFetchMetadata(httpRequest)
// 14. If httpRequests header list does not contain `User-Agent`, then
// user agents should append `User-Agent`/default `User-Agent` value to
// httpRequests header list.
if (!httpRequest.headersList.contains('user-agent')) {
httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
}
// 15. If httpRequests cache mode is "default" and httpRequests header
// list contains `If-Modified-Since`, `If-None-Match`,
// `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
// httpRequests cache mode to "no-store".
if (
httpRequest.cache === 'default' &&
(httpRequest.headersList.contains('if-modified-since') ||
httpRequest.headersList.contains('if-none-match') ||
httpRequest.headersList.contains('if-unmodified-since') ||
httpRequest.headersList.contains('if-match') ||
httpRequest.headersList.contains('if-range'))
) {
httpRequest.cache = 'no-store'
}
// 16. If httpRequests cache mode is "no-cache", httpRequests prevent
// no-cache cache-control header modification flag is unset, and
// httpRequests header list does not contain `Cache-Control`, then append
// `Cache-Control`/`max-age=0` to httpRequests header list.
if (
httpRequest.cache === 'no-cache' &&
!httpRequest.preventNoCacheCacheControlHeaderModification &&
!httpRequest.headersList.contains('cache-control')
) {
httpRequest.headersList.append('cache-control', 'max-age=0')
}
// 17. If httpRequests cache mode is "no-store" or "reload", then:
if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
// 1. If httpRequests header list does not contain `Pragma`, then append
// `Pragma`/`no-cache` to httpRequests header list.
if (!httpRequest.headersList.contains('pragma')) {
httpRequest.headersList.append('pragma', 'no-cache')
}
// 2. If httpRequests header list does not contain `Cache-Control`,
// then append `Cache-Control`/`no-cache` to httpRequests header list.
if (!httpRequest.headersList.contains('cache-control')) {
httpRequest.headersList.append('cache-control', 'no-cache')
}
}
// 18. If httpRequests header list contains `Range`, then append
// `Accept-Encoding`/`identity` to httpRequests header list.
if (httpRequest.headersList.contains('range')) {
httpRequest.headersList.append('accept-encoding', 'identity')
}
// 19. Modify httpRequests header list per HTTP. Do not append a given
// header if httpRequests header list contains that headers name.
// TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
if (!httpRequest.headersList.contains('accept-encoding')) {
if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
} else {
httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
}
}
httpRequest.headersList.delete('host')
// 20. If includeCredentials is true, then:
if (includeCredentials) {
// 1. If the user agent is not configured to block cookies for httpRequest
// (see section 7 of [COOKIES]), then:
// TODO: credentials
// 2. If httpRequests header list does not contain `Authorization`, then:
// TODO: credentials
}
// 21. If theres a proxy-authentication entry, use it as appropriate.
// TODO: proxy-authentication
// 22. Set httpCache to the result of determining the HTTP cache
// partition, given httpRequest.
// TODO: cache
// 23. If httpCache is null, then set httpRequests cache mode to
// "no-store".
if (httpCache == null) {
httpRequest.cache = 'no-store'
}
// 24. If httpRequests cache mode is neither "no-store" nor "reload",
// then:
if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
// TODO: cache
}
// 9. If aborted, then return the appropriate network error for fetchParams.
// TODO
// 10. If response is null, then:
if (response == null) {
// 1. If httpRequests cache mode is "only-if-cached", then return a
// network error.
if (httpRequest.mode === 'only-if-cached') {
return makeNetworkError('only if cached')
}
// 2. Let forwardResponse be the result of running HTTP-network fetch
// given httpFetchParams, includeCredentials, and isNewConnectionFetch.
const forwardResponse = await httpNetworkFetch(
httpFetchParams,
includeCredentials,
isNewConnectionFetch
)
// 3. If httpRequests method is unsafe and forwardResponses status is
// in the range 200 to 399, inclusive, invalidate appropriate stored
// responses in httpCache, as per the "Invalidation" chapter of HTTP
// Caching, and set storedResponse to null. [HTTP-CACHING]
if (
!safeMethodsSet.has(httpRequest.method) &&
forwardResponse.status >= 200 &&
forwardResponse.status <= 399
) {
// TODO: cache
}
// 4. If the revalidatingFlag is set and forwardResponses status is 304,
// then:
if (revalidatingFlag && forwardResponse.status === 304) {
// TODO: cache
}
// 5. If response is null, then:
if (response == null) {
// 1. Set response to forwardResponse.
response = forwardResponse
// 2. Store httpRequest and forwardResponse in httpCache, as per the
// "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
// TODO: cache
}
}
// 11. Set responses URL list to a clone of httpRequests URL list.
response.urlList = [...httpRequest.urlList]
// 12. If httpRequests header list contains `Range`, then set responses
// range-requested flag.
if (httpRequest.headersList.contains('range')) {
response.rangeRequested = true
}
// 13. Set responses request-includes-credentials to includeCredentials.
response.requestIncludesCredentials = includeCredentials
// 14. If responses status is 401, httpRequests response tainting is not
// "cors", includeCredentials is true, and requests window is an environment
// settings object, then:
// TODO
// 15. If responses status is 407, then:
if (response.status === 407) {
// 1. If requests window is "no-window", then return a network error.
if (request.window === 'no-window') {
return makeNetworkError()
}
// 2. ???
// 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams)
}
// 4. Prompt the end user as appropriate in requests window and store
// the result as a proxy-authentication entry. [HTTP-AUTH]
// TODO: Invoke some kind of callback?
// 5. Set response to the result of running HTTP-network-or-cache fetch given
// fetchParams.
// TODO
return makeNetworkError('proxy authentication required')
}
// 16. If all of the following are true
if (
// responses status is 421
response.status === 421 &&
// isNewConnectionFetch is false
!isNewConnectionFetch &&
// requests body is null, or requests body is non-null and requests bodys source is non-null
(request.body == null || request.body.source != null)
) {
// then:
// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams)
}
// 2. Set response to the result of running HTTP-network-or-cache
// fetch given fetchParams, isAuthenticationFetch, and true.
// TODO (spec): The spec doesn't specify this but we need to cancel
// the active response before we can start a new one.
// https://github.com/whatwg/fetch/issues/1293
fetchParams.controller.connection.destroy()
response = await httpNetworkOrCacheFetch(
fetchParams,
isAuthenticationFetch,
true
)
}
// 17. If isAuthenticationFetch is true, then create an authentication entry
if (isAuthenticationFetch) {
// TODO
}
// 18. Return response.
return response
}
// https://fetch.spec.whatwg.org/#http-network-fetch
async function httpNetworkFetch (
fetchParams,
includeCredentials = false,
forceNewConnection = false
) {
assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
fetchParams.controller.connection = {
abort: null,
destroyed: false,
destroy (err) {
if (!this.destroyed) {
this.destroyed = true
this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
}
}
}
// 1. Let request be fetchParamss request.
const request = fetchParams.request
// 2. Let response be null.
let response = null
// 3. Let timingInfo be fetchParamss timing info.
const timingInfo = fetchParams.timingInfo
// 4. Let httpCache be the result of determining the HTTP cache partition,
// given request.
// TODO: cache
const httpCache = null
// 5. If httpCache is null, then set requests cache mode to "no-store".
if (httpCache == null) {
request.cache = 'no-store'
}
// 6. Let networkPartitionKey be the result of determining the network
// partition key given request.
// TODO
// 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
// "no".
const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
// 8. Switch on requests mode:
if (request.mode === 'websocket') {
// Let connection be the result of obtaining a WebSocket connection,
// given requests current URL.
// TODO
} else {
// Let connection be the result of obtaining a connection, given
// networkPartitionKey, requests current URLs origin,
// includeCredentials, and forceNewConnection.
// TODO
}
// 9. Run these steps, but abort when the ongoing fetch is terminated:
// 1. If connection is failure, then return a network error.
// 2. Set timingInfos final connection timing info to the result of
// calling clamp and coarsen connection timing info with connections
// timing info, timingInfos post-redirect start time, and fetchParamss
// cross-origin isolated capability.
// 3. If connection is not an HTTP/2 connection, requests body is non-null,
// and requests bodys source is null, then append (`Transfer-Encoding`,
// `chunked`) to requests header list.
// 4. Set timingInfos final network-request start time to the coarsened
// shared current time given fetchParamss cross-origin isolated
// capability.
// 5. Set response to the result of making an HTTP request over connection
// using request with the following caveats:
// - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
// [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
// - If requests body is non-null, and requests bodys source is null,
// then the user agent may have a buffer of up to 64 kibibytes and store
// a part of requests body in that buffer. If the user agent reads from
// requests body beyond that buffers size and the user agent needs to
// resend request, then instead return a network error.
// - Set timingInfos final network-response start time to the coarsened
// shared current time given fetchParamss cross-origin isolated capability,
// immediately after the user agents HTTP parser receives the first byte
// of the response (e.g., frame header bytes for HTTP/2 or response status
// line for HTTP/1.x).
// - Wait until all the headers are transmitted.
// - Any responses whose status is in the range 100 to 199, inclusive,
// and is not 101, are to be ignored, except for the purposes of setting
// timingInfos final network-response start time above.
// - If requests header list contains `Transfer-Encoding`/`chunked` and
// response is transferred via HTTP/1.0 or older, then return a network
// error.
// - If the HTTP request results in a TLS client certificate dialog, then:
// 1. If requests window is an environment settings object, make the
// dialog available in requests window.
// 2. Otherwise, return a network error.
// To transmit requests body body, run these steps:
let requestBody = null
// 1. If body is null and fetchParamss process request end-of-body is
// non-null, then queue a fetch task given fetchParamss process request
// end-of-body and fetchParamss task destination.
if (request.body == null && fetchParams.processRequestEndOfBody) {
queueMicrotask(() => fetchParams.processRequestEndOfBody())
} else if (request.body != null) {
// 2. Otherwise, if body is non-null:
// 1. Let processBodyChunk given bytes be these steps:
const processBodyChunk = async function * (bytes) {
// 1. If the ongoing fetch is terminated, then abort these steps.
if (isCancelled(fetchParams)) {
return
}
// 2. Run this step in parallel: transmit bytes.
yield bytes
// 3. If fetchParamss process request body is non-null, then run
// fetchParamss process request body given bytess length.
fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
}
// 2. Let processEndOfBody be these steps:
const processEndOfBody = () => {
// 1. If fetchParams is canceled, then abort these steps.
if (isCancelled(fetchParams)) {
return
}
// 2. If fetchParamss process request end-of-body is non-null,
// then run fetchParamss process request end-of-body.
if (fetchParams.processRequestEndOfBody) {
fetchParams.processRequestEndOfBody()
}
}
// 3. Let processBodyError given e be these steps:
const processBodyError = (e) => {
// 1. If fetchParams is canceled, then abort these steps.
if (isCancelled(fetchParams)) {
return
}
// 2. If e is an "AbortError" DOMException, then abort fetchParamss controller.
if (e.name === 'AbortError') {
fetchParams.controller.abort()
} else {
fetchParams.controller.terminate(e)
}
}
// 4. Incrementally read requests body given processBodyChunk, processEndOfBody,
// processBodyError, and fetchParamss task destination.
requestBody = (async function * () {
try {
for await (const bytes of request.body.stream) {
yield * processBodyChunk(bytes)
}
processEndOfBody()
} catch (err) {
processBodyError(err)
}
})()
}
try {
// socket is only provided for websockets
const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
if (socket) {
response = makeResponse({ status, statusText, headersList, socket })
} else {
const iterator = body[Symbol.asyncIterator]()
fetchParams.controller.next = () => iterator.next()
response = makeResponse({ status, statusText, headersList })
}
} catch (err) {
// 10. If aborted, then:
if (err.name === 'AbortError') {
// 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
fetchParams.controller.connection.destroy()
// 2. Return the appropriate network error for fetchParams.
return makeAppropriateNetworkError(fetchParams, err)
}
return makeNetworkError(err)
}
// 11. Let pullAlgorithm be an action that resumes the ongoing fetch
// if it is suspended.
const pullAlgorithm = () => {
fetchParams.controller.resume()
}
// 12. Let cancelAlgorithm be an algorithm that aborts fetchParamss
// controller with reason, given reason.
const cancelAlgorithm = (reason) => {
fetchParams.controller.abort(reason)
}
// 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
// the user agent.
// TODO
// 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
// and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
// TODO
// 15. Let stream be a new ReadableStream.
// 16. Set up stream with pullAlgorithm set to pullAlgorithm,
// cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
// highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
if (!ReadableStream) {
ReadableStream = (__nccwpck_require__(35356).ReadableStream)
}
const stream = new ReadableStream(
{
async start (controller) {
fetchParams.controller.controller = controller
},
async pull (controller) {
await pullAlgorithm(controller)
},
async cancel (reason) {
await cancelAlgorithm(reason)
}
},
{
highWaterMark: 0,
size () {
return 1
}
}
)
// 17. Run these steps, but abort when the ongoing fetch is terminated:
// 1. Set responses body to a new body whose stream is stream.
response.body = { stream }
// 2. If response is not a network error and requests cache mode is
// not "no-store", then update response in httpCache for request.
// TODO
// 3. If includeCredentials is true and the user agent is not configured
// to block cookies for request (see section 7 of [COOKIES]), then run the
// "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
// the value of each header whose name is a byte-case-insensitive match for
// `Set-Cookie` in responses header list, if any, and requests current URL.
// TODO
// 18. If aborted, then:
// TODO
// 19. Run these steps in parallel:
// 1. Run these steps, but abort when fetchParams is canceled:
fetchParams.controller.on('terminated', onAborted)
fetchParams.controller.resume = async () => {
// 1. While true
while (true) {
// 1-3. See onData...
// 4. Set bytes to the result of handling content codings given
// codings and bytes.
let bytes
let isFailure
try {
const { done, value } = await fetchParams.controller.next()
if (isAborted(fetchParams)) {
break
}
bytes = done ? undefined : value
} catch (err) {
if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
// zlib doesn't like empty streams.
bytes = undefined
} else {
bytes = err
// err may be propagated from the result of calling readablestream.cancel,
// which might not be an error. https://github.com/nodejs/undici/issues/2009
isFailure = true
}
}
if (bytes === undefined) {
// 2. Otherwise, if the bytes transmission for responses message
// body is done normally and stream is readable, then close
// stream, finalize response for fetchParams and response, and
// abort these in-parallel steps.
readableStreamClose(fetchParams.controller.controller)
finalizeResponse(fetchParams, response)
return
}
// 5. Increase timingInfos decoded body size by bytess length.
timingInfo.decodedBodySize += bytes?.byteLength ?? 0
// 6. If bytes is failure, then terminate fetchParamss controller.
if (isFailure) {
fetchParams.controller.terminate(bytes)
return
}
// 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
// into stream.
fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
// 8. If stream is errored, then terminate the ongoing fetch.
if (isErrored(stream)) {
fetchParams.controller.terminate()
return
}
// 9. If stream doesnt need more data ask the user agent to suspend
// the ongoing fetch.
if (!fetchParams.controller.controller.desiredSize) {
return
}
}
}
// 2. If aborted, then:
function onAborted (reason) {
// 2. If fetchParams is aborted, then:
if (isAborted(fetchParams)) {
// 1. Set responses aborted flag.
response.aborted = true
// 2. If stream is readable, then error stream with the result of
// deserialize a serialized abort reason given fetchParamss
// controllers serialized abort reason and an
// implementation-defined realm.
if (isReadable(stream)) {
fetchParams.controller.controller.error(
fetchParams.controller.serializedAbortReason
)
}
} else {
// 3. Otherwise, if stream is readable, error stream with a TypeError.
if (isReadable(stream)) {
fetchParams.controller.controller.error(new TypeError('terminated', {
cause: isErrorLike(reason) ? reason : undefined
}))
}
}
// 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
// 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
fetchParams.controller.connection.destroy()
}
// 20. Return response.
return response
async function dispatch ({ body }) {
const url = requestCurrentURL(request)
/** @type {import('../..').Agent} */
const agent = fetchParams.controller.dispatcher
return new Promise((resolve, reject) => agent.dispatch(
{
path: url.pathname + url.search,
origin: url.origin,
method: request.method,
body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
headers: request.headersList.entries,
maxRedirections: 0,
upgrade: request.mode === 'websocket' ? 'websocket' : undefined
},
{
body: null,
abort: null,
onConnect (abort) {
// TODO (fix): Do we need connection here?
const { connection } = fetchParams.controller
if (connection.destroyed) {
abort(new DOMException('The operation was aborted.', 'AbortError'))
} else {
fetchParams.controller.on('terminated', abort)
this.abort = connection.abort = abort
}
},
onHeaders (status, headersList, resume, statusText) {
if (status < 200) {
return
}
let codings = []
let location = ''
const headers = new Headers()
// For H2, the headers are a plain JS object
// We distinguish between them and iterate accordingly
if (Array.isArray(headersList)) {
for (let n = 0; n < headersList.length; n += 2) {
const key = headersList[n + 0].toString('latin1')
const val = headersList[n + 1].toString('latin1')
if (key.toLowerCase() === 'content-encoding') {
// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
// "All content-coding values are case-insensitive..."
codings = val.toLowerCase().split(',').map((x) => x.trim())
} else if (key.toLowerCase() === 'location') {
location = val
}
headers[kHeadersList].append(key, val)
}
} else {
const keys = Object.keys(headersList)
for (const key of keys) {
const val = headersList[key]
if (key.toLowerCase() === 'content-encoding') {
// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
// "All content-coding values are case-insensitive..."
codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
} else if (key.toLowerCase() === 'location') {
location = val
}
headers[kHeadersList].append(key, val)
}
}
this.body = new Readable({ read: resume })
const decoders = []
const willFollow = request.redirect === 'follow' &&
location &&
redirectStatusSet.has(status)
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
for (const coding of codings) {
// https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
if (coding === 'x-gzip' || coding === 'gzip') {
decoders.push(zlib.createGunzip({
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (coding === 'deflate') {
decoders.push(zlib.createInflate())
} else if (coding === 'br') {
decoders.push(zlib.createBrotliDecompress())
} else {
decoders.length = 0
break
}
}
}
resolve({
status,
statusText,
headersList: headers[kHeadersList],
body: decoders.length
? pipeline(this.body, ...decoders, () => { })
: this.body.on('error', () => {})
})
return true
},
onData (chunk) {
if (fetchParams.controller.dump) {
return
}
// 1. If one or more bytes have been transmitted from responses
// message body, then:
// 1. Let bytes be the transmitted bytes.
const bytes = chunk
// 2. Let codings be the result of extracting header list values
// given `Content-Encoding` and responses header list.
// See pullAlgorithm.
// 3. Increase timingInfos encoded body size by bytess length.
timingInfo.encodedBodySize += bytes.byteLength
// 4. See pullAlgorithm...
return this.body.push(bytes)
},
onComplete () {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
fetchParams.controller.ended = true
this.body.push(null)
},
onError (error) {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
this.body?.destroy(error)
fetchParams.controller.terminate(error)
reject(error)
},
onUpgrade (status, headersList, socket) {
if (status !== 101) {
return
}
const headers = new Headers()
for (let n = 0; n < headersList.length; n += 2) {
const key = headersList[n + 0].toString('latin1')
const val = headersList[n + 1].toString('latin1')
headers[kHeadersList].append(key, val)
}
resolve({
status,
statusText: STATUS_CODES[status],
headersList: headers[kHeadersList],
socket
})
return true
}
}
))
}
}
module.exports = {
fetch,
Fetch,
fetching,
finalizeAndReportTiming
}
/***/ }),
/***/ 48359:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* globals AbortController */
const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(41472)
const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(10554)
const { FinalizationRegistry } = __nccwpck_require__(56436)()
const util = __nccwpck_require__(83983)
const {
isValidHTTPToken,
sameOrigin,
normalizeMethod,
makePolicyContainer,
normalizeMethodRecord
} = __nccwpck_require__(52538)
const {
forbiddenMethodsSet,
corsSafeListedMethodsSet,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache,
requestDuplex
} = __nccwpck_require__(41037)
const { kEnumerableProperty } = util
const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(15861)
const { webidl } = __nccwpck_require__(21744)
const { getGlobalOrigin } = __nccwpck_require__(71246)
const { URLSerializer } = __nccwpck_require__(685)
const { kHeadersList, kConstruct } = __nccwpck_require__(72785)
const assert = __nccwpck_require__(39491)
const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(82361)
let TransformStream = globalThis.TransformStream
const kAbortController = Symbol('abortController')
const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
signal.removeEventListener('abort', abort)
})
// https://fetch.spec.whatwg.org/#request-class
class Request {
// https://fetch.spec.whatwg.org/#dom-request
constructor (input, init = {}) {
if (input === kConstruct) {
return
}
webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
input = webidl.converters.RequestInfo(input)
init = webidl.converters.RequestInit(init)
// https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
this[kRealm] = {
settingsObject: {
baseUrl: getGlobalOrigin(),
get origin () {
return this.baseUrl?.origin
},
policyContainer: makePolicyContainer()
}
}
// 1. Let request be null.
let request = null
// 2. Let fallbackMode be null.
let fallbackMode = null
// 3. Let baseURL be thiss relevant settings objects API base URL.
const baseUrl = this[kRealm].settingsObject.baseUrl
// 4. Let signal be null.
let signal = null
// 5. If input is a string, then:
if (typeof input === 'string') {
// 1. Let parsedURL be the result of parsing input with baseURL.
// 2. If parsedURL is failure, then throw a TypeError.
let parsedURL
try {
parsedURL = new URL(input, baseUrl)
} catch (err) {
throw new TypeError('Failed to parse URL from ' + input, { cause: err })
}
// 3. If parsedURL includes credentials, then throw a TypeError.
if (parsedURL.username || parsedURL.password) {
throw new TypeError(
'Request cannot be constructed from a URL that includes credentials: ' +
input
)
}
// 4. Set request to a new request whose URL is parsedURL.
request = makeRequest({ urlList: [parsedURL] })
// 5. Set fallbackMode to "cors".
fallbackMode = 'cors'
} else {
// 6. Otherwise:
// 7. Assert: input is a Request object.
assert(input instanceof Request)
// 8. Set request to inputs request.
request = input[kState]
// 9. Set signal to inputs signal.
signal = input[kSignal]
}
// 7. Let origin be thiss relevant settings objects origin.
const origin = this[kRealm].settingsObject.origin
// 8. Let window be "client".
let window = 'client'
// 9. If requests window is an environment settings object and its origin
// is same origin with origin, then set window to requests window.
if (
request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
sameOrigin(request.window, origin)
) {
window = request.window
}
// 10. If init["window"] exists and is non-null, then throw a TypeError.
if (init.window != null) {
throw new TypeError(`'window' option '${window}' must be null`)
}
// 11. If init["window"] exists, then set window to "no-window".
if ('window' in init) {
window = 'no-window'
}
// 12. Set request to a new request with the following properties:
request = makeRequest({
// URL requests URL.
// undici implementation note: this is set as the first item in request's urlList in makeRequest
// method requests method.
method: request.method,
// header list A copy of requests header list.
// undici implementation note: headersList is cloned in makeRequest
headersList: request.headersList,
// unsafe-request flag Set.
unsafeRequest: request.unsafeRequest,
// client Thiss relevant settings object.
client: this[kRealm].settingsObject,
// window window.
window,
// priority requests priority.
priority: request.priority,
// origin requests origin. The propagation of the origin is only significant for navigation requests
// being handled by a service worker. In this scenario a request can have an origin that is different
// from the current client.
origin: request.origin,
// referrer requests referrer.
referrer: request.referrer,
// referrer policy requests referrer policy.
referrerPolicy: request.referrerPolicy,
// mode requests mode.
mode: request.mode,
// credentials mode requests credentials mode.
credentials: request.credentials,
// cache mode requests cache mode.
cache: request.cache,
// redirect mode requests redirect mode.
redirect: request.redirect,
// integrity metadata requests integrity metadata.
integrity: request.integrity,
// keepalive requests keepalive.
keepalive: request.keepalive,
// reload-navigation flag requests reload-navigation flag.
reloadNavigation: request.reloadNavigation,
// history-navigation flag requests history-navigation flag.
historyNavigation: request.historyNavigation,
// URL list A clone of requests URL list.
urlList: [...request.urlList]
})
const initHasKey = Object.keys(init).length !== 0
// 13. If init is not empty, then:
if (initHasKey) {
// 1. If requests mode is "navigate", then set it to "same-origin".
if (request.mode === 'navigate') {
request.mode = 'same-origin'
}
// 2. Unset requests reload-navigation flag.
request.reloadNavigation = false
// 3. Unset requests history-navigation flag.
request.historyNavigation = false
// 4. Set requests origin to "client".
request.origin = 'client'
// 5. Set requests referrer to "client"
request.referrer = 'client'
// 6. Set requests referrer policy to the empty string.
request.referrerPolicy = ''
// 7. Set requests URL to requests current URL.
request.url = request.urlList[request.urlList.length - 1]
// 8. Set requests URL list to « requests URL ».
request.urlList = [request.url]
}
// 14. If init["referrer"] exists, then:
if (init.referrer !== undefined) {
// 1. Let referrer be init["referrer"].
const referrer = init.referrer
// 2. If referrer is the empty string, then set requests referrer to "no-referrer".
if (referrer === '') {
request.referrer = 'no-referrer'
} else {
// 1. Let parsedReferrer be the result of parsing referrer with
// baseURL.
// 2. If parsedReferrer is failure, then throw a TypeError.
let parsedReferrer
try {
parsedReferrer = new URL(referrer, baseUrl)
} catch (err) {
throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
}
// 3. If one of the following is true
// - parsedReferrers scheme is "about" and path is the string "client"
// - parsedReferrers origin is not same origin with origin
// then set requests referrer to "client".
if (
(parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
(origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
) {
request.referrer = 'client'
} else {
// 4. Otherwise, set requests referrer to parsedReferrer.
request.referrer = parsedReferrer
}
}
}
// 15. If init["referrerPolicy"] exists, then set requests referrer policy
// to it.
if (init.referrerPolicy !== undefined) {
request.referrerPolicy = init.referrerPolicy
}
// 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
let mode
if (init.mode !== undefined) {
mode = init.mode
} else {
mode = fallbackMode
}
// 17. If mode is "navigate", then throw a TypeError.
if (mode === 'navigate') {
throw webidl.errors.exception({
header: 'Request constructor',
message: 'invalid request mode navigate.'
})
}
// 18. If mode is non-null, set requests mode to mode.
if (mode != null) {
request.mode = mode
}
// 19. If init["credentials"] exists, then set requests credentials mode
// to it.
if (init.credentials !== undefined) {
request.credentials = init.credentials
}
// 18. If init["cache"] exists, then set requests cache mode to it.
if (init.cache !== undefined) {
request.cache = init.cache
}
// 21. If requests cache mode is "only-if-cached" and requests mode is
// not "same-origin", then throw a TypeError.
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
throw new TypeError(
"'only-if-cached' can be set only with 'same-origin' mode"
)
}
// 22. If init["redirect"] exists, then set requests redirect mode to it.
if (init.redirect !== undefined) {
request.redirect = init.redirect
}
// 23. If init["integrity"] exists, then set requests integrity metadata to it.
if (init.integrity != null) {
request.integrity = String(init.integrity)
}
// 24. If init["keepalive"] exists, then set requests keepalive to it.
if (init.keepalive !== undefined) {
request.keepalive = Boolean(init.keepalive)
}
// 25. If init["method"] exists, then:
if (init.method !== undefined) {
// 1. Let method be init["method"].
let method = init.method
// 2. If method is not a method or method is a forbidden method, then
// throw a TypeError.
if (!isValidHTTPToken(method)) {
throw new TypeError(`'${method}' is not a valid HTTP method.`)
}
if (forbiddenMethodsSet.has(method.toUpperCase())) {
throw new TypeError(`'${method}' HTTP method is unsupported.`)
}
// 3. Normalize method.
method = normalizeMethodRecord[method] ?? normalizeMethod(method)
// 4. Set requests method to method.
request.method = method
}
// 26. If init["signal"] exists, then set signal to it.
if (init.signal !== undefined) {
signal = init.signal
}
// 27. Set thiss request to request.
this[kState] = request
// 28. Set thiss signal to a new AbortSignal object with thiss relevant
// Realm.
// TODO: could this be simplified with AbortSignal.any
// (https://dom.spec.whatwg.org/#dom-abortsignal-any)
const ac = new AbortController()
this[kSignal] = ac.signal
this[kSignal][kRealm] = this[kRealm]
// 29. If signal is not null, then make thiss signal follow signal.
if (signal != null) {
if (
!signal ||
typeof signal.aborted !== 'boolean' ||
typeof signal.addEventListener !== 'function'
) {
throw new TypeError(
"Failed to construct 'Request': member signal is not of type AbortSignal."
)
}
if (signal.aborted) {
ac.abort(signal.reason)
} else {
// Keep a strong ref to ac while request object
// is alive. This is needed to prevent AbortController
// from being prematurely garbage collected.
// See, https://github.com/nodejs/undici/issues/1926.
this[kAbortController] = ac
const acRef = new WeakRef(ac)
const abort = function () {
const ac = acRef.deref()
if (ac !== undefined) {
ac.abort(this.reason)
}
}
// Third-party AbortControllers may not work with these.
// See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
try {
// If the max amount of listeners is equal to the default, increase it
// This is only available in node >= v19.9.0
if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
setMaxListeners(100, signal)
} else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
setMaxListeners(100, signal)
}
} catch {}
util.addAbortListener(signal, abort)
requestFinalizer.register(ac, { signal, abort })
}
}
// 30. Set thiss headers to a new Headers object with thiss relevant
// Realm, whose header list is requests header list and guard is
// "request".
this[kHeaders] = new Headers(kConstruct)
this[kHeaders][kHeadersList] = request.headersList
this[kHeaders][kGuard] = 'request'
this[kHeaders][kRealm] = this[kRealm]
// 31. If thiss requests mode is "no-cors", then:
if (mode === 'no-cors') {
// 1. If thiss requests method is not a CORS-safelisted method,
// then throw a TypeError.
if (!corsSafeListedMethodsSet.has(request.method)) {
throw new TypeError(
`'${request.method} is unsupported in no-cors mode.`
)
}
// 2. Set thiss headerss guard to "request-no-cors".
this[kHeaders][kGuard] = 'request-no-cors'
}
// 32. If init is not empty, then:
if (initHasKey) {
/** @type {HeadersList} */
const headersList = this[kHeaders][kHeadersList]
// 1. Let headers be a copy of thiss headers and its associated header
// list.
// 2. If init["headers"] exists, then set headers to init["headers"].
const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
// 3. Empty thiss headerss header list.
headersList.clear()
// 4. If headers is a Headers object, then for each header in its header
// list, append headers name/headers value to thiss headers.
if (headers instanceof HeadersList) {
for (const [key, val] of headers) {
headersList.append(key, val)
}
// Note: Copy the `set-cookie` meta-data.
headersList.cookies = headers.cookies
} else {
// 5. Otherwise, fill thiss headers with headers.
fillHeaders(this[kHeaders], headers)
}
}
// 33. Let inputBody be inputs requests body if input is a Request
// object; otherwise null.
const inputBody = input instanceof Request ? input[kState].body : null
// 34. If either init["body"] exists and is non-null or inputBody is
// non-null, and requests method is `GET` or `HEAD`, then throw a
// TypeError.
if (
(init.body != null || inputBody != null) &&
(request.method === 'GET' || request.method === 'HEAD')
) {
throw new TypeError('Request with GET/HEAD method cannot have body.')
}
// 35. Let initBody be null.
let initBody = null
// 36. If init["body"] exists and is non-null, then:
if (init.body != null) {
// 1. Let Content-Type be null.
// 2. Set initBody and Content-Type to the result of extracting
// init["body"], with keepalive set to requests keepalive.
const [extractedBody, contentType] = extractBody(
init.body,
request.keepalive
)
initBody = extractedBody
// 3, If Content-Type is non-null and thiss headerss header list does
// not contain `Content-Type`, then append `Content-Type`/Content-Type to
// thiss headers.
if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
this[kHeaders].append('content-type', contentType)
}
}
// 37. Let inputOrInitBody be initBody if it is non-null; otherwise
// inputBody.
const inputOrInitBody = initBody ?? inputBody
// 38. If inputOrInitBody is non-null and inputOrInitBodys source is
// null, then:
if (inputOrInitBody != null && inputOrInitBody.source == null) {
// 1. If initBody is non-null and init["duplex"] does not exist,
// then throw a TypeError.
if (initBody != null && init.duplex == null) {
throw new TypeError('RequestInit: duplex option is required when sending a body.')
}
// 2. If thiss requests mode is neither "same-origin" nor "cors",
// then throw a TypeError.
if (request.mode !== 'same-origin' && request.mode !== 'cors') {
throw new TypeError(
'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
)
}
// 3. Set thiss requests use-CORS-preflight flag.
request.useCORSPreflightFlag = true
}
// 39. Let finalBody be inputOrInitBody.
let finalBody = inputOrInitBody
// 40. If initBody is null and inputBody is non-null, then:
if (initBody == null && inputBody != null) {
// 1. If input is unusable, then throw a TypeError.
if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
throw new TypeError(
'Cannot construct a Request with a Request object that has already been used.'
)
}
// 2. Set finalBody to the result of creating a proxy for inputBody.
if (!TransformStream) {
TransformStream = (__nccwpck_require__(35356).TransformStream)
}
// https://streams.spec.whatwg.org/#readablestream-create-a-proxy
const identityTransform = new TransformStream()
inputBody.stream.pipeThrough(identityTransform)
finalBody = {
source: inputBody.source,
length: inputBody.length,
stream: identityTransform.readable
}
}
// 41. Set thiss requests body to finalBody.
this[kState].body = finalBody
}
// Returns requests HTTP method, which is "GET" by default.
get method () {
webidl.brandCheck(this, Request)
// The method getter steps are to return thiss requests method.
return this[kState].method
}
// Returns the URL of request as a string.
get url () {
webidl.brandCheck(this, Request)
// The url getter steps are to return thiss requests URL, serialized.
return URLSerializer(this[kState].url)
}
// Returns a Headers object consisting of the headers associated with request.
// Note that headers added in the network layer by the user agent will not
// be accounted for in this object, e.g., the "Host" header.
get headers () {
webidl.brandCheck(this, Request)
// The headers getter steps are to return thiss headers.
return this[kHeaders]
}
// Returns the kind of resource requested by request, e.g., "document"
// or "script".
get destination () {
webidl.brandCheck(this, Request)
// The destination getter are to return thiss requests destination.
return this[kState].destination
}
// Returns the referrer of request. Its value can be a same-origin URL if
// explicitly set in init, the empty string to indicate no referrer, and
// "about:client" when defaulting to the globals default. This is used
// during fetching to determine the value of the `Referer` header of the
// request being made.
get referrer () {
webidl.brandCheck(this, Request)
// 1. If thiss requests referrer is "no-referrer", then return the
// empty string.
if (this[kState].referrer === 'no-referrer') {
return ''
}
// 2. If thiss requests referrer is "client", then return
// "about:client".
if (this[kState].referrer === 'client') {
return 'about:client'
}
// Return thiss requests referrer, serialized.
return this[kState].referrer.toString()
}
// Returns the referrer policy associated with request.
// This is used during fetching to compute the value of the requests
// referrer.
get referrerPolicy () {
webidl.brandCheck(this, Request)
// The referrerPolicy getter steps are to return thiss requests referrer policy.
return this[kState].referrerPolicy
}
// Returns the mode associated with request, which is a string indicating
// whether the request will use CORS, or will be restricted to same-origin
// URLs.
get mode () {
webidl.brandCheck(this, Request)
// The mode getter steps are to return thiss requests mode.
return this[kState].mode
}
// Returns the credentials mode associated with request,
// which is a string indicating whether credentials will be sent with the
// request always, never, or only when sent to a same-origin URL.
get credentials () {
// The credentials getter steps are to return thiss requests credentials mode.
return this[kState].credentials
}
// Returns the cache mode associated with request,
// which is a string indicating how the request will
// interact with the browsers cache when fetching.
get cache () {
webidl.brandCheck(this, Request)
// The cache getter steps are to return thiss requests cache mode.
return this[kState].cache
}
// Returns the redirect mode associated with request,
// which is a string indicating how redirects for the
// request will be handled during fetching. A request
// will follow redirects by default.
get redirect () {
webidl.brandCheck(this, Request)
// The redirect getter steps are to return thiss requests redirect mode.
return this[kState].redirect
}
// Returns requests subresource integrity metadata, which is a
// cryptographic hash of the resource being fetched. Its value
// consists of multiple hashes separated by whitespace. [SRI]
get integrity () {
webidl.brandCheck(this, Request)
// The integrity getter steps are to return thiss requests integrity
// metadata.
return this[kState].integrity
}
// Returns a boolean indicating whether or not request can outlive the
// global in which it was created.
get keepalive () {
webidl.brandCheck(this, Request)
// The keepalive getter steps are to return thiss requests keepalive.
return this[kState].keepalive
}
// Returns a boolean indicating whether or not request is for a reload
// navigation.
get isReloadNavigation () {
webidl.brandCheck(this, Request)
// The isReloadNavigation getter steps are to return true if thiss
// requests reload-navigation flag is set; otherwise false.
return this[kState].reloadNavigation
}
// Returns a boolean indicating whether or not request is for a history
// navigation (a.k.a. back-foward navigation).
get isHistoryNavigation () {
webidl.brandCheck(this, Request)
// The isHistoryNavigation getter steps are to return true if thiss requests
// history-navigation flag is set; otherwise false.
return this[kState].historyNavigation
}
// Returns the signal associated with request, which is an AbortSignal
// object indicating whether or not request has been aborted, and its
// abort event handler.
get signal () {
webidl.brandCheck(this, Request)
// The signal getter steps are to return thiss signal.
return this[kSignal]
}
get body () {
webidl.brandCheck(this, Request)
return this[kState].body ? this[kState].body.stream : null
}
get bodyUsed () {
webidl.brandCheck(this, Request)
return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
get duplex () {
webidl.brandCheck(this, Request)
return 'half'
}
// Returns a clone of request.
clone () {
webidl.brandCheck(this, Request)
// 1. If this is unusable, then throw a TypeError.
if (this.bodyUsed || this.body?.locked) {
throw new TypeError('unusable')
}
// 2. Let clonedRequest be the result of cloning thiss request.
const clonedRequest = cloneRequest(this[kState])
// 3. Let clonedRequestObject be the result of creating a Request object,
// given clonedRequest, thiss headerss guard, and thiss relevant Realm.
const clonedRequestObject = new Request(kConstruct)
clonedRequestObject[kState] = clonedRequest
clonedRequestObject[kRealm] = this[kRealm]
clonedRequestObject[kHeaders] = new Headers(kConstruct)
clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
// 4. Make clonedRequestObjects signal follow thiss signal.
const ac = new AbortController()
if (this.signal.aborted) {
ac.abort(this.signal.reason)
} else {
util.addAbortListener(
this.signal,
() => {
ac.abort(this.signal.reason)
}
)
}
clonedRequestObject[kSignal] = ac.signal
// 4. Return clonedRequestObject.
return clonedRequestObject
}
}
mixinBody(Request)
function makeRequest (init) {
// https://fetch.spec.whatwg.org/#requests
const request = {
method: 'GET',
localURLsOnly: false,
unsafeRequest: false,
body: null,
client: null,
reservedClient: null,
replacesClientId: '',
window: 'client',
keepalive: false,
serviceWorkers: 'all',
initiator: '',
destination: '',
priority: null,
origin: 'client',
policyContainer: 'client',
referrer: 'client',
referrerPolicy: '',
mode: 'no-cors',
useCORSPreflightFlag: false,
credentials: 'same-origin',
useCredentials: false,
cache: 'default',
redirect: 'follow',
integrity: '',
cryptoGraphicsNonceMetadata: '',
parserMetadata: '',
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: 'basic',
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
...init,
headersList: init.headersList
? new HeadersList(init.headersList)
: new HeadersList()
}
request.url = request.urlList[0]
return request
}
// https://fetch.spec.whatwg.org/#concept-request-clone
function cloneRequest (request) {
// To clone a request request, run these steps:
// 1. Let newRequest be a copy of request, except for its body.
const newRequest = makeRequest({ ...request, body: null })
// 2. If requests body is non-null, set newRequests body to the
// result of cloning requests body.
if (request.body != null) {
newRequest.body = cloneBody(request.body)
}
// 3. Return newRequest.
return newRequest
}
Object.defineProperties(Request.prototype, {
method: kEnumerableProperty,
url: kEnumerableProperty,
headers: kEnumerableProperty,
redirect: kEnumerableProperty,
clone: kEnumerableProperty,
signal: kEnumerableProperty,
duplex: kEnumerableProperty,
destination: kEnumerableProperty,
body: kEnumerableProperty,
bodyUsed: kEnumerableProperty,
isHistoryNavigation: kEnumerableProperty,
isReloadNavigation: kEnumerableProperty,
keepalive: kEnumerableProperty,
integrity: kEnumerableProperty,
cache: kEnumerableProperty,
credentials: kEnumerableProperty,
attribute: kEnumerableProperty,
referrerPolicy: kEnumerableProperty,
referrer: kEnumerableProperty,
mode: kEnumerableProperty,
[Symbol.toStringTag]: {
value: 'Request',
configurable: true
}
})
webidl.converters.Request = webidl.interfaceConverter(
Request
)
// https://fetch.spec.whatwg.org/#requestinfo
webidl.converters.RequestInfo = function (V) {
if (typeof V === 'string') {
return webidl.converters.USVString(V)
}
if (V instanceof Request) {
return webidl.converters.Request(V)
}
return webidl.converters.USVString(V)
}
webidl.converters.AbortSignal = webidl.interfaceConverter(
AbortSignal
)
// https://fetch.spec.whatwg.org/#requestinit
webidl.converters.RequestInit = webidl.dictionaryConverter([
{
key: 'method',
converter: webidl.converters.ByteString
},
{
key: 'headers',
converter: webidl.converters.HeadersInit
},
{
key: 'body',
converter: webidl.nullableConverter(
webidl.converters.BodyInit
)
},
{
key: 'referrer',
converter: webidl.converters.USVString
},
{
key: 'referrerPolicy',
converter: webidl.converters.DOMString,
// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
allowedValues: referrerPolicy
},
{
key: 'mode',
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#concept-request-mode
allowedValues: requestMode
},
{
key: 'credentials',
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestcredentials
allowedValues: requestCredentials
},
{
key: 'cache',
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestcache
allowedValues: requestCache
},
{
key: 'redirect',
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestredirect
allowedValues: requestRedirect
},
{
key: 'integrity',
converter: webidl.converters.DOMString
},
{
key: 'keepalive',
converter: webidl.converters.boolean
},
{
key: 'signal',
converter: webidl.nullableConverter(
(signal) => webidl.converters.AbortSignal(
signal,
{ strict: false }
)
)
},
{
key: 'window',
converter: webidl.converters.any
},
{
key: 'duplex',
converter: webidl.converters.DOMString,
allowedValues: requestDuplex
}
])
module.exports = { Request, makeRequest }
/***/ }),
/***/ 27823:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { Headers, HeadersList, fill } = __nccwpck_require__(10554)
const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(41472)
const util = __nccwpck_require__(83983)
const { kEnumerableProperty } = util
const {
isValidReasonPhrase,
isCancelled,
isAborted,
isBlobLike,
serializeJavascriptValueToJSONString,
isErrorLike,
isomorphicEncode
} = __nccwpck_require__(52538)
const {
redirectStatusSet,
nullBodyStatus,
DOMException
} = __nccwpck_require__(41037)
const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861)
const { webidl } = __nccwpck_require__(21744)
const { FormData } = __nccwpck_require__(72015)
const { getGlobalOrigin } = __nccwpck_require__(71246)
const { URLSerializer } = __nccwpck_require__(685)
const { kHeadersList, kConstruct } = __nccwpck_require__(72785)
const assert = __nccwpck_require__(39491)
const { types } = __nccwpck_require__(73837)
const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream)
const textEncoder = new TextEncoder('utf-8')
// https://fetch.spec.whatwg.org/#response-class
class Response {
// Creates network error Response.
static error () {
// TODO
const relevantRealm = { settingsObject: {} }
// The static error() method steps are to return the result of creating a
// Response object, given a new network error, "immutable", and thiss
// relevant Realm.
const responseObject = new Response()
responseObject[kState] = makeNetworkError()
responseObject[kRealm] = relevantRealm
responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
responseObject[kHeaders][kGuard] = 'immutable'
responseObject[kHeaders][kRealm] = relevantRealm
return responseObject
}
// https://fetch.spec.whatwg.org/#dom-response-json
static json (data, init = {}) {
webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
if (init !== null) {
init = webidl.converters.ResponseInit(init)
}
// 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
const bytes = textEncoder.encode(
serializeJavascriptValueToJSONString(data)
)
// 2. Let body be the result of extracting bytes.
const body = extractBody(bytes)
// 3. Let responseObject be the result of creating a Response object, given a new response,
// "response", and thiss relevant Realm.
const relevantRealm = { settingsObject: {} }
const responseObject = new Response()
responseObject[kRealm] = relevantRealm
responseObject[kHeaders][kGuard] = 'response'
responseObject[kHeaders][kRealm] = relevantRealm
// 4. Perform initialize a response given responseObject, init, and (body, "application/json").
initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
// 5. Return responseObject.
return responseObject
}
// Creates a redirect Response that redirects to url with status status.
static redirect (url, status = 302) {
const relevantRealm = { settingsObject: {} }
webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
url = webidl.converters.USVString(url)
status = webidl.converters['unsigned short'](status)
// 1. Let parsedURL be the result of parsing url with current settings
// objects API base URL.
// 2. If parsedURL is failure, then throw a TypeError.
// TODO: base-URL?
let parsedURL
try {
parsedURL = new URL(url, getGlobalOrigin())
} catch (err) {
throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
cause: err
})
}
// 3. If status is not a redirect status, then throw a RangeError.
if (!redirectStatusSet.has(status)) {
throw new RangeError('Invalid status code ' + status)
}
// 4. Let responseObject be the result of creating a Response object,
// given a new response, "immutable", and thiss relevant Realm.
const responseObject = new Response()
responseObject[kRealm] = relevantRealm
responseObject[kHeaders][kGuard] = 'immutable'
responseObject[kHeaders][kRealm] = relevantRealm
// 5. Set responseObjects responses status to status.
responseObject[kState].status = status
// 6. Let value be parsedURL, serialized and isomorphic encoded.
const value = isomorphicEncode(URLSerializer(parsedURL))
// 7. Append `Location`/value to responseObjects responses header list.
responseObject[kState].headersList.append('location', value)
// 8. Return responseObject.
return responseObject
}
// https://fetch.spec.whatwg.org/#dom-response
constructor (body = null, init = {}) {
if (body !== null) {
body = webidl.converters.BodyInit(body)
}
init = webidl.converters.ResponseInit(init)
// TODO
this[kRealm] = { settingsObject: {} }
// 1. Set thiss response to a new response.
this[kState] = makeResponse({})
// 2. Set thiss headers to a new Headers object with thiss relevant
// Realm, whose header list is thiss responses header list and guard
// is "response".
this[kHeaders] = new Headers(kConstruct)
this[kHeaders][kGuard] = 'response'
this[kHeaders][kHeadersList] = this[kState].headersList
this[kHeaders][kRealm] = this[kRealm]
// 3. Let bodyWithType be null.
let bodyWithType = null
// 4. If body is non-null, then set bodyWithType to the result of extracting body.
if (body != null) {
const [extractedBody, type] = extractBody(body)
bodyWithType = { body: extractedBody, type }
}
// 5. Perform initialize a response given this, init, and bodyWithType.
initializeResponse(this, init, bodyWithType)
}
// Returns responses type, e.g., "cors".
get type () {
webidl.brandCheck(this, Response)
// The type getter steps are to return thiss responses type.
return this[kState].type
}
// Returns responses URL, if it has one; otherwise the empty string.
get url () {
webidl.brandCheck(this, Response)
const urlList = this[kState].urlList
// The url getter steps are to return the empty string if thiss
// responses URL is null; otherwise thiss responses URL,
// serialized with exclude fragment set to true.
const url = urlList[urlList.length - 1] ?? null
if (url === null) {
return ''
}
return URLSerializer(url, true)
}
// Returns whether response was obtained through a redirect.
get redirected () {
webidl.brandCheck(this, Response)
// The redirected getter steps are to return true if thiss responses URL
// list has more than one item; otherwise false.
return this[kState].urlList.length > 1
}
// Returns responses status.
get status () {
webidl.brandCheck(this, Response)
// The status getter steps are to return thiss responses status.
return this[kState].status
}
// Returns whether responses status is an ok status.
get ok () {
webidl.brandCheck(this, Response)
// The ok getter steps are to return true if thiss responses status is an
// ok status; otherwise false.
return this[kState].status >= 200 && this[kState].status <= 299
}
// Returns responses status message.
get statusText () {
webidl.brandCheck(this, Response)
// The statusText getter steps are to return thiss responses status
// message.
return this[kState].statusText
}
// Returns responses headers as Headers.
get headers () {
webidl.brandCheck(this, Response)
// The headers getter steps are to return thiss headers.
return this[kHeaders]
}
get body () {
webidl.brandCheck(this, Response)
return this[kState].body ? this[kState].body.stream : null
}
get bodyUsed () {
webidl.brandCheck(this, Response)
return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
// Returns a clone of response.
clone () {
webidl.brandCheck(this, Response)
// 1. If this is unusable, then throw a TypeError.
if (this.bodyUsed || (this.body && this.body.locked)) {
throw webidl.errors.exception({
header: 'Response.clone',
message: 'Body has already been consumed.'
})
}
// 2. Let clonedResponse be the result of cloning thiss response.
const clonedResponse = cloneResponse(this[kState])
// 3. Return the result of creating a Response object, given
// clonedResponse, thiss headerss guard, and thiss relevant Realm.
const clonedResponseObject = new Response()
clonedResponseObject[kState] = clonedResponse
clonedResponseObject[kRealm] = this[kRealm]
clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
return clonedResponseObject
}
}
mixinBody(Response)
Object.defineProperties(Response.prototype, {
type: kEnumerableProperty,
url: kEnumerableProperty,
status: kEnumerableProperty,
ok: kEnumerableProperty,
redirected: kEnumerableProperty,
statusText: kEnumerableProperty,
headers: kEnumerableProperty,
clone: kEnumerableProperty,
body: kEnumerableProperty,
bodyUsed: kEnumerableProperty,
[Symbol.toStringTag]: {
value: 'Response',
configurable: true
}
})
Object.defineProperties(Response, {
json: kEnumerableProperty,
redirect: kEnumerableProperty,
error: kEnumerableProperty
})
// https://fetch.spec.whatwg.org/#concept-response-clone
function cloneResponse (response) {
// To clone a response response, run these steps:
// 1. If response is a filtered response, then return a new identical
// filtered response whose internal response is a clone of responses
// internal response.
if (response.internalResponse) {
return filterResponse(
cloneResponse(response.internalResponse),
response.type
)
}
// 2. Let newResponse be a copy of response, except for its body.
const newResponse = makeResponse({ ...response, body: null })
// 3. If responses body is non-null, then set newResponses body to the
// result of cloning responses body.
if (response.body != null) {
newResponse.body = cloneBody(response.body)
}
// 4. Return newResponse.
return newResponse
}
function makeResponse (init) {
return {
aborted: false,
rangeRequested: false,
timingAllowPassed: false,
requestIncludesCredentials: false,
type: 'default',
status: 200,
timingInfo: null,
cacheState: '',
statusText: '',
...init,
headersList: init.headersList
? new HeadersList(init.headersList)
: new HeadersList(),
urlList: init.urlList ? [...init.urlList] : []
}
}
function makeNetworkError (reason) {
const isError = isErrorLike(reason)
return makeResponse({
type: 'error',
status: 0,
error: isError
? reason
: new Error(reason ? String(reason) : reason),
aborted: reason && reason.name === 'AbortError'
})
}
function makeFilteredResponse (response, state) {
state = {
internalResponse: response,
...state
}
return new Proxy(response, {
get (target, p) {
return p in state ? state[p] : target[p]
},
set (target, p, value) {
assert(!(p in state))
target[p] = value
return true
}
})
}
// https://fetch.spec.whatwg.org/#concept-filtered-response
function filterResponse (response, type) {
// Set response to the following filtered response with response as its
// internal response, depending on requests response tainting:
if (type === 'basic') {
// A basic filtered response is a filtered response whose type is "basic"
// and header list excludes any headers in internal responses header list
// whose name is a forbidden response-header name.
// Note: undici does not implement forbidden response-header names
return makeFilteredResponse(response, {
type: 'basic',
headersList: response.headersList
})
} else if (type === 'cors') {
// A CORS filtered response is a filtered response whose type is "cors"
// and header list excludes any headers in internal responses header
// list whose name is not a CORS-safelisted response-header name, given
// internal responses CORS-exposed header-name list.
// Note: undici does not implement CORS-safelisted response-header names
return makeFilteredResponse(response, {
type: 'cors',
headersList: response.headersList
})
} else if (type === 'opaque') {
// An opaque filtered response is a filtered response whose type is
// "opaque", URL list is the empty list, status is 0, status message
// is the empty byte sequence, header list is empty, and body is null.
return makeFilteredResponse(response, {
type: 'opaque',
urlList: Object.freeze([]),
status: 0,
statusText: '',
body: null
})
} else if (type === 'opaqueredirect') {
// An opaque-redirect filtered response is a filtered response whose type
// is "opaqueredirect", status is 0, status message is the empty byte
// sequence, header list is empty, and body is null.
return makeFilteredResponse(response, {
type: 'opaqueredirect',
status: 0,
statusText: '',
headersList: [],
body: null
})
} else {
assert(false)
}
}
// https://fetch.spec.whatwg.org/#appropriate-network-error
function makeAppropriateNetworkError (fetchParams, err = null) {
// 1. Assert: fetchParams is canceled.
assert(isCancelled(fetchParams))
// 2. Return an aborted network error if fetchParams is aborted;
// otherwise return a network error.
return isAborted(fetchParams)
? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
: makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
}
// https://whatpr.org/fetch/1392.html#initialize-a-response
function initializeResponse (response, init, body) {
// 1. If init["status"] is not in the range 200 to 599, inclusive, then
// throw a RangeError.
if (init.status !== null && (init.status < 200 || init.status > 599)) {
throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
}
// 2. If init["statusText"] does not match the reason-phrase token production,
// then throw a TypeError.
if ('statusText' in init && init.statusText != null) {
// See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
if (!isValidReasonPhrase(String(init.statusText))) {
throw new TypeError('Invalid statusText')
}
}
// 3. Set responses responses status to init["status"].
if ('status' in init && init.status != null) {
response[kState].status = init.status
}
// 4. Set responses responses status message to init["statusText"].
if ('statusText' in init && init.statusText != null) {
response[kState].statusText = init.statusText
}
// 5. If init["headers"] exists, then fill responses headers with init["headers"].
if ('headers' in init && init.headers != null) {
fill(response[kHeaders], init.headers)
}
// 6. If body was given, then:
if (body) {
// 1. If response's status is a null body status, then throw a TypeError.
if (nullBodyStatus.includes(response.status)) {
throw webidl.errors.exception({
header: 'Response constructor',
message: 'Invalid response status code ' + response.status
})
}
// 2. Set response's body to body's body.
response[kState].body = body.body
// 3. If body's type is non-null and response's header list does not contain
// `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
response[kState].headersList.append('content-type', body.type)
}
}
}
webidl.converters.ReadableStream = webidl.interfaceConverter(
ReadableStream
)
webidl.converters.FormData = webidl.interfaceConverter(
FormData
)
webidl.converters.URLSearchParams = webidl.interfaceConverter(
URLSearchParams
)
// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
webidl.converters.XMLHttpRequestBodyInit = function (V) {
if (typeof V === 'string') {
return webidl.converters.USVString(V)
}
if (isBlobLike(V)) {
return webidl.converters.Blob(V, { strict: false })
}
if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
return webidl.converters.BufferSource(V)
}
if (util.isFormDataLike(V)) {
return webidl.converters.FormData(V, { strict: false })
}
if (V instanceof URLSearchParams) {
return webidl.converters.URLSearchParams(V)
}
return webidl.converters.DOMString(V)
}
// https://fetch.spec.whatwg.org/#bodyinit
webidl.converters.BodyInit = function (V) {
if (V instanceof ReadableStream) {
return webidl.converters.ReadableStream(V)
}
// Note: the spec doesn't include async iterables,
// this is an undici extension.
if (V?.[Symbol.asyncIterator]) {
return V
}
return webidl.converters.XMLHttpRequestBodyInit(V)
}
webidl.converters.ResponseInit = webidl.dictionaryConverter([
{
key: 'status',
converter: webidl.converters['unsigned short'],
defaultValue: 200
},
{
key: 'statusText',
converter: webidl.converters.ByteString,
defaultValue: ''
},
{
key: 'headers',
converter: webidl.converters.HeadersInit
}
])
module.exports = {
makeNetworkError,
makeResponse,
makeAppropriateNetworkError,
filterResponse,
Response,
cloneResponse
}
/***/ }),
/***/ 15861:
/***/ ((module) => {
"use strict";
module.exports = {
kUrl: Symbol('url'),
kHeaders: Symbol('headers'),
kSignal: Symbol('signal'),
kState: Symbol('state'),
kGuard: Symbol('guard'),
kRealm: Symbol('realm')
}
/***/ }),
/***/ 52538:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(41037)
const { getGlobalOrigin } = __nccwpck_require__(71246)
const { performance } = __nccwpck_require__(4074)
const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(83983)
const assert = __nccwpck_require__(39491)
const { isUint8Array } = __nccwpck_require__(29830)
let supportedHashes = []
// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
/** @type {import('crypto')|undefined} */
let crypto
try {
crypto = __nccwpck_require__(6113)
const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
/* c8 ignore next 3 */
} catch {
}
function responseURL (response) {
// https://fetch.spec.whatwg.org/#responses
// A response has an associated URL. It is a pointer to the last URL
// in responses URL list and null if responses URL list is empty.
const urlList = response.urlList
const length = urlList.length
return length === 0 ? null : urlList[length - 1].toString()
}
// https://fetch.spec.whatwg.org/#concept-response-location-url
function responseLocationURL (response, requestFragment) {
// 1. If responses status is not a redirect status, then return null.
if (!redirectStatusSet.has(response.status)) {
return null
}
// 2. Let location be the result of extracting header list values given
// `Location` and responses header list.
let location = response.headersList.get('location')
// 3. If location is a header value, then set location to the result of
// parsing location with responses URL.
if (location !== null && isValidHeaderValue(location)) {
location = new URL(location, responseURL(response))
}
// 4. If location is a URL whose fragment is null, then set locations
// fragment to requestFragment.
if (location && !location.hash) {
location.hash = requestFragment
}
// 5. Return location.
return location
}
/** @returns {URL} */
function requestCurrentURL (request) {
return request.urlList[request.urlList.length - 1]
}
function requestBadPort (request) {
// 1. Let url be requests current URL.
const url = requestCurrentURL(request)
// 2. If urls scheme is an HTTP(S) scheme and urls port is a bad port,
// then return blocked.
if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
return 'blocked'
}
// 3. Return allowed.
return 'allowed'
}
function isErrorLike (object) {
return object instanceof Error || (
object?.constructor?.name === 'Error' ||
object?.constructor?.name === 'DOMException'
)
}
// Check whether |statusText| is a ByteString and
// matches the Reason-Phrase token production.
// RFC 2616: https://tools.ietf.org/html/rfc2616
// RFC 7230: https://tools.ietf.org/html/rfc7230
// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
function isValidReasonPhrase (statusText) {
for (let i = 0; i < statusText.length; ++i) {
const c = statusText.charCodeAt(i)
if (
!(
(
c === 0x09 || // HTAB
(c >= 0x20 && c <= 0x7e) || // SP / VCHAR
(c >= 0x80 && c <= 0xff)
) // obs-text
)
) {
return false
}
}
return true
}
/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2.6
* @param {number} c
*/
function isTokenCharCode (c) {
switch (c) {
case 0x22:
case 0x28:
case 0x29:
case 0x2c:
case 0x2f:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3d:
case 0x3e:
case 0x3f:
case 0x40:
case 0x5b:
case 0x5c:
case 0x5d:
case 0x7b:
case 0x7d:
// DQUOTE and "(),/:;<=>?@[\]{}"
return false
default:
// VCHAR %x21-7E
return c >= 0x21 && c <= 0x7e
}
}
/**
* @param {string} characters
*/
function isValidHTTPToken (characters) {
if (characters.length === 0) {
return false
}
for (let i = 0; i < characters.length; ++i) {
if (!isTokenCharCode(characters.charCodeAt(i))) {
return false
}
}
return true
}
/**
* @see https://fetch.spec.whatwg.org/#header-name
* @param {string} potentialValue
*/
function isValidHeaderName (potentialValue) {
return isValidHTTPToken(potentialValue)
}
/**
* @see https://fetch.spec.whatwg.org/#header-value
* @param {string} potentialValue
*/
function isValidHeaderValue (potentialValue) {
// - Has no leading or trailing HTTP tab or space bytes.
// - Contains no 0x00 (NUL) or HTTP newline bytes.
if (
potentialValue.startsWith('\t') ||
potentialValue.startsWith(' ') ||
potentialValue.endsWith('\t') ||
potentialValue.endsWith(' ')
) {
return false
}
if (
potentialValue.includes('\0') ||
potentialValue.includes('\r') ||
potentialValue.includes('\n')
) {
return false
}
return true
}
// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
// Given a request request and a response actualResponse, this algorithm
// updates requests referrer policy according to the Referrer-Policy
// header (if any) in actualResponse.
// 1. Let policy be the result of executing § 8.1 Parse a referrer policy
// from a Referrer-Policy header on actualResponse.
// 8.1 Parse a referrer policy from a Referrer-Policy header
// 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and responses header list.
const { headersList } = actualResponse
// 2. Let policy be the empty string.
// 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
// 4. Return policy.
const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
// Note: As the referrer-policy can contain multiple policies
// separated by comma, we need to loop through all of them
// and pick the first valid one.
// Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
let policy = ''
if (policyHeader.length > 0) {
// The right-most policy takes precedence.
// The left-most policy is the fallback.
for (let i = policyHeader.length; i !== 0; i--) {
const token = policyHeader[i - 1].trim()
if (referrerPolicyTokens.has(token)) {
policy = token
break
}
}
}
// 2. If policy is not the empty string, then set requests referrer policy to policy.
if (policy !== '') {
request.referrerPolicy = policy
}
}
// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
function crossOriginResourcePolicyCheck () {
// TODO
return 'allowed'
}
// https://fetch.spec.whatwg.org/#concept-cors-check
function corsCheck () {
// TODO
return 'success'
}
// https://fetch.spec.whatwg.org/#concept-tao-check
function TAOCheck () {
// TODO
return 'success'
}
function appendFetchMetadata (httpRequest) {
// https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
// TODO
// https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
// 1. Assert: rs url is a potentially trustworthy URL.
// TODO
// 2. Let header be a Structured Header whose value is a token.
let header = null
// 3. Set headers value to rs mode.
header = httpRequest.mode
// 4. Set a structured field value `Sec-Fetch-Mode`/header in rs header list.
httpRequest.headersList.set('sec-fetch-mode', header)
// https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
// TODO
// https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
// TODO
}
// https://fetch.spec.whatwg.org/#append-a-request-origin-header
function appendRequestOriginHeader (request) {
// 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
let serializedOrigin = request.origin
// 2. If requests response tainting is "cors" or requests mode is "websocket", then append (`Origin`, serializedOrigin) to requests header list.
if (request.responseTainting === 'cors' || request.mode === 'websocket') {
if (serializedOrigin) {
request.headersList.append('origin', serializedOrigin)
}
// 3. Otherwise, if requests method is neither `GET` nor `HEAD`, then:
} else if (request.method !== 'GET' && request.method !== 'HEAD') {
// 1. Switch on requests referrer policy:
switch (request.referrerPolicy) {
case 'no-referrer':
// Set serializedOrigin to `null`.
serializedOrigin = null
break
case 'no-referrer-when-downgrade':
case 'strict-origin':
case 'strict-origin-when-cross-origin':
// If requests origin is a tuple origin, its scheme is "https", and requests current URLs scheme is not "https", then set serializedOrigin to `null`.
if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
serializedOrigin = null
}
break
case 'same-origin':
// If requests origin is not same origin with requests current URLs origin, then set serializedOrigin to `null`.
if (!sameOrigin(request, requestCurrentURL(request))) {
serializedOrigin = null
}
break
default:
// Do nothing.
}
if (serializedOrigin) {
// 2. Append (`Origin`, serializedOrigin) to requests header list.
request.headersList.append('origin', serializedOrigin)
}
}
}
function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
// TODO
return performance.now()
}
// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
function createOpaqueTimingInfo (timingInfo) {
return {
startTime: timingInfo.startTime ?? 0,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: timingInfo.startTime ?? 0,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 0,
decodedBodySize: 0,
finalConnectionTimingInfo: null
}
}
// https://html.spec.whatwg.org/multipage/origin.html#policy-container
function makePolicyContainer () {
// Note: the fetch spec doesn't make use of embedder policy or CSP list
return {
referrerPolicy: 'strict-origin-when-cross-origin'
}
}
// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
function clonePolicyContainer (policyContainer) {
return {
referrerPolicy: policyContainer.referrerPolicy
}
}
// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
function determineRequestsReferrer (request) {
// 1. Let policy be request's referrer policy.
const policy = request.referrerPolicy
// Note: policy cannot (shouldn't) be null or an empty string.
assert(policy)
// 2. Let environment be requests client.
let referrerSource = null
// 3. Switch on requests referrer:
if (request.referrer === 'client') {
// Note: node isn't a browser and doesn't implement document/iframes,
// so we bypass this step and replace it with our own.
const globalOrigin = getGlobalOrigin()
if (!globalOrigin || globalOrigin.origin === 'null') {
return 'no-referrer'
}
// note: we need to clone it as it's mutated
referrerSource = new URL(globalOrigin)
} else if (request.referrer instanceof URL) {
// Let referrerSource be requests referrer.
referrerSource = request.referrer
}
// 4. Let requests referrerURL be the result of stripping referrerSource for
// use as a referrer.
let referrerURL = stripURLForReferrer(referrerSource)
// 5. Let referrerOrigin be the result of stripping referrerSource for use as
// a referrer, with the origin-only flag set to true.
const referrerOrigin = stripURLForReferrer(referrerSource, true)
// 6. If the result of serializing referrerURL is a string whose length is
// greater than 4096, set referrerURL to referrerOrigin.
if (referrerURL.toString().length > 4096) {
referrerURL = referrerOrigin
}
const areSameOrigin = sameOrigin(request, referrerURL)
const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
!isURLPotentiallyTrustworthy(request.url)
// 8. Execute the switch statements corresponding to the value of policy:
switch (policy) {
case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
case 'unsafe-url': return referrerURL
case 'same-origin':
return areSameOrigin ? referrerOrigin : 'no-referrer'
case 'origin-when-cross-origin':
return areSameOrigin ? referrerURL : referrerOrigin
case 'strict-origin-when-cross-origin': {
const currentURL = requestCurrentURL(request)
// 1. If the origin of referrerURL and the origin of requests current
// URL are the same, then return referrerURL.
if (sameOrigin(referrerURL, currentURL)) {
return referrerURL
}
// 2. If referrerURL is a potentially trustworthy URL and requests
// current URL is not a potentially trustworthy URL, then return no
// referrer.
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
return 'no-referrer'
}
// 3. Return referrerOrigin.
return referrerOrigin
}
case 'strict-origin': // eslint-disable-line
/**
* 1. If referrerURL is a potentially trustworthy URL and
* requests current URL is not a potentially trustworthy URL,
* then return no referrer.
* 2. Return referrerOrigin
*/
case 'no-referrer-when-downgrade': // eslint-disable-line
/**
* 1. If referrerURL is a potentially trustworthy URL and
* requests current URL is not a potentially trustworthy URL,
* then return no referrer.
* 2. Return referrerOrigin
*/
default: // eslint-disable-line
return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
}
}
/**
* @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
* @param {URL} url
* @param {boolean|undefined} originOnly
*/
function stripURLForReferrer (url, originOnly) {
// 1. Assert: url is a URL.
assert(url instanceof URL)
// 2. If urls scheme is a local scheme, then return no referrer.
if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
return 'no-referrer'
}
// 3. Set urls username to the empty string.
url.username = ''
// 4. Set urls password to the empty string.
url.password = ''
// 5. Set urls fragment to null.
url.hash = ''
// 6. If the origin-only flag is true, then:
if (originOnly) {
// 1. Set urls path to « the empty string ».
url.pathname = ''
// 2. Set urls query to null.
url.search = ''
}
// 7. Return url.
return url
}
function isURLPotentiallyTrustworthy (url) {
if (!(url instanceof URL)) {
return false
}
// If child of about, return true
if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
return true
}
// If scheme is data, return true
if (url.protocol === 'data:') return true
// If file, return true
if (url.protocol === 'file:') return true
return isOriginPotentiallyTrustworthy(url.origin)
function isOriginPotentiallyTrustworthy (origin) {
// If origin is explicitly null, return false
if (origin == null || origin === 'null') return false
const originAsURL = new URL(origin)
// If secure, return true
if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
return true
}
// If localhost or variants, return true
if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
(originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
(originAsURL.hostname.endsWith('.localhost'))) {
return true
}
// If any other, return false
return false
}
}
/**
* @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
* @param {Uint8Array} bytes
* @param {string} metadataList
*/
function bytesMatch (bytes, metadataList) {
// If node is not built with OpenSSL support, we cannot check
// a request's integrity, so allow it by default (the spec will
// allow requests if an invalid hash is given, as precedence).
/* istanbul ignore if: only if node is built with --without-ssl */
if (crypto === undefined) {
return true
}
// 1. Let parsedMetadata be the result of parsing metadataList.
const parsedMetadata = parseMetadata(metadataList)
// 2. If parsedMetadata is no metadata, return true.
if (parsedMetadata === 'no metadata') {
return true
}
// 3. If response is not eligible for integrity validation, return false.
// TODO
// 4. If parsedMetadata is the empty set, return true.
if (parsedMetadata.length === 0) {
return true
}
// 5. Let metadata be the result of getting the strongest
// metadata from parsedMetadata.
const strongest = getStrongestMetadata(parsedMetadata)
const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
// 6. For each item in metadata:
for (const item of metadata) {
// 1. Let algorithm be the alg component of item.
const algorithm = item.algo
// 2. Let expectedValue be the val component of item.
const expectedValue = item.hash
// See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
// "be liberal with padding". This is annoying, and it's not even in the spec.
// 3. Let actualValue be the result of applying algorithm to bytes.
let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
if (actualValue[actualValue.length - 1] === '=') {
if (actualValue[actualValue.length - 2] === '=') {
actualValue = actualValue.slice(0, -2)
} else {
actualValue = actualValue.slice(0, -1)
}
}
// 4. If actualValue is a case-sensitive match for expectedValue,
// return true.
if (compareBase64Mixed(actualValue, expectedValue)) {
return true
}
}
// 7. Return false.
return false
}
// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
// https://www.w3.org/TR/CSP2/#source-list-syntax
// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
const parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
/**
* @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
* @param {string} metadata
*/
function parseMetadata (metadata) {
// 1. Let result be the empty set.
/** @type {{ algo: string, hash: string }[]} */
const result = []
// 2. Let empty be equal to true.
let empty = true
// 3. For each token returned by splitting metadata on spaces:
for (const token of metadata.split(' ')) {
// 1. Set empty to false.
empty = false
// 2. Parse token as a hash-with-options.
const parsedToken = parseHashWithOptions.exec(token)
// 3. If token does not parse, continue to the next token.
if (
parsedToken === null ||
parsedToken.groups === undefined ||
parsedToken.groups.algo === undefined
) {
// Note: Chromium blocks the request at this point, but Firefox
// gives a warning that an invalid integrity was given. The
// correct behavior is to ignore these, and subsequently not
// check the integrity of the resource.
continue
}
// 4. Let algorithm be the hash-algo component of token.
const algorithm = parsedToken.groups.algo.toLowerCase()
// 5. If algorithm is a hash function recognized by the user
// agent, add the parsed token to result.
if (supportedHashes.includes(algorithm)) {
result.push(parsedToken.groups)
}
}
// 4. Return no metadata if empty is true, otherwise return result.
if (empty === true) {
return 'no metadata'
}
return result
}
/**
* @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
*/
function getStrongestMetadata (metadataList) {
// Let algorithm be the algo component of the first item in metadataList.
// Can be sha256
let algorithm = metadataList[0].algo
// If the algorithm is sha512, then it is the strongest
// and we can return immediately
if (algorithm[3] === '5') {
return algorithm
}
for (let i = 1; i < metadataList.length; ++i) {
const metadata = metadataList[i]
// If the algorithm is sha512, then it is the strongest
// and we can break the loop immediately
if (metadata.algo[3] === '5') {
algorithm = 'sha512'
break
// If the algorithm is sha384, then a potential sha256 or sha384 is ignored
} else if (algorithm[3] === '3') {
continue
// algorithm is sha256, check if algorithm is sha384 and if so, set it as
// the strongest
} else if (metadata.algo[3] === '3') {
algorithm = 'sha384'
}
}
return algorithm
}
function filterMetadataListByAlgorithm (metadataList, algorithm) {
if (metadataList.length === 1) {
return metadataList
}
let pos = 0
for (let i = 0; i < metadataList.length; ++i) {
if (metadataList[i].algo === algorithm) {
metadataList[pos++] = metadataList[i]
}
}
metadataList.length = pos
return metadataList
}
/**
* Compares two base64 strings, allowing for base64url
* in the second string.
*
* @param {string} actualValue always base64
* @param {string} expectedValue base64 or base64url
* @returns {boolean}
*/
function compareBase64Mixed (actualValue, expectedValue) {
if (actualValue.length !== expectedValue.length) {
return false
}
for (let i = 0; i < actualValue.length; ++i) {
if (actualValue[i] !== expectedValue[i]) {
if (
(actualValue[i] === '+' && expectedValue[i] === '-') ||
(actualValue[i] === '/' && expectedValue[i] === '_')
) {
continue
}
return false
}
}
return true
}
// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
// TODO
}
/**
* @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
* @param {URL} A
* @param {URL} B
*/
function sameOrigin (A, B) {
// 1. If A and B are the same opaque origin, then return true.
if (A.origin === B.origin && A.origin === 'null') {
return true
}
// 2. If A and B are both tuple origins and their schemes,
// hosts, and port are identical, then return true.
if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
return true
}
// 3. Return false.
return false
}
function createDeferredPromise () {
let res
let rej
const promise = new Promise((resolve, reject) => {
res = resolve
rej = reject
})
return { promise, resolve: res, reject: rej }
}
function isAborted (fetchParams) {
return fetchParams.controller.state === 'aborted'
}
function isCancelled (fetchParams) {
return fetchParams.controller.state === 'aborted' ||
fetchParams.controller.state === 'terminated'
}
const normalizeMethodRecord = {
delete: 'DELETE',
DELETE: 'DELETE',
get: 'GET',
GET: 'GET',
head: 'HEAD',
HEAD: 'HEAD',
options: 'OPTIONS',
OPTIONS: 'OPTIONS',
post: 'POST',
POST: 'POST',
put: 'PUT',
PUT: 'PUT'
}
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
Object.setPrototypeOf(normalizeMethodRecord, null)
/**
* @see https://fetch.spec.whatwg.org/#concept-method-normalize
* @param {string} method
*/
function normalizeMethod (method) {
return normalizeMethodRecord[method.toLowerCase()] ?? method
}
// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
function serializeJavascriptValueToJSONString (value) {
// 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
const result = JSON.stringify(value)
// 2. If result is undefined, then throw a TypeError.
if (result === undefined) {
throw new TypeError('Value is not JSON serializable')
}
// 3. Assert: result is a string.
assert(typeof result === 'string')
// 4. Return result.
return result
}
// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
/**
* @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
* @param {() => unknown[]} iterator
* @param {string} name name of the instance
* @param {'key'|'value'|'key+value'} kind
*/
function makeIterator (iterator, name, kind) {
const object = {
index: 0,
kind,
target: iterator
}
const i = {
next () {
// 1. Let interface be the interface for which the iterator prototype object exists.
// 2. Let thisValue be the this value.
// 3. Let object be ? ToObject(thisValue).
// 4. If object is a platform object, then perform a security
// check, passing:
// 5. If object is not a default iterator object for interface,
// then throw a TypeError.
if (Object.getPrototypeOf(this) !== i) {
throw new TypeError(
`'next' called on an object that does not implement interface ${name} Iterator.`
)
}
// 6. Let index be objects index.
// 7. Let kind be objects kind.
// 8. Let values be objects target's value pairs to iterate over.
const { index, kind, target } = object
const values = target()
// 9. Let len be the length of values.
const len = values.length
// 10. If index is greater than or equal to len, then return
// CreateIterResultObject(undefined, true).
if (index >= len) {
return { value: undefined, done: true }
}
// 11. Let pair be the entry in values at index index.
const pair = values[index]
// 12. Set objects index to index + 1.
object.index = index + 1
// 13. Return the iterator result for pair and kind.
return iteratorResult(pair, kind)
},
// The class string of an iterator prototype object for a given interface is the
// result of concatenating the identifier of the interface and the string " Iterator".
[Symbol.toStringTag]: `${name} Iterator`
}
// The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
Object.setPrototypeOf(i, esIteratorPrototype)
// esIteratorPrototype needs to be the prototype of i
// which is the prototype of an empty object. Yes, it's confusing.
return Object.setPrototypeOf({}, i)
}
// https://webidl.spec.whatwg.org/#iterator-result
function iteratorResult (pair, kind) {
let result
// 1. Let result be a value determined by the value of kind:
switch (kind) {
case 'key': {
// 1. Let idlKey be pairs key.
// 2. Let key be the result of converting idlKey to an
// ECMAScript value.
// 3. result is key.
result = pair[0]
break
}
case 'value': {
// 1. Let idlValue be pairs value.
// 2. Let value be the result of converting idlValue to
// an ECMAScript value.
// 3. result is value.
result = pair[1]
break
}
case 'key+value': {
// 1. Let idlKey be pairs key.
// 2. Let idlValue be pairs value.
// 3. Let key be the result of converting idlKey to an
// ECMAScript value.
// 4. Let value be the result of converting idlValue to
// an ECMAScript value.
// 5. Let array be ! ArrayCreate(2).
// 6. Call ! CreateDataProperty(array, "0", key).
// 7. Call ! CreateDataProperty(array, "1", value).
// 8. result is array.
result = pair
break
}
}
// 2. Return CreateIterResultObject(result, false).
return { value: result, done: false }
}
/**
* @see https://fetch.spec.whatwg.org/#body-fully-read
*/
async function fullyReadBody (body, processBody, processBodyError) {
// 1. If taskDestination is null, then set taskDestination to
// the result of starting a new parallel queue.
// 2. Let successSteps given a byte sequence bytes be to queue a
// fetch task to run processBody given bytes, with taskDestination.
const successSteps = processBody
// 3. Let errorSteps be to queue a fetch task to run processBodyError,
// with taskDestination.
const errorSteps = processBodyError
// 4. Let reader be the result of getting a reader for bodys stream.
// If that threw an exception, then run errorSteps with that
// exception and return.
let reader
try {
reader = body.stream.getReader()
} catch (e) {
errorSteps(e)
return
}
// 5. Read all bytes from reader, given successSteps and errorSteps.
try {
const result = await readAllBytes(reader)
successSteps(result)
} catch (e) {
errorSteps(e)
}
}
/** @type {ReadableStream} */
let ReadableStream = globalThis.ReadableStream
function isReadableStreamLike (stream) {
if (!ReadableStream) {
ReadableStream = (__nccwpck_require__(35356).ReadableStream)
}
return stream instanceof ReadableStream || (
stream[Symbol.toStringTag] === 'ReadableStream' &&
typeof stream.tee === 'function'
)
}
const MAXIMUM_ARGUMENT_LENGTH = 65535
/**
* @see https://infra.spec.whatwg.org/#isomorphic-decode
* @param {number[]|Uint8Array} input
*/
function isomorphicDecode (input) {
// 1. To isomorphic decode a byte sequence input, return a string whose code point
// length is equal to inputs length and whose code points have the same values
// as the values of inputs bytes, in the same order.
if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
return String.fromCharCode(...input)
}
return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
}
/**
* @param {ReadableStreamController<Uint8Array>} controller
*/
function readableStreamClose (controller) {
try {
controller.close()
} catch (err) {
// TODO: add comment explaining why this error occurs.
if (!err.message.includes('Controller is already closed')) {
throw err
}
}
}
/**
* @see https://infra.spec.whatwg.org/#isomorphic-encode
* @param {string} input
*/
function isomorphicEncode (input) {
// 1. Assert: input contains no code points greater than U+00FF.
for (let i = 0; i < input.length; i++) {
assert(input.charCodeAt(i) <= 0xFF)
}
// 2. Return a byte sequence whose length is equal to inputs code
// point length and whose bytes have the same values as the
// values of inputs code points, in the same order
return input
}
/**
* @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
* @see https://streams.spec.whatwg.org/#read-loop
* @param {ReadableStreamDefaultReader} reader
*/
async function readAllBytes (reader) {
const bytes = []
let byteLength = 0
while (true) {
const { done, value: chunk } = await reader.read()
if (done) {
// 1. Call successSteps with bytes.
return Buffer.concat(bytes, byteLength)
}
// 1. If chunk is not a Uint8Array object, call failureSteps
// with a TypeError and abort these steps.
if (!isUint8Array(chunk)) {
throw new TypeError('Received non-Uint8Array chunk')
}
// 2. Append the bytes represented by chunk to bytes.
bytes.push(chunk)
byteLength += chunk.length
// 3. Read-loop given reader, bytes, successSteps, and failureSteps.
}
}
/**
* @see https://fetch.spec.whatwg.org/#is-local
* @param {URL} url
*/
function urlIsLocal (url) {
assert('protocol' in url) // ensure it's a url object
const protocol = url.protocol
return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
}
/**
* @param {string|URL} url
*/
function urlHasHttpsScheme (url) {
if (typeof url === 'string') {
return url.startsWith('https:')
}
return url.protocol === 'https:'
}
/**
* @see https://fetch.spec.whatwg.org/#http-scheme
* @param {URL} url
*/
function urlIsHttpHttpsScheme (url) {
assert('protocol' in url) // ensure it's a url object
const protocol = url.protocol
return protocol === 'http:' || protocol === 'https:'
}
/**
* Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
*/
const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
module.exports = {
isAborted,
isCancelled,
createDeferredPromise,
ReadableStreamFrom,
toUSVString,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
coarsenedSharedCurrentTime,
determineRequestsReferrer,
makePolicyContainer,
clonePolicyContainer,
appendFetchMetadata,
appendRequestOriginHeader,
TAOCheck,
corsCheck,
crossOriginResourcePolicyCheck,
createOpaqueTimingInfo,
setRequestReferrerPolicyOnRedirect,
isValidHTTPToken,
requestBadPort,
requestCurrentURL,
responseURL,
responseLocationURL,
isBlobLike,
isURLPotentiallyTrustworthy,
isValidReasonPhrase,
sameOrigin,
normalizeMethod,
serializeJavascriptValueToJSONString,
makeIterator,
isValidHeaderName,
isValidHeaderValue,
hasOwn,
isErrorLike,
fullyReadBody,
bytesMatch,
isReadableStreamLike,
readableStreamClose,
isomorphicEncode,
isomorphicDecode,
urlIsLocal,
urlHasHttpsScheme,
urlIsHttpHttpsScheme,
readAllBytes,
normalizeMethodRecord,
parseMetadata
}
/***/ }),
/***/ 21744:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { types } = __nccwpck_require__(73837)
const { hasOwn, toUSVString } = __nccwpck_require__(52538)
/** @type {import('../../types/webidl').Webidl} */
const webidl = {}
webidl.converters = {}
webidl.util = {}
webidl.errors = {}
webidl.errors.exception = function (message) {
return new TypeError(`${message.header}: ${message.message}`)
}
webidl.errors.conversionFailed = function (context) {
const plural = context.types.length === 1 ? '' : ' one of'
const message =
`${context.argument} could not be converted to` +
`${plural}: ${context.types.join(', ')}.`
return webidl.errors.exception({
header: context.prefix,
message
})
}
webidl.errors.invalidArgument = function (context) {
return webidl.errors.exception({
header: context.prefix,
message: `"${context.value}" is an invalid ${context.type}.`
})
}
// https://webidl.spec.whatwg.org/#implements
webidl.brandCheck = function (V, I, opts = undefined) {
if (opts?.strict !== false && !(V instanceof I)) {
throw new TypeError('Illegal invocation')
} else {
return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
}
}
webidl.argumentLengthCheck = function ({ length }, min, ctx) {
if (length < min) {
throw webidl.errors.exception({
message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
`but${length ? ' only' : ''} ${length} found.`,
...ctx
})
}
}
webidl.illegalConstructor = function () {
throw webidl.errors.exception({
header: 'TypeError',
message: 'Illegal constructor'
})
}
// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
webidl.util.Type = function (V) {
switch (typeof V) {
case 'undefined': return 'Undefined'
case 'boolean': return 'Boolean'
case 'string': return 'String'
case 'symbol': return 'Symbol'
case 'number': return 'Number'
case 'bigint': return 'BigInt'
case 'function':
case 'object': {
if (V === null) {
return 'Null'
}
return 'Object'
}
}
}
// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
let upperBound
let lowerBound
// 1. If bitLength is 64, then:
if (bitLength === 64) {
// 1. Let upperBound be 2^53 1.
upperBound = Math.pow(2, 53) - 1
// 2. If signedness is "unsigned", then let lowerBound be 0.
if (signedness === 'unsigned') {
lowerBound = 0
} else {
// 3. Otherwise let lowerBound be 2^53 + 1.
lowerBound = Math.pow(-2, 53) + 1
}
} else if (signedness === 'unsigned') {
// 2. Otherwise, if signedness is "unsigned", then:
// 1. Let lowerBound be 0.
lowerBound = 0
// 2. Let upperBound be 2^bitLength 1.
upperBound = Math.pow(2, bitLength) - 1
} else {
// 3. Otherwise:
// 1. Let lowerBound be -2^bitLength 1.
lowerBound = Math.pow(-2, bitLength) - 1
// 2. Let upperBound be 2^bitLength 1 1.
upperBound = Math.pow(2, bitLength - 1) - 1
}
// 4. Let x be ? ToNumber(V).
let x = Number(V)
// 5. If x is 0, then set x to +0.
if (x === 0) {
x = 0
}
// 6. If the conversion is to an IDL type associated
// with the [EnforceRange] extended attribute, then:
if (opts.enforceRange === true) {
// 1. If x is NaN, +∞, or −∞, then throw a TypeError.
if (
Number.isNaN(x) ||
x === Number.POSITIVE_INFINITY ||
x === Number.NEGATIVE_INFINITY
) {
throw webidl.errors.exception({
header: 'Integer conversion',
message: `Could not convert ${V} to an integer.`
})
}
// 2. Set x to IntegerPart(x).
x = webidl.util.IntegerPart(x)
// 3. If x < lowerBound or x > upperBound, then
// throw a TypeError.
if (x < lowerBound || x > upperBound) {
throw webidl.errors.exception({
header: 'Integer conversion',
message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
})
}
// 4. Return x.
return x
}
// 7. If x is not NaN and the conversion is to an IDL
// type associated with the [Clamp] extended
// attribute, then:
if (!Number.isNaN(x) && opts.clamp === true) {
// 1. Set x to min(max(x, lowerBound), upperBound).
x = Math.min(Math.max(x, lowerBound), upperBound)
// 2. Round x to the nearest integer, choosing the
// even integer if it lies halfway between two,
// and choosing +0 rather than 0.
if (Math.floor(x) % 2 === 0) {
x = Math.floor(x)
} else {
x = Math.ceil(x)
}
// 3. Return x.
return x
}
// 8. If x is NaN, +0, +∞, or −∞, then return +0.
if (
Number.isNaN(x) ||
(x === 0 && Object.is(0, x)) ||
x === Number.POSITIVE_INFINITY ||
x === Number.NEGATIVE_INFINITY
) {
return 0
}
// 9. Set x to IntegerPart(x).
x = webidl.util.IntegerPart(x)
// 10. Set x to x modulo 2^bitLength.
x = x % Math.pow(2, bitLength)
// 11. If signedness is "signed" and x ≥ 2^bitLength 1,
// then return x 2^bitLength.
if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
return x - Math.pow(2, bitLength)
}
// 12. Otherwise, return x.
return x
}
// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
webidl.util.IntegerPart = function (n) {
// 1. Let r be floor(abs(n)).
const r = Math.floor(Math.abs(n))
// 2. If n < 0, then return -1 × r.
if (n < 0) {
return -1 * r
}
// 3. Otherwise, return r.
return r
}
// https://webidl.spec.whatwg.org/#es-sequence
webidl.sequenceConverter = function (converter) {
return (V) => {
// 1. If Type(V) is not Object, throw a TypeError.
if (webidl.util.Type(V) !== 'Object') {
throw webidl.errors.exception({
header: 'Sequence',
message: `Value of type ${webidl.util.Type(V)} is not an Object.`
})
}
// 2. Let method be ? GetMethod(V, @@iterator).
/** @type {Generator} */
const method = V?.[Symbol.iterator]?.()
const seq = []
// 3. If method is undefined, throw a TypeError.
if (
method === undefined ||
typeof method.next !== 'function'
) {
throw webidl.errors.exception({
header: 'Sequence',
message: 'Object is not an iterator.'
})
}
// https://webidl.spec.whatwg.org/#create-sequence-from-iterable
while (true) {
const { done, value } = method.next()
if (done) {
break
}
seq.push(converter(value))
}
return seq
}
}
// https://webidl.spec.whatwg.org/#es-to-record
webidl.recordConverter = function (keyConverter, valueConverter) {
return (O) => {
// 1. If Type(O) is not Object, throw a TypeError.
if (webidl.util.Type(O) !== 'Object') {
throw webidl.errors.exception({
header: 'Record',
message: `Value of type ${webidl.util.Type(O)} is not an Object.`
})
}
// 2. Let result be a new empty instance of record<K, V>.
const result = {}
if (!types.isProxy(O)) {
// Object.keys only returns enumerable properties
const keys = Object.keys(O)
for (const key of keys) {
// 1. Let typedKey be key converted to an IDL value of type K.
const typedKey = keyConverter(key)
// 2. Let value be ? Get(O, key).
// 3. Let typedValue be value converted to an IDL value of type V.
const typedValue = valueConverter(O[key])
// 4. Set result[typedKey] to typedValue.
result[typedKey] = typedValue
}
// 5. Return result.
return result
}
// 3. Let keys be ? O.[[OwnPropertyKeys]]().
const keys = Reflect.ownKeys(O)
// 4. For each key of keys.
for (const key of keys) {
// 1. Let desc be ? O.[[GetOwnProperty]](key).
const desc = Reflect.getOwnPropertyDescriptor(O, key)
// 2. If desc is not undefined and desc.[[Enumerable]] is true:
if (desc?.enumerable) {
// 1. Let typedKey be key converted to an IDL value of type K.
const typedKey = keyConverter(key)
// 2. Let value be ? Get(O, key).
// 3. Let typedValue be value converted to an IDL value of type V.
const typedValue = valueConverter(O[key])
// 4. Set result[typedKey] to typedValue.
result[typedKey] = typedValue
}
}
// 5. Return result.
return result
}
}
webidl.interfaceConverter = function (i) {
return (V, opts = {}) => {
if (opts.strict !== false && !(V instanceof i)) {
throw webidl.errors.exception({
header: i.name,
message: `Expected ${V} to be an instance of ${i.name}.`
})
}
return V
}
}
webidl.dictionaryConverter = function (converters) {
return (dictionary) => {
const type = webidl.util.Type(dictionary)
const dict = {}
if (type === 'Null' || type === 'Undefined') {
return dict
} else if (type !== 'Object') {
throw webidl.errors.exception({
header: 'Dictionary',
message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
})
}
for (const options of converters) {
const { key, defaultValue, required, converter } = options
if (required === true) {
if (!hasOwn(dictionary, key)) {
throw webidl.errors.exception({
header: 'Dictionary',
message: `Missing required key "${key}".`
})
}
}
let value = dictionary[key]
const hasDefault = hasOwn(options, 'defaultValue')
// Only use defaultValue if value is undefined and
// a defaultValue options was provided.
if (hasDefault && value !== null) {
value = value ?? defaultValue
}
// A key can be optional and have no default value.
// When this happens, do not perform a conversion,
// and do not assign the key a value.
if (required || hasDefault || value !== undefined) {
value = converter(value)
if (
options.allowedValues &&
!options.allowedValues.includes(value)
) {
throw webidl.errors.exception({
header: 'Dictionary',
message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
})
}
dict[key] = value
}
}
return dict
}
}
webidl.nullableConverter = function (converter) {
return (V) => {
if (V === null) {
return V
}
return converter(V)
}
}
// https://webidl.spec.whatwg.org/#es-DOMString
webidl.converters.DOMString = function (V, opts = {}) {
// 1. If V is null and the conversion is to an IDL type
// associated with the [LegacyNullToEmptyString]
// extended attribute, then return the DOMString value
// that represents the empty string.
if (V === null && opts.legacyNullToEmptyString) {
return ''
}
// 2. Let x be ? ToString(V).
if (typeof V === 'symbol') {
throw new TypeError('Could not convert argument of type symbol to string.')
}
// 3. Return the IDL DOMString value that represents the
// same sequence of code units as the one the
// ECMAScript String value x represents.
return String(V)
}
// https://webidl.spec.whatwg.org/#es-ByteString
webidl.converters.ByteString = function (V) {
// 1. Let x be ? ToString(V).
// Note: DOMString converter perform ? ToString(V)
const x = webidl.converters.DOMString(V)
// 2. If the value of any element of x is greater than
// 255, then throw a TypeError.
for (let index = 0; index < x.length; index++) {
if (x.charCodeAt(index) > 255) {
throw new TypeError(
'Cannot convert argument to a ByteString because the character at ' +
`index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
)
}
}
// 3. Return an IDL ByteString value whose length is the
// length of x, and where the value of each element is
// the value of the corresponding element of x.
return x
}
// https://webidl.spec.whatwg.org/#es-USVString
webidl.converters.USVString = toUSVString
// https://webidl.spec.whatwg.org/#es-boolean
webidl.converters.boolean = function (V) {
// 1. Let x be the result of computing ToBoolean(V).
const x = Boolean(V)
// 2. Return the IDL boolean value that is the one that represents
// the same truth value as the ECMAScript Boolean value x.
return x
}
// https://webidl.spec.whatwg.org/#es-any
webidl.converters.any = function (V) {
return V
}
// https://webidl.spec.whatwg.org/#es-long-long
webidl.converters['long long'] = function (V) {
// 1. Let x be ? ConvertToInt(V, 64, "signed").
const x = webidl.util.ConvertToInt(V, 64, 'signed')
// 2. Return the IDL long long value that represents
// the same numeric value as x.
return x
}
// https://webidl.spec.whatwg.org/#es-unsigned-long-long
webidl.converters['unsigned long long'] = function (V) {
// 1. Let x be ? ConvertToInt(V, 64, "unsigned").
const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
// 2. Return the IDL unsigned long long value that
// represents the same numeric value as x.
return x
}
// https://webidl.spec.whatwg.org/#es-unsigned-long
webidl.converters['unsigned long'] = function (V) {
// 1. Let x be ? ConvertToInt(V, 32, "unsigned").
const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
// 2. Return the IDL unsigned long value that
// represents the same numeric value as x.
return x
}
// https://webidl.spec.whatwg.org/#es-unsigned-short
webidl.converters['unsigned short'] = function (V, opts) {
// 1. Let x be ? ConvertToInt(V, 16, "unsigned").
const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
// 2. Return the IDL unsigned short value that represents
// the same numeric value as x.
return x
}
// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
webidl.converters.ArrayBuffer = function (V, opts = {}) {
// 1. If Type(V) is not Object, or V does not have an
// [[ArrayBufferData]] internal slot, then throw a
// TypeError.
// see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
// see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
if (
webidl.util.Type(V) !== 'Object' ||
!types.isAnyArrayBuffer(V)
) {
throw webidl.errors.conversionFailed({
prefix: `${V}`,
argument: `${V}`,
types: ['ArrayBuffer']
})
}
// 2. If the conversion is not to an IDL type associated
// with the [AllowShared] extended attribute, and
// IsSharedArrayBuffer(V) is true, then throw a
// TypeError.
if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
throw webidl.errors.exception({
header: 'ArrayBuffer',
message: 'SharedArrayBuffer is not allowed.'
})
}
// 3. If the conversion is not to an IDL type associated
// with the [AllowResizable] extended attribute, and
// IsResizableArrayBuffer(V) is true, then throw a
// TypeError.
// Note: resizable ArrayBuffers are currently a proposal.
// 4. Return the IDL ArrayBuffer value that is a
// reference to the same object as V.
return V
}
webidl.converters.TypedArray = function (V, T, opts = {}) {
// 1. Let T be the IDL type V is being converted to.
// 2. If Type(V) is not Object, or V does not have a
// [[TypedArrayName]] internal slot with a value
// equal to Ts name, then throw a TypeError.
if (
webidl.util.Type(V) !== 'Object' ||
!types.isTypedArray(V) ||
V.constructor.name !== T.name
) {
throw webidl.errors.conversionFailed({
prefix: `${T.name}`,
argument: `${V}`,
types: [T.name]
})
}
// 3. If the conversion is not to an IDL type associated
// with the [AllowShared] extended attribute, and
// IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
// true, then throw a TypeError.
if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
throw webidl.errors.exception({
header: 'ArrayBuffer',
message: 'SharedArrayBuffer is not allowed.'
})
}
// 4. If the conversion is not to an IDL type associated
// with the [AllowResizable] extended attribute, and
// IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
// true, then throw a TypeError.
// Note: resizable array buffers are currently a proposal
// 5. Return the IDL value of type T that is a reference
// to the same object as V.
return V
}
webidl.converters.DataView = function (V, opts = {}) {
// 1. If Type(V) is not Object, or V does not have a
// [[DataView]] internal slot, then throw a TypeError.
if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
throw webidl.errors.exception({
header: 'DataView',
message: 'Object is not a DataView.'
})
}
// 2. If the conversion is not to an IDL type associated
// with the [AllowShared] extended attribute, and
// IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
// then throw a TypeError.
if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
throw webidl.errors.exception({
header: 'ArrayBuffer',
message: 'SharedArrayBuffer is not allowed.'
})
}
// 3. If the conversion is not to an IDL type associated
// with the [AllowResizable] extended attribute, and
// IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
// true, then throw a TypeError.
// Note: resizable ArrayBuffers are currently a proposal
// 4. Return the IDL DataView value that is a reference
// to the same object as V.
return V
}
// https://webidl.spec.whatwg.org/#BufferSource
webidl.converters.BufferSource = function (V, opts = {}) {
if (types.isAnyArrayBuffer(V)) {
return webidl.converters.ArrayBuffer(V, opts)
}
if (types.isTypedArray(V)) {
return webidl.converters.TypedArray(V, V.constructor)
}
if (types.isDataView(V)) {
return webidl.converters.DataView(V, opts)
}
throw new TypeError(`Could not convert ${V} to a BufferSource.`)
}
webidl.converters['sequence<ByteString>'] = webidl.sequenceConverter(
webidl.converters.ByteString
)
webidl.converters['sequence<sequence<ByteString>>'] = webidl.sequenceConverter(
webidl.converters['sequence<ByteString>']
)
webidl.converters['record<ByteString, ByteString>'] = webidl.recordConverter(
webidl.converters.ByteString,
webidl.converters.ByteString
)
module.exports = {
webidl
}
/***/ }),
/***/ 84854:
/***/ ((module) => {
"use strict";
/**
* @see https://encoding.spec.whatwg.org/#concept-encoding-get
* @param {string|undefined} label
*/
function getEncoding (label) {
if (!label) {
return 'failure'
}
// 1. Remove any leading and trailing ASCII whitespace from label.
// 2. If label is an ASCII case-insensitive match for any of the
// labels listed in the table below, then return the
// corresponding encoding; otherwise return failure.
switch (label.trim().toLowerCase()) {
case 'unicode-1-1-utf-8':
case 'unicode11utf8':
case 'unicode20utf8':
case 'utf-8':
case 'utf8':
case 'x-unicode20utf8':
return 'UTF-8'
case '866':
case 'cp866':
case 'csibm866':
case 'ibm866':
return 'IBM866'
case 'csisolatin2':
case 'iso-8859-2':
case 'iso-ir-101':
case 'iso8859-2':
case 'iso88592':
case 'iso_8859-2':
case 'iso_8859-2:1987':
case 'l2':
case 'latin2':
return 'ISO-8859-2'
case 'csisolatin3':
case 'iso-8859-3':
case 'iso-ir-109':
case 'iso8859-3':
case 'iso88593':
case 'iso_8859-3':
case 'iso_8859-3:1988':
case 'l3':
case 'latin3':
return 'ISO-8859-3'
case 'csisolatin4':
case 'iso-8859-4':
case 'iso-ir-110':
case 'iso8859-4':
case 'iso88594':
case 'iso_8859-4':
case 'iso_8859-4:1988':
case 'l4':
case 'latin4':
return 'ISO-8859-4'
case 'csisolatincyrillic':
case 'cyrillic':
case 'iso-8859-5':
case 'iso-ir-144':
case 'iso8859-5':
case 'iso88595':
case 'iso_8859-5':
case 'iso_8859-5:1988':
return 'ISO-8859-5'
case 'arabic':
case 'asmo-708':
case 'csiso88596e':
case 'csiso88596i':
case 'csisolatinarabic':
case 'ecma-114':
case 'iso-8859-6':
case 'iso-8859-6-e':
case 'iso-8859-6-i':
case 'iso-ir-127':
case 'iso8859-6':
case 'iso88596':
case 'iso_8859-6':
case 'iso_8859-6:1987':
return 'ISO-8859-6'
case 'csisolatingreek':
case 'ecma-118':
case 'elot_928':
case 'greek':
case 'greek8':
case 'iso-8859-7':
case 'iso-ir-126':
case 'iso8859-7':
case 'iso88597':
case 'iso_8859-7':
case 'iso_8859-7:1987':
case 'sun_eu_greek':
return 'ISO-8859-7'
case 'csiso88598e':
case 'csisolatinhebrew':
case 'hebrew':
case 'iso-8859-8':
case 'iso-8859-8-e':
case 'iso-ir-138':
case 'iso8859-8':
case 'iso88598':
case 'iso_8859-8':
case 'iso_8859-8:1988':
case 'visual':
return 'ISO-8859-8'
case 'csiso88598i':
case 'iso-8859-8-i':
case 'logical':
return 'ISO-8859-8-I'
case 'csisolatin6':
case 'iso-8859-10':
case 'iso-ir-157':
case 'iso8859-10':
case 'iso885910':
case 'l6':
case 'latin6':
return 'ISO-8859-10'
case 'iso-8859-13':
case 'iso8859-13':
case 'iso885913':
return 'ISO-8859-13'
case 'iso-8859-14':
case 'iso8859-14':
case 'iso885914':
return 'ISO-8859-14'
case 'csisolatin9':
case 'iso-8859-15':
case 'iso8859-15':
case 'iso885915':
case 'iso_8859-15':
case 'l9':
return 'ISO-8859-15'
case 'iso-8859-16':
return 'ISO-8859-16'
case 'cskoi8r':
case 'koi':
case 'koi8':
case 'koi8-r':
case 'koi8_r':
return 'KOI8-R'
case 'koi8-ru':
case 'koi8-u':
return 'KOI8-U'
case 'csmacintosh':
case 'mac':
case 'macintosh':
case 'x-mac-roman':
return 'macintosh'
case 'iso-8859-11':
case 'iso8859-11':
case 'iso885911':
case 'tis-620':
case 'windows-874':
return 'windows-874'
case 'cp1250':
case 'windows-1250':
case 'x-cp1250':
return 'windows-1250'
case 'cp1251':
case 'windows-1251':
case 'x-cp1251':
return 'windows-1251'
case 'ansi_x3.4-1968':
case 'ascii':
case 'cp1252':
case 'cp819':
case 'csisolatin1':
case 'ibm819':
case 'iso-8859-1':
case 'iso-ir-100':
case 'iso8859-1':
case 'iso88591':
case 'iso_8859-1':
case 'iso_8859-1:1987':
case 'l1':
case 'latin1':
case 'us-ascii':
case 'windows-1252':
case 'x-cp1252':
return 'windows-1252'
case 'cp1253':
case 'windows-1253':
case 'x-cp1253':
return 'windows-1253'
case 'cp1254':
case 'csisolatin5':
case 'iso-8859-9':
case 'iso-ir-148':
case 'iso8859-9':
case 'iso88599':
case 'iso_8859-9':
case 'iso_8859-9:1989':
case 'l5':
case 'latin5':
case 'windows-1254':
case 'x-cp1254':
return 'windows-1254'
case 'cp1255':
case 'windows-1255':
case 'x-cp1255':
return 'windows-1255'
case 'cp1256':
case 'windows-1256':
case 'x-cp1256':
return 'windows-1256'
case 'cp1257':
case 'windows-1257':
case 'x-cp1257':
return 'windows-1257'
case 'cp1258':
case 'windows-1258':
case 'x-cp1258':
return 'windows-1258'
case 'x-mac-cyrillic':
case 'x-mac-ukrainian':
return 'x-mac-cyrillic'
case 'chinese':
case 'csgb2312':
case 'csiso58gb231280':
case 'gb2312':
case 'gb_2312':
case 'gb_2312-80':
case 'gbk':
case 'iso-ir-58':
case 'x-gbk':
return 'GBK'
case 'gb18030':
return 'gb18030'
case 'big5':
case 'big5-hkscs':
case 'cn-big5':
case 'csbig5':
case 'x-x-big5':
return 'Big5'
case 'cseucpkdfmtjapanese':
case 'euc-jp':
case 'x-euc-jp':
return 'EUC-JP'
case 'csiso2022jp':
case 'iso-2022-jp':
return 'ISO-2022-JP'
case 'csshiftjis':
case 'ms932':
case 'ms_kanji':
case 'shift-jis':
case 'shift_jis':
case 'sjis':
case 'windows-31j':
case 'x-sjis':
return 'Shift_JIS'
case 'cseuckr':
case 'csksc56011987':
case 'euc-kr':
case 'iso-ir-149':
case 'korean':
case 'ks_c_5601-1987':
case 'ks_c_5601-1989':
case 'ksc5601':
case 'ksc_5601':
case 'windows-949':
return 'EUC-KR'
case 'csiso2022kr':
case 'hz-gb-2312':
case 'iso-2022-cn':
case 'iso-2022-cn-ext':
case 'iso-2022-kr':
case 'replacement':
return 'replacement'
case 'unicodefffe':
case 'utf-16be':
return 'UTF-16BE'
case 'csunicode':
case 'iso-10646-ucs-2':
case 'ucs-2':
case 'unicode':
case 'unicodefeff':
case 'utf-16':
case 'utf-16le':
return 'UTF-16LE'
case 'x-user-defined':
return 'x-user-defined'
default: return 'failure'
}
}
module.exports = {
getEncoding
}
/***/ }),
/***/ 1446:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
staticPropertyDescriptors,
readOperation,
fireAProgressEvent
} = __nccwpck_require__(87530)
const {
kState,
kError,
kResult,
kEvents,
kAborted
} = __nccwpck_require__(29054)
const { webidl } = __nccwpck_require__(21744)
const { kEnumerableProperty } = __nccwpck_require__(83983)
class FileReader extends EventTarget {
constructor () {
super()
this[kState] = 'empty'
this[kResult] = null
this[kError] = null
this[kEvents] = {
loadend: null,
error: null,
abort: null,
load: null,
progress: null,
loadstart: null
}
}
/**
* @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
* @param {import('buffer').Blob} blob
*/
readAsArrayBuffer (blob) {
webidl.brandCheck(this, FileReader)
webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
blob = webidl.converters.Blob(blob, { strict: false })
// The readAsArrayBuffer(blob) method, when invoked,
// must initiate a read operation for blob with ArrayBuffer.
readOperation(this, blob, 'ArrayBuffer')
}
/**
* @see https://w3c.github.io/FileAPI/#readAsBinaryString
* @param {import('buffer').Blob} blob
*/
readAsBinaryString (blob) {
webidl.brandCheck(this, FileReader)
webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
blob = webidl.converters.Blob(blob, { strict: false })
// The readAsBinaryString(blob) method, when invoked,
// must initiate a read operation for blob with BinaryString.
readOperation(this, blob, 'BinaryString')
}
/**
* @see https://w3c.github.io/FileAPI/#readAsDataText
* @param {import('buffer').Blob} blob
* @param {string?} encoding
*/
readAsText (blob, encoding = undefined) {
webidl.brandCheck(this, FileReader)
webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
blob = webidl.converters.Blob(blob, { strict: false })
if (encoding !== undefined) {
encoding = webidl.converters.DOMString(encoding)
}
// The readAsText(blob, encoding) method, when invoked,
// must initiate a read operation for blob with Text and encoding.
readOperation(this, blob, 'Text', encoding)
}
/**
* @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
* @param {import('buffer').Blob} blob
*/
readAsDataURL (blob) {
webidl.brandCheck(this, FileReader)
webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
blob = webidl.converters.Blob(blob, { strict: false })
// The readAsDataURL(blob) method, when invoked, must
// initiate a read operation for blob with DataURL.
readOperation(this, blob, 'DataURL')
}
/**
* @see https://w3c.github.io/FileAPI/#dfn-abort
*/
abort () {
// 1. If this's state is "empty" or if this's state is
// "done" set this's result to null and terminate
// this algorithm.
if (this[kState] === 'empty' || this[kState] === 'done') {
this[kResult] = null
return
}
// 2. If this's state is "loading" set this's state to
// "done" and set this's result to null.
if (this[kState] === 'loading') {
this[kState] = 'done'
this[kResult] = null
}
// 3. If there are any tasks from this on the file reading
// task source in an affiliated task queue, then remove
// those tasks from that task queue.
this[kAborted] = true
// 4. Terminate the algorithm for the read method being processed.
// TODO
// 5. Fire a progress event called abort at this.
fireAProgressEvent('abort', this)
// 6. If this's state is not "loading", fire a progress
// event called loadend at this.
if (this[kState] !== 'loading') {
fireAProgressEvent('loadend', this)
}
}
/**
* @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
*/
get readyState () {
webidl.brandCheck(this, FileReader)
switch (this[kState]) {
case 'empty': return this.EMPTY
case 'loading': return this.LOADING
case 'done': return this.DONE
}
}
/**
* @see https://w3c.github.io/FileAPI/#dom-filereader-result
*/
get result () {
webidl.brandCheck(this, FileReader)
// The result attributes getter, when invoked, must return
// this's result.
return this[kResult]
}
/**
* @see https://w3c.github.io/FileAPI/#dom-filereader-error
*/
get error () {
webidl.brandCheck(this, FileReader)
// The error attributes getter, when invoked, must return
// this's error.
return this[kError]
}
get onloadend () {
webidl.brandCheck(this, FileReader)
return this[kEvents].loadend
}
set onloadend (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].loadend) {
this.removeEventListener('loadend', this[kEvents].loadend)
}
if (typeof fn === 'function') {
this[kEvents].loadend = fn
this.addEventListener('loadend', fn)
} else {
this[kEvents].loadend = null
}
}
get onerror () {
webidl.brandCheck(this, FileReader)
return this[kEvents].error
}
set onerror (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].error) {
this.removeEventListener('error', this[kEvents].error)
}
if (typeof fn === 'function') {
this[kEvents].error = fn
this.addEventListener('error', fn)
} else {
this[kEvents].error = null
}
}
get onloadstart () {
webidl.brandCheck(this, FileReader)
return this[kEvents].loadstart
}
set onloadstart (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].loadstart) {
this.removeEventListener('loadstart', this[kEvents].loadstart)
}
if (typeof fn === 'function') {
this[kEvents].loadstart = fn
this.addEventListener('loadstart', fn)
} else {
this[kEvents].loadstart = null
}
}
get onprogress () {
webidl.brandCheck(this, FileReader)
return this[kEvents].progress
}
set onprogress (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].progress) {
this.removeEventListener('progress', this[kEvents].progress)
}
if (typeof fn === 'function') {
this[kEvents].progress = fn
this.addEventListener('progress', fn)
} else {
this[kEvents].progress = null
}
}
get onload () {
webidl.brandCheck(this, FileReader)
return this[kEvents].load
}
set onload (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].load) {
this.removeEventListener('load', this[kEvents].load)
}
if (typeof fn === 'function') {
this[kEvents].load = fn
this.addEventListener('load', fn)
} else {
this[kEvents].load = null
}
}
get onabort () {
webidl.brandCheck(this, FileReader)
return this[kEvents].abort
}
set onabort (fn) {
webidl.brandCheck(this, FileReader)
if (this[kEvents].abort) {
this.removeEventListener('abort', this[kEvents].abort)
}
if (typeof fn === 'function') {
this[kEvents].abort = fn
this.addEventListener('abort', fn)
} else {
this[kEvents].abort = null
}
}
}
// https://w3c.github.io/FileAPI/#dom-filereader-empty
FileReader.EMPTY = FileReader.prototype.EMPTY = 0
// https://w3c.github.io/FileAPI/#dom-filereader-loading
FileReader.LOADING = FileReader.prototype.LOADING = 1
// https://w3c.github.io/FileAPI/#dom-filereader-done
FileReader.DONE = FileReader.prototype.DONE = 2
Object.defineProperties(FileReader.prototype, {
EMPTY: staticPropertyDescriptors,
LOADING: staticPropertyDescriptors,
DONE: staticPropertyDescriptors,
readAsArrayBuffer: kEnumerableProperty,
readAsBinaryString: kEnumerableProperty,
readAsText: kEnumerableProperty,
readAsDataURL: kEnumerableProperty,
abort: kEnumerableProperty,
readyState: kEnumerableProperty,
result: kEnumerableProperty,
error: kEnumerableProperty,
onloadstart: kEnumerableProperty,
onprogress: kEnumerableProperty,
onload: kEnumerableProperty,
onabort: kEnumerableProperty,
onerror: kEnumerableProperty,
onloadend: kEnumerableProperty,
[Symbol.toStringTag]: {
value: 'FileReader',
writable: false,
enumerable: false,
configurable: true
}
})
Object.defineProperties(FileReader, {
EMPTY: staticPropertyDescriptors,
LOADING: staticPropertyDescriptors,
DONE: staticPropertyDescriptors
})
module.exports = {
FileReader
}
/***/ }),
/***/ 55504:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { webidl } = __nccwpck_require__(21744)
const kState = Symbol('ProgressEvent state')
/**
* @see https://xhr.spec.whatwg.org/#progressevent
*/
class ProgressEvent extends Event {
constructor (type, eventInitDict = {}) {
type = webidl.converters.DOMString(type)
eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
super(type, eventInitDict)
this[kState] = {
lengthComputable: eventInitDict.lengthComputable,
loaded: eventInitDict.loaded,
total: eventInitDict.total
}
}
get lengthComputable () {
webidl.brandCheck(this, ProgressEvent)
return this[kState].lengthComputable
}
get loaded () {
webidl.brandCheck(this, ProgressEvent)
return this[kState].loaded
}
get total () {
webidl.brandCheck(this, ProgressEvent)
return this[kState].total
}
}
webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
{
key: 'lengthComputable',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'loaded',
converter: webidl.converters['unsigned long long'],
defaultValue: 0
},
{
key: 'total',
converter: webidl.converters['unsigned long long'],
defaultValue: 0
},
{
key: 'bubbles',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'cancelable',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'composed',
converter: webidl.converters.boolean,
defaultValue: false
}
])
module.exports = {
ProgressEvent
}
/***/ }),
/***/ 29054:
/***/ ((module) => {
"use strict";
module.exports = {
kState: Symbol('FileReader state'),
kResult: Symbol('FileReader result'),
kError: Symbol('FileReader error'),
kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
kEvents: Symbol('FileReader events'),
kAborted: Symbol('FileReader aborted')
}
/***/ }),
/***/ 87530:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kState,
kError,
kResult,
kAborted,
kLastProgressEventFired
} = __nccwpck_require__(29054)
const { ProgressEvent } = __nccwpck_require__(55504)
const { getEncoding } = __nccwpck_require__(84854)
const { DOMException } = __nccwpck_require__(41037)
const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685)
const { types } = __nccwpck_require__(73837)
const { StringDecoder } = __nccwpck_require__(71576)
const { btoa } = __nccwpck_require__(14300)
/** @type {PropertyDescriptor} */
const staticPropertyDescriptors = {
enumerable: true,
writable: false,
configurable: false
}
/**
* @see https://w3c.github.io/FileAPI/#readOperation
* @param {import('./filereader').FileReader} fr
* @param {import('buffer').Blob} blob
* @param {string} type
* @param {string?} encodingName
*/
function readOperation (fr, blob, type, encodingName) {
// 1. If frs state is "loading", throw an InvalidStateError
// DOMException.
if (fr[kState] === 'loading') {
throw new DOMException('Invalid state', 'InvalidStateError')
}
// 2. Set frs state to "loading".
fr[kState] = 'loading'
// 3. Set frs result to null.
fr[kResult] = null
// 4. Set frs error to null.
fr[kError] = null
// 5. Let stream be the result of calling get stream on blob.
/** @type {import('stream/web').ReadableStream} */
const stream = blob.stream()
// 6. Let reader be the result of getting a reader from stream.
const reader = stream.getReader()
// 7. Let bytes be an empty byte sequence.
/** @type {Uint8Array[]} */
const bytes = []
// 8. Let chunkPromise be the result of reading a chunk from
// stream with reader.
let chunkPromise = reader.read()
// 9. Let isFirstChunk be true.
let isFirstChunk = true
// 10. In parallel, while true:
// Note: "In parallel" just means non-blocking
// Note 2: readOperation itself cannot be async as double
// reading the body would then reject the promise, instead
// of throwing an error.
;(async () => {
while (!fr[kAborted]) {
// 1. Wait for chunkPromise to be fulfilled or rejected.
try {
const { done, value } = await chunkPromise
// 2. If chunkPromise is fulfilled, and isFirstChunk is
// true, queue a task to fire a progress event called
// loadstart at fr.
if (isFirstChunk && !fr[kAborted]) {
queueMicrotask(() => {
fireAProgressEvent('loadstart', fr)
})
}
// 3. Set isFirstChunk to false.
isFirstChunk = false
// 4. If chunkPromise is fulfilled with an object whose
// done property is false and whose value property is
// a Uint8Array object, run these steps:
if (!done && types.isUint8Array(value)) {
// 1. Let bs be the byte sequence represented by the
// Uint8Array object.
// 2. Append bs to bytes.
bytes.push(value)
// 3. If roughly 50ms have passed since these steps
// were last invoked, queue a task to fire a
// progress event called progress at fr.
if (
(
fr[kLastProgressEventFired] === undefined ||
Date.now() - fr[kLastProgressEventFired] >= 50
) &&
!fr[kAborted]
) {
fr[kLastProgressEventFired] = Date.now()
queueMicrotask(() => {
fireAProgressEvent('progress', fr)
})
}
// 4. Set chunkPromise to the result of reading a
// chunk from stream with reader.
chunkPromise = reader.read()
} else if (done) {
// 5. Otherwise, if chunkPromise is fulfilled with an
// object whose done property is true, queue a task
// to run the following steps and abort this algorithm:
queueMicrotask(() => {
// 1. Set frs state to "done".
fr[kState] = 'done'
// 2. Let result be the result of package data given
// bytes, type, blobs type, and encodingName.
try {
const result = packageData(bytes, type, blob.type, encodingName)
// 4. Else:
if (fr[kAborted]) {
return
}
// 1. Set frs result to result.
fr[kResult] = result
// 2. Fire a progress event called load at the fr.
fireAProgressEvent('load', fr)
} catch (error) {
// 3. If package data threw an exception error:
// 1. Set frs error to error.
fr[kError] = error
// 2. Fire a progress event called error at fr.
fireAProgressEvent('error', fr)
}
// 5. If frs state is not "loading", fire a progress
// event called loadend at the fr.
if (fr[kState] !== 'loading') {
fireAProgressEvent('loadend', fr)
}
})
break
}
} catch (error) {
if (fr[kAborted]) {
return
}
// 6. Otherwise, if chunkPromise is rejected with an
// error error, queue a task to run the following
// steps and abort this algorithm:
queueMicrotask(() => {
// 1. Set frs state to "done".
fr[kState] = 'done'
// 2. Set frs error to error.
fr[kError] = error
// 3. Fire a progress event called error at fr.
fireAProgressEvent('error', fr)
// 4. If frs state is not "loading", fire a progress
// event called loadend at fr.
if (fr[kState] !== 'loading') {
fireAProgressEvent('loadend', fr)
}
})
break
}
}
})()
}
/**
* @see https://w3c.github.io/FileAPI/#fire-a-progress-event
* @see https://dom.spec.whatwg.org/#concept-event-fire
* @param {string} e The name of the event
* @param {import('./filereader').FileReader} reader
*/
function fireAProgressEvent (e, reader) {
// The progress event e does not bubble. e.bubbles must be false
// The progress event e is NOT cancelable. e.cancelable must be false
const event = new ProgressEvent(e, {
bubbles: false,
cancelable: false
})
reader.dispatchEvent(event)
}
/**
* @see https://w3c.github.io/FileAPI/#blob-package-data
* @param {Uint8Array[]} bytes
* @param {string} type
* @param {string?} mimeType
* @param {string?} encodingName
*/
function packageData (bytes, type, mimeType, encodingName) {
// 1. A Blob has an associated package data algorithm, given
// bytes, a type, a optional mimeType, and a optional
// encodingName, which switches on type and runs the
// associated steps:
switch (type) {
case 'DataURL': {
// 1. Return bytes as a DataURL [RFC2397] subject to
// the considerations below:
// * Use mimeType as part of the Data URL if it is
// available in keeping with the Data URL
// specification [RFC2397].
// * If mimeType is not available return a Data URL
// without a media-type. [RFC2397].
// https://datatracker.ietf.org/doc/html/rfc2397#section-3
// dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
// mediatype := [ type "/" subtype ] *( ";" parameter )
// data := *urlchar
// parameter := attribute "=" value
let dataURL = 'data:'
const parsed = parseMIMEType(mimeType || 'application/octet-stream')
if (parsed !== 'failure') {
dataURL += serializeAMimeType(parsed)
}
dataURL += ';base64,'
const decoder = new StringDecoder('latin1')
for (const chunk of bytes) {
dataURL += btoa(decoder.write(chunk))
}
dataURL += btoa(decoder.end())
return dataURL
}
case 'Text': {
// 1. Let encoding be failure
let encoding = 'failure'
// 2. If the encodingName is present, set encoding to the
// result of getting an encoding from encodingName.
if (encodingName) {
encoding = getEncoding(encodingName)
}
// 3. If encoding is failure, and mimeType is present:
if (encoding === 'failure' && mimeType) {
// 1. Let type be the result of parse a MIME type
// given mimeType.
const type = parseMIMEType(mimeType)
// 2. If type is not failure, set encoding to the result
// of getting an encoding from types parameters["charset"].
if (type !== 'failure') {
encoding = getEncoding(type.parameters.get('charset'))
}
}
// 4. If encoding is failure, then set encoding to UTF-8.
if (encoding === 'failure') {
encoding = 'UTF-8'
}
// 5. Decode bytes using fallback encoding encoding, and
// return the result.
return decode(bytes, encoding)
}
case 'ArrayBuffer': {
// Return a new ArrayBuffer whose contents are bytes.
const sequence = combineByteSequences(bytes)
return sequence.buffer
}
case 'BinaryString': {
// Return bytes as a binary string, in which every byte
// is represented by a code unit of equal value [0..255].
let binaryString = ''
const decoder = new StringDecoder('latin1')
for (const chunk of bytes) {
binaryString += decoder.write(chunk)
}
binaryString += decoder.end()
return binaryString
}
}
}
/**
* @see https://encoding.spec.whatwg.org/#decode
* @param {Uint8Array[]} ioQueue
* @param {string} encoding
*/
function decode (ioQueue, encoding) {
const bytes = combineByteSequences(ioQueue)
// 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
const BOMEncoding = BOMSniffing(bytes)
let slice = 0
// 2. If BOMEncoding is non-null:
if (BOMEncoding !== null) {
// 1. Set encoding to BOMEncoding.
encoding = BOMEncoding
// 2. Read three bytes from ioQueue, if BOMEncoding is
// UTF-8; otherwise read two bytes.
// (Do nothing with those bytes.)
slice = BOMEncoding === 'UTF-8' ? 3 : 2
}
// 3. Process a queue with an instance of encodings
// decoder, ioQueue, output, and "replacement".
// 4. Return output.
const sliced = bytes.slice(slice)
return new TextDecoder(encoding).decode(sliced)
}
/**
* @see https://encoding.spec.whatwg.org/#bom-sniff
* @param {Uint8Array} ioQueue
*/
function BOMSniffing (ioQueue) {
// 1. Let BOM be the result of peeking 3 bytes from ioQueue,
// converted to a byte sequence.
const [a, b, c] = ioQueue
// 2. For each of the rows in the table below, starting with
// the first one and going down, if BOM starts with the
// bytes given in the first column, then return the
// encoding given in the cell in the second column of that
// row. Otherwise, return null.
if (a === 0xEF && b === 0xBB && c === 0xBF) {
return 'UTF-8'
} else if (a === 0xFE && b === 0xFF) {
return 'UTF-16BE'
} else if (a === 0xFF && b === 0xFE) {
return 'UTF-16LE'
}
return null
}
/**
* @param {Uint8Array[]} sequences
*/
function combineByteSequences (sequences) {
const size = sequences.reduce((a, b) => {
return a + b.byteLength
}, 0)
let offset = 0
return sequences.reduce((a, b) => {
a.set(b, offset)
offset += b.byteLength
return a
}, new Uint8Array(size))
}
module.exports = {
staticPropertyDescriptors,
readOperation,
fireAProgressEvent
}
/***/ }),
/***/ 21892:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// We include a version number for the Dispatcher API. In case of breaking changes,
// this version number must be increased to avoid conflicts.
const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
const { InvalidArgumentError } = __nccwpck_require__(48045)
const Agent = __nccwpck_require__(7890)
if (getGlobalDispatcher() === undefined) {
setGlobalDispatcher(new Agent())
}
function setGlobalDispatcher (agent) {
if (!agent || typeof agent.dispatch !== 'function') {
throw new InvalidArgumentError('Argument agent must implement Agent')
}
Object.defineProperty(globalThis, globalDispatcher, {
value: agent,
writable: true,
enumerable: false,
configurable: false
})
}
function getGlobalDispatcher () {
return globalThis[globalDispatcher]
}
module.exports = {
setGlobalDispatcher,
getGlobalDispatcher
}
/***/ }),
/***/ 46930:
/***/ ((module) => {
"use strict";
module.exports = class DecoratorHandler {
constructor (handler) {
this.handler = handler
}
onConnect (...args) {
return this.handler.onConnect(...args)
}
onError (...args) {
return this.handler.onError(...args)
}
onUpgrade (...args) {
return this.handler.onUpgrade(...args)
}
onHeaders (...args) {
return this.handler.onHeaders(...args)
}
onData (...args) {
return this.handler.onData(...args)
}
onComplete (...args) {
return this.handler.onComplete(...args)
}
onBodySent (...args) {
return this.handler.onBodySent(...args)
}
}
/***/ }),
/***/ 72860:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const util = __nccwpck_require__(83983)
const { kBodyUsed } = __nccwpck_require__(72785)
const assert = __nccwpck_require__(39491)
const { InvalidArgumentError } = __nccwpck_require__(48045)
const EE = __nccwpck_require__(82361)
const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
const kBody = Symbol('body')
class BodyAsyncIterable {
constructor (body) {
this[kBody] = body
this[kBodyUsed] = false
}
async * [Symbol.asyncIterator] () {
assert(!this[kBodyUsed], 'disturbed')
this[kBodyUsed] = true
yield * this[kBody]
}
}
class RedirectHandler {
constructor (dispatch, maxRedirections, opts, handler) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError('maxRedirections must be a positive number')
}
util.validateHandler(handler, opts.method, opts.upgrade)
this.dispatch = dispatch
this.location = null
this.abort = null
this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
this.maxRedirections = maxRedirections
this.handler = handler
this.history = []
if (util.isStream(this.opts.body)) {
// TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
// so that it can be dispatched again?
// TODO (fix): Do we need 100-expect support to provide a way to do this properly?
if (util.bodyLength(this.opts.body) === 0) {
this.opts.body
.on('data', function () {
assert(false)
})
}
if (typeof this.opts.body.readableDidRead !== 'boolean') {
this.opts.body[kBodyUsed] = false
EE.prototype.on.call(this.opts.body, 'data', function () {
this[kBodyUsed] = true
})
}
} else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
// TODO (fix): We can't access ReadableStream internal state
// to determine whether or not it has been disturbed. This is just
// a workaround.
this.opts.body = new BodyAsyncIterable(this.opts.body)
} else if (
this.opts.body &&
typeof this.opts.body !== 'string' &&
!ArrayBuffer.isView(this.opts.body) &&
util.isIterable(this.opts.body)
) {
// TODO: Should we allow re-using iterable if !this.opts.idempotent
// or through some other flag?
this.opts.body = new BodyAsyncIterable(this.opts.body)
}
}
onConnect (abort) {
this.abort = abort
this.handler.onConnect(abort, { history: this.history })
}
onUpgrade (statusCode, headers, socket) {
this.handler.onUpgrade(statusCode, headers, socket)
}
onError (error) {
this.handler.onError(error)
}
onHeaders (statusCode, headers, resume, statusText) {
this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
? null
: parseLocation(statusCode, headers)
if (this.opts.origin) {
this.history.push(new URL(this.opts.path, this.opts.origin))
}
if (!this.location) {
return this.handler.onHeaders(statusCode, headers, resume, statusText)
}
const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
const path = search ? `${pathname}${search}` : pathname
// Remove headers referring to the original URL.
// By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
// https://tools.ietf.org/html/rfc7231#section-6.4
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
this.opts.path = path
this.opts.origin = origin
this.opts.maxRedirections = 0
this.opts.query = null
// https://tools.ietf.org/html/rfc7231#section-6.4.4
// In case of HTTP 303, always replace method to be either HEAD or GET
if (statusCode === 303 && this.opts.method !== 'HEAD') {
this.opts.method = 'GET'
this.opts.body = null
}
}
onData (chunk) {
if (this.location) {
/*
https://tools.ietf.org/html/rfc7231#section-6.4
TLDR: undici always ignores 3xx response bodies.
Redirection is used to serve the requested resource from another URL, so it is assumes that
no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
(which means it's optional and not mandated) contain just an hyperlink to the value of
the Location response header, so the body can be ignored safely.
For status 300, which is "Multiple Choices", the spec mentions both generating a Location
response header AND a response body with the other possible location to follow.
Since the spec explicitily chooses not to specify a format for such body and leave it to
servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
*/
} else {
return this.handler.onData(chunk)
}
}
onComplete (trailers) {
if (this.location) {
/*
https://tools.ietf.org/html/rfc7231#section-6.4
TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
and neither are useful if present.
See comment on onData method above for more detailed informations.
*/
this.location = null
this.abort = null
this.dispatch(this.opts, this)
} else {
this.handler.onComplete(trailers)
}
}
onBodySent (chunk) {
if (this.handler.onBodySent) {
this.handler.onBodySent(chunk)
}
}
}
function parseLocation (statusCode, headers) {
if (redirectableStatusCodes.indexOf(statusCode) === -1) {
return null
}
for (let i = 0; i < headers.length; i += 2) {
if (headers[i].toString().toLowerCase() === 'location') {
return headers[i + 1]
}
}
}
// https://tools.ietf.org/html/rfc7231#section-6.4.4
function shouldRemoveHeader (header, removeContent, unknownOrigin) {
if (header.length === 4) {
return util.headerNameToString(header) === 'host'
}
if (removeContent && util.headerNameToString(header).startsWith('content-')) {
return true
}
if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
const name = util.headerNameToString(header)
return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
}
return false
}
// https://tools.ietf.org/html/rfc7231#section-6.4
function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
const ret = []
if (Array.isArray(headers)) {
for (let i = 0; i < headers.length; i += 2) {
if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
ret.push(headers[i], headers[i + 1])
}
}
} else if (headers && typeof headers === 'object') {
for (const key of Object.keys(headers)) {
if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
ret.push(key, headers[key])
}
}
} else {
assert(headers == null, 'headers must be an object or an array')
}
return ret
}
module.exports = RedirectHandler
/***/ }),
/***/ 82286:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const assert = __nccwpck_require__(39491)
const { kRetryHandlerDefaultRetry } = __nccwpck_require__(72785)
const { RequestRetryError } = __nccwpck_require__(48045)
const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(83983)
function calculateRetryAfterHeader (retryAfter) {
const current = Date.now()
const diff = new Date(retryAfter).getTime() - current
return diff
}
class RetryHandler {
constructor (opts, handlers) {
const { retryOptions, ...dispatchOpts } = opts
const {
// Retry scoped
retry: retryFn,
maxRetries,
maxTimeout,
minTimeout,
timeoutFactor,
// Response scoped
methods,
errorCodes,
retryAfter,
statusCodes
} = retryOptions ?? {}
this.dispatch = handlers.dispatch
this.handler = handlers.handler
this.opts = dispatchOpts
this.abort = null
this.aborted = false
this.retryOpts = {
retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
retryAfter: retryAfter ?? true,
maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
timeout: minTimeout ?? 500, // .5s
timeoutFactor: timeoutFactor ?? 2,
maxRetries: maxRetries ?? 5,
// What errors we should retry
methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
// Indicates which errors to retry
statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
// List of errors to retry
errorCodes: errorCodes ?? [
'ECONNRESET',
'ECONNREFUSED',
'ENOTFOUND',
'ENETDOWN',
'ENETUNREACH',
'EHOSTDOWN',
'EHOSTUNREACH',
'EPIPE'
]
}
this.retryCount = 0
this.start = 0
this.end = null
this.etag = null
this.resume = null
// Handle possible onConnect duplication
this.handler.onConnect(reason => {
this.aborted = true
if (this.abort) {
this.abort(reason)
} else {
this.reason = reason
}
})
}
onRequestSent () {
if (this.handler.onRequestSent) {
this.handler.onRequestSent()
}
}
onUpgrade (statusCode, headers, socket) {
if (this.handler.onUpgrade) {
this.handler.onUpgrade(statusCode, headers, socket)
}
}
onConnect (abort) {
if (this.aborted) {
abort(this.reason)
} else {
this.abort = abort
}
}
onBodySent (chunk) {
if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
}
static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
const { statusCode, code, headers } = err
const { method, retryOptions } = opts
const {
maxRetries,
timeout,
maxTimeout,
timeoutFactor,
statusCodes,
errorCodes,
methods
} = retryOptions
let { counter, currentTimeout } = state
currentTimeout =
currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
// Any code that is not a Undici's originated and allowed to retry
if (
code &&
code !== 'UND_ERR_REQ_RETRY' &&
code !== 'UND_ERR_SOCKET' &&
!errorCodes.includes(code)
) {
cb(err)
return
}
// If a set of method are provided and the current method is not in the list
if (Array.isArray(methods) && !methods.includes(method)) {
cb(err)
return
}
// If a set of status code are provided and the current status code is not in the list
if (
statusCode != null &&
Array.isArray(statusCodes) &&
!statusCodes.includes(statusCode)
) {
cb(err)
return
}
// If we reached the max number of retries
if (counter > maxRetries) {
cb(err)
return
}
let retryAfterHeader = headers != null && headers['retry-after']
if (retryAfterHeader) {
retryAfterHeader = Number(retryAfterHeader)
retryAfterHeader = isNaN(retryAfterHeader)
? calculateRetryAfterHeader(retryAfterHeader)
: retryAfterHeader * 1e3 // Retry-After is in seconds
}
const retryTimeout =
retryAfterHeader > 0
? Math.min(retryAfterHeader, maxTimeout)
: Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
state.currentTimeout = retryTimeout
setTimeout(() => cb(null), retryTimeout)
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
const headers = parseHeaders(rawHeaders)
this.retryCount += 1
if (statusCode >= 300) {
this.abort(
new RequestRetryError('Request failed', statusCode, {
headers,
count: this.retryCount
})
)
return false
}
// Checkpoint for resume from where we left it
if (this.resume != null) {
this.resume = null
if (statusCode !== 206) {
return true
}
const contentRange = parseRangeHeader(headers['content-range'])
// If no content range
if (!contentRange) {
this.abort(
new RequestRetryError('Content-Range mismatch', statusCode, {
headers,
count: this.retryCount
})
)
return false
}
// Let's start with a weak etag check
if (this.etag != null && this.etag !== headers.etag) {
this.abort(
new RequestRetryError('ETag mismatch', statusCode, {
headers,
count: this.retryCount
})
)
return false
}
const { start, size, end = size } = contentRange
assert(this.start === start, 'content-range mismatch')
assert(this.end == null || this.end === end, 'content-range mismatch')
this.resume = resume
return true
}
if (this.end == null) {
if (statusCode === 206) {
// First time we receive 206
const range = parseRangeHeader(headers['content-range'])
if (range == null) {
return this.handler.onHeaders(
statusCode,
rawHeaders,
resume,
statusMessage
)
}
const { start, size, end = size } = range
assert(
start != null && Number.isFinite(start) && this.start !== start,
'content-range mismatch'
)
assert(Number.isFinite(start))
assert(
end != null && Number.isFinite(end) && this.end !== end,
'invalid content-length'
)
this.start = start
this.end = end
}
// We make our best to checkpoint the body for further range headers
if (this.end == null) {
const contentLength = headers['content-length']
this.end = contentLength != null ? Number(contentLength) : null
}
assert(Number.isFinite(this.start))
assert(
this.end == null || Number.isFinite(this.end),
'invalid content-length'
)
this.resume = resume
this.etag = headers.etag != null ? headers.etag : null
return this.handler.onHeaders(
statusCode,
rawHeaders,
resume,
statusMessage
)
}
const err = new RequestRetryError('Request failed', statusCode, {
headers,
count: this.retryCount
})
this.abort(err)
return false
}
onData (chunk) {
this.start += chunk.length
return this.handler.onData(chunk)
}
onComplete (rawTrailers) {
this.retryCount = 0
return this.handler.onComplete(rawTrailers)
}
onError (err) {
if (this.aborted || isDisturbed(this.opts.body)) {
return this.handler.onError(err)
}
this.retryOpts.retry(
err,
{
state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
opts: { retryOptions: this.retryOpts, ...this.opts }
},
onRetry.bind(this)
)
function onRetry (err) {
if (err != null || this.aborted || isDisturbed(this.opts.body)) {
return this.handler.onError(err)
}
if (this.start !== 0) {
this.opts = {
...this.opts,
headers: {
...this.opts.headers,
range: `bytes=${this.start}-${this.end ?? ''}`
}
}
}
try {
this.dispatch(this.opts, this)
} catch (err) {
this.handler.onError(err)
}
}
}
}
module.exports = RetryHandler
/***/ }),
/***/ 38861:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const RedirectHandler = __nccwpck_require__(72860)
function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
return (dispatch) => {
return function Intercept (opts, handler) {
const { maxRedirections = defaultMaxRedirections } = opts
if (!maxRedirections) {
return dispatch(opts, handler)
}
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
return dispatch(opts, redirectHandler)
}
}
}
module.exports = createRedirectInterceptor
/***/ }),
/***/ 30953:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
const utils_1 = __nccwpck_require__(41891);
// C headers
var ERROR;
(function (ERROR) {
ERROR[ERROR["OK"] = 0] = "OK";
ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
ERROR[ERROR["STRICT"] = 2] = "STRICT";
ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
ERROR[ERROR["USER"] = 24] = "USER";
})(ERROR = exports.ERROR || (exports.ERROR = {}));
var TYPE;
(function (TYPE) {
TYPE[TYPE["BOTH"] = 0] = "BOTH";
TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
})(TYPE = exports.TYPE || (exports.TYPE = {}));
var FLAGS;
(function (FLAGS) {
FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
// 1 << 8 is unused
FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
var LENIENT_FLAGS;
(function (LENIENT_FLAGS) {
LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
var METHODS;
(function (METHODS) {
METHODS[METHODS["DELETE"] = 0] = "DELETE";
METHODS[METHODS["GET"] = 1] = "GET";
METHODS[METHODS["HEAD"] = 2] = "HEAD";
METHODS[METHODS["POST"] = 3] = "POST";
METHODS[METHODS["PUT"] = 4] = "PUT";
/* pathological */
METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
METHODS[METHODS["TRACE"] = 7] = "TRACE";
/* WebDAV */
METHODS[METHODS["COPY"] = 8] = "COPY";
METHODS[METHODS["LOCK"] = 9] = "LOCK";
METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
METHODS[METHODS["MOVE"] = 11] = "MOVE";
METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
METHODS[METHODS["BIND"] = 16] = "BIND";
METHODS[METHODS["REBIND"] = 17] = "REBIND";
METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
METHODS[METHODS["ACL"] = 19] = "ACL";
/* subversion */
METHODS[METHODS["REPORT"] = 20] = "REPORT";
METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
METHODS[METHODS["MERGE"] = 23] = "MERGE";
/* upnp */
METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
/* RFC-5789 */
METHODS[METHODS["PATCH"] = 28] = "PATCH";
METHODS[METHODS["PURGE"] = 29] = "PURGE";
/* CalDAV */
METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
/* RFC-2068, section 19.6.1.2 */
METHODS[METHODS["LINK"] = 31] = "LINK";
METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
/* icecast */
METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
/* RFC-7540, section 11.6 */
METHODS[METHODS["PRI"] = 34] = "PRI";
/* RFC-2326 RTSP */
METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
METHODS[METHODS["SETUP"] = 37] = "SETUP";
METHODS[METHODS["PLAY"] = 38] = "PLAY";
METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
METHODS[METHODS["RECORD"] = 44] = "RECORD";
/* RAOP */
METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
})(METHODS = exports.METHODS || (exports.METHODS = {}));
exports.METHODS_HTTP = [
METHODS.DELETE,
METHODS.GET,
METHODS.HEAD,
METHODS.POST,
METHODS.PUT,
METHODS.CONNECT,
METHODS.OPTIONS,
METHODS.TRACE,
METHODS.COPY,
METHODS.LOCK,
METHODS.MKCOL,
METHODS.MOVE,
METHODS.PROPFIND,
METHODS.PROPPATCH,
METHODS.SEARCH,
METHODS.UNLOCK,
METHODS.BIND,
METHODS.REBIND,
METHODS.UNBIND,
METHODS.ACL,
METHODS.REPORT,
METHODS.MKACTIVITY,
METHODS.CHECKOUT,
METHODS.MERGE,
METHODS['M-SEARCH'],
METHODS.NOTIFY,
METHODS.SUBSCRIBE,
METHODS.UNSUBSCRIBE,
METHODS.PATCH,
METHODS.PURGE,
METHODS.MKCALENDAR,
METHODS.LINK,
METHODS.UNLINK,
METHODS.PRI,
// TODO(indutny): should we allow it with HTTP?
METHODS.SOURCE,
];
exports.METHODS_ICE = [
METHODS.SOURCE,
];
exports.METHODS_RTSP = [
METHODS.OPTIONS,
METHODS.DESCRIBE,
METHODS.ANNOUNCE,
METHODS.SETUP,
METHODS.PLAY,
METHODS.PAUSE,
METHODS.TEARDOWN,
METHODS.GET_PARAMETER,
METHODS.SET_PARAMETER,
METHODS.REDIRECT,
METHODS.RECORD,
METHODS.FLUSH,
// For AirPlay
METHODS.GET,
METHODS.POST,
];
exports.METHOD_MAP = utils_1.enumToMap(METHODS);
exports.H_METHOD_MAP = {};
Object.keys(exports.METHOD_MAP).forEach((key) => {
if (/^H/.test(key)) {
exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
}
});
var FINISH;
(function (FINISH) {
FINISH[FINISH["SAFE"] = 0] = "SAFE";
FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
})(FINISH = exports.FINISH || (exports.FINISH = {}));
exports.ALPHA = [];
for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
// Upper case
exports.ALPHA.push(String.fromCharCode(i));
// Lower case
exports.ALPHA.push(String.fromCharCode(i + 0x20));
}
exports.NUM_MAP = {
0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
};
exports.HEX_MAP = {
0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
};
exports.NUM = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
];
exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
exports.USERINFO_CHARS = exports.ALPHANUM
.concat(exports.MARK)
.concat(['%', ';', ':', '&', '=', '+', '$', ',']);
// TODO(indutny): use RFC
exports.STRICT_URL_CHAR = [
'!', '"', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '-', '.', '/',
':', ';', '<', '=', '>',
'@', '[', '\\', ']', '^', '_',
'`',
'{', '|', '}', '~',
].concat(exports.ALPHANUM);
exports.URL_CHAR = exports.STRICT_URL_CHAR
.concat(['\t', '\f']);
// All characters with 0x80 bit set to 1
for (let i = 0x80; i <= 0xff; i++) {
exports.URL_CHAR.push(i);
}
exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
/* Tokens as defined by rfc 2616. Also lowercases them.
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
*/
exports.STRICT_TOKEN = [
'!', '#', '$', '%', '&', '\'',
'*', '+', '-', '.',
'^', '_', '`',
'|', '~',
].concat(exports.ALPHANUM);
exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
/*
* Verify that a char is a valid visible (printable) US-ASCII
* character or %x80-FF
*/
exports.HEADER_CHARS = ['\t'];
for (let i = 32; i <= 255; i++) {
if (i !== 127) {
exports.HEADER_CHARS.push(i);
}
}
// ',' = \x44
exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
exports.MAJOR = exports.NUM_MAP;
exports.MINOR = exports.MAJOR;
var HEADER_STATE;
(function (HEADER_STATE) {
HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
exports.SPECIAL_HEADERS = {
'connection': HEADER_STATE.CONNECTION,
'content-length': HEADER_STATE.CONTENT_LENGTH,
'proxy-connection': HEADER_STATE.CONNECTION,
'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
'upgrade': HEADER_STATE.UPGRADE,
};
//# sourceMappingURL=constants.js.map
/***/ }),
/***/ 61145:
/***/ ((module) => {
module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='
/***/ }),
/***/ 95627:
/***/ ((module) => {
module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
/***/ }),
/***/ 41891:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.enumToMap = void 0;
function enumToMap(obj) {
const res = {};
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (typeof value === 'number') {
res[key] = value;
}
});
return res;
}
exports.enumToMap = enumToMap;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 66771:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { kClients } = __nccwpck_require__(72785)
const Agent = __nccwpck_require__(7890)
const {
kAgent,
kMockAgentSet,
kMockAgentGet,
kDispatches,
kIsMockActive,
kNetConnect,
kGetNetConnect,
kOptions,
kFactory
} = __nccwpck_require__(24347)
const MockClient = __nccwpck_require__(58687)
const MockPool = __nccwpck_require__(26193)
const { matchValue, buildMockOptions } = __nccwpck_require__(79323)
const { InvalidArgumentError, UndiciError } = __nccwpck_require__(48045)
const Dispatcher = __nccwpck_require__(60412)
const Pluralizer = __nccwpck_require__(78891)
const PendingInterceptorsFormatter = __nccwpck_require__(86823)
class FakeWeakRef {
constructor (value) {
this.value = value
}
deref () {
return this.value
}
}
class MockAgent extends Dispatcher {
constructor (opts) {
super(opts)
this[kNetConnect] = true
this[kIsMockActive] = true
// Instantiate Agent and encapsulate
if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
const agent = opts && opts.agent ? opts.agent : new Agent(opts)
this[kAgent] = agent
this[kClients] = agent[kClients]
this[kOptions] = buildMockOptions(opts)
}
get (origin) {
let dispatcher = this[kMockAgentGet](origin)
if (!dispatcher) {
dispatcher = this[kFactory](origin)
this[kMockAgentSet](origin, dispatcher)
}
return dispatcher
}
dispatch (opts, handler) {
// Call MockAgent.get to perform additional setup before dispatching as normal
this.get(opts.origin)
return this[kAgent].dispatch(opts, handler)
}
async close () {
await this[kAgent].close()
this[kClients].clear()
}
deactivate () {
this[kIsMockActive] = false
}
activate () {
this[kIsMockActive] = true
}
enableNetConnect (matcher) {
if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
if (Array.isArray(this[kNetConnect])) {
this[kNetConnect].push(matcher)
} else {
this[kNetConnect] = [matcher]
}
} else if (typeof matcher === 'undefined') {
this[kNetConnect] = true
} else {
throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
}
}
disableNetConnect () {
this[kNetConnect] = false
}
// This is required to bypass issues caused by using global symbols - see:
// https://github.com/nodejs/undici/issues/1447
get isMockActive () {
return this[kIsMockActive]
}
[kMockAgentSet] (origin, dispatcher) {
this[kClients].set(origin, new FakeWeakRef(dispatcher))
}
[kFactory] (origin) {
const mockOptions = Object.assign({ agent: this }, this[kOptions])
return this[kOptions] && this[kOptions].connections === 1
? new MockClient(origin, mockOptions)
: new MockPool(origin, mockOptions)
}
[kMockAgentGet] (origin) {
// First check if we can immediately find it
const ref = this[kClients].get(origin)
if (ref) {
return ref.deref()
}
// If the origin is not a string create a dummy parent pool and return to user
if (typeof origin !== 'string') {
const dispatcher = this[kFactory]('http://localhost:9999')
this[kMockAgentSet](origin, dispatcher)
return dispatcher
}
// If we match, create a pool and assign the same dispatches
for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
const nonExplicitDispatcher = nonExplicitRef.deref()
if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
const dispatcher = this[kFactory](origin)
this[kMockAgentSet](origin, dispatcher)
dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
return dispatcher
}
}
}
[kGetNetConnect] () {
return this[kNetConnect]
}
pendingInterceptors () {
const mockAgentClients = this[kClients]
return Array.from(mockAgentClients.entries())
.flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
.filter(({ pending }) => pending)
}
assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
const pending = this.pendingInterceptors()
if (pending.length === 0) {
return
}
const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
throw new UndiciError(`
${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
${pendingInterceptorsFormatter.format(pending)}
`.trim())
}
}
module.exports = MockAgent
/***/ }),
/***/ 58687:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { promisify } = __nccwpck_require__(73837)
const Client = __nccwpck_require__(33598)
const { buildMockDispatch } = __nccwpck_require__(79323)
const {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected
} = __nccwpck_require__(24347)
const { MockInterceptor } = __nccwpck_require__(90410)
const Symbols = __nccwpck_require__(72785)
const { InvalidArgumentError } = __nccwpck_require__(48045)
/**
* MockClient provides an API that extends the Client to influence the mockDispatches.
*/
class MockClient extends Client {
constructor (origin, opts) {
super(origin, opts)
if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
this[kMockAgent] = opts.agent
this[kOrigin] = origin
this[kDispatches] = []
this[kConnected] = 1
this[kOriginalDispatch] = this.dispatch
this[kOriginalClose] = this.close.bind(this)
this.dispatch = buildMockDispatch.call(this)
this.close = this[kClose]
}
get [Symbols.kConnected] () {
return this[kConnected]
}
/**
* Sets up the base interceptor for mocking replies from undici.
*/
intercept (opts) {
return new MockInterceptor(opts, this[kDispatches])
}
async [kClose] () {
await promisify(this[kOriginalClose])()
this[kConnected] = 0
this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
}
module.exports = MockClient
/***/ }),
/***/ 50888:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { UndiciError } = __nccwpck_require__(48045)
class MockNotMatchedError extends UndiciError {
constructor (message) {
super(message)
Error.captureStackTrace(this, MockNotMatchedError)
this.name = 'MockNotMatchedError'
this.message = message || 'The request does not match any registered mock dispatches'
this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
}
module.exports = {
MockNotMatchedError
}
/***/ }),
/***/ 90410:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(79323)
const {
kDispatches,
kDispatchKey,
kDefaultHeaders,
kDefaultTrailers,
kContentLength,
kMockDispatch
} = __nccwpck_require__(24347)
const { InvalidArgumentError } = __nccwpck_require__(48045)
const { buildURL } = __nccwpck_require__(83983)
/**
* Defines the scope API for an interceptor reply
*/
class MockScope {
constructor (mockDispatch) {
this[kMockDispatch] = mockDispatch
}
/**
* Delay a reply by a set amount in ms.
*/
delay (waitInMs) {
if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
}
this[kMockDispatch].delay = waitInMs
return this
}
/**
* For a defined reply, never mark as consumed.
*/
persist () {
this[kMockDispatch].persist = true
return this
}
/**
* Allow one to define a reply for a set amount of matching requests.
*/
times (repeatTimes) {
if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
}
this[kMockDispatch].times = repeatTimes
return this
}
}
/**
* Defines an interceptor for a Mock
*/
class MockInterceptor {
constructor (opts, mockDispatches) {
if (typeof opts !== 'object') {
throw new InvalidArgumentError('opts must be an object')
}
if (typeof opts.path === 'undefined') {
throw new InvalidArgumentError('opts.path must be defined')
}
if (typeof opts.method === 'undefined') {
opts.method = 'GET'
}
// See https://github.com/nodejs/undici/issues/1245
// As per RFC 3986, clients are not supposed to send URI
// fragments to servers when they retrieve a document,
if (typeof opts.path === 'string') {
if (opts.query) {
opts.path = buildURL(opts.path, opts.query)
} else {
// Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
const parsedURL = new URL(opts.path, 'data://')
opts.path = parsedURL.pathname + parsedURL.search
}
}
if (typeof opts.method === 'string') {
opts.method = opts.method.toUpperCase()
}
this[kDispatchKey] = buildKey(opts)
this[kDispatches] = mockDispatches
this[kDefaultHeaders] = {}
this[kDefaultTrailers] = {}
this[kContentLength] = false
}
createMockScopeDispatchData (statusCode, data, responseOptions = {}) {
const responseData = getResponseData(data)
const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
return { statusCode, data, headers, trailers }
}
validateReplyParameters (statusCode, data, responseOptions) {
if (typeof statusCode === 'undefined') {
throw new InvalidArgumentError('statusCode must be defined')
}
if (typeof data === 'undefined') {
throw new InvalidArgumentError('data must be defined')
}
if (typeof responseOptions !== 'object') {
throw new InvalidArgumentError('responseOptions must be an object')
}
}
/**
* Mock an undici request with a defined reply.
*/
reply (replyData) {
// Values of reply aren't available right now as they
// can only be available when the reply callback is invoked.
if (typeof replyData === 'function') {
// We'll first wrap the provided callback in another function,
// this function will properly resolve the data from the callback
// when invoked.
const wrappedDefaultsCallback = (opts) => {
// Our reply options callback contains the parameter for statusCode, data and options.
const resolvedData = replyData(opts)
// Check if it is in the right format
if (typeof resolvedData !== 'object') {
throw new InvalidArgumentError('reply options callback must return an object')
}
const { statusCode, data = '', responseOptions = {} } = resolvedData
this.validateReplyParameters(statusCode, data, responseOptions)
// Since the values can be obtained immediately we return them
// from this higher order function that will be resolved later.
return {
...this.createMockScopeDispatchData(statusCode, data, responseOptions)
}
}
// Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
return new MockScope(newMockDispatch)
}
// We can have either one or three parameters, if we get here,
// we should have 1-3 parameters. So we spread the arguments of
// this function to obtain the parameters, since replyData will always
// just be the statusCode.
const [statusCode, data = '', responseOptions = {}] = [...arguments]
this.validateReplyParameters(statusCode, data, responseOptions)
// Send in-already provided data like usual
const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
return new MockScope(newMockDispatch)
}
/**
* Mock an undici request with a defined error.
*/
replyWithError (error) {
if (typeof error === 'undefined') {
throw new InvalidArgumentError('error must be defined')
}
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
return new MockScope(newMockDispatch)
}
/**
* Set default reply headers on the interceptor for subsequent replies
*/
defaultReplyHeaders (headers) {
if (typeof headers === 'undefined') {
throw new InvalidArgumentError('headers must be defined')
}
this[kDefaultHeaders] = headers
return this
}
/**
* Set default reply trailers on the interceptor for subsequent replies
*/
defaultReplyTrailers (trailers) {
if (typeof trailers === 'undefined') {
throw new InvalidArgumentError('trailers must be defined')
}
this[kDefaultTrailers] = trailers
return this
}
/**
* Set reply content length header for replies on the interceptor
*/
replyContentLength () {
this[kContentLength] = true
return this
}
}
module.exports.MockInterceptor = MockInterceptor
module.exports.MockScope = MockScope
/***/ }),
/***/ 26193:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { promisify } = __nccwpck_require__(73837)
const Pool = __nccwpck_require__(4634)
const { buildMockDispatch } = __nccwpck_require__(79323)
const {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected
} = __nccwpck_require__(24347)
const { MockInterceptor } = __nccwpck_require__(90410)
const Symbols = __nccwpck_require__(72785)
const { InvalidArgumentError } = __nccwpck_require__(48045)
/**
* MockPool provides an API that extends the Pool to influence the mockDispatches.
*/
class MockPool extends Pool {
constructor (origin, opts) {
super(origin, opts)
if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
this[kMockAgent] = opts.agent
this[kOrigin] = origin
this[kDispatches] = []
this[kConnected] = 1
this[kOriginalDispatch] = this.dispatch
this[kOriginalClose] = this.close.bind(this)
this.dispatch = buildMockDispatch.call(this)
this.close = this[kClose]
}
get [Symbols.kConnected] () {
return this[kConnected]
}
/**
* Sets up the base interceptor for mocking replies from undici.
*/
intercept (opts) {
return new MockInterceptor(opts, this[kDispatches])
}
async [kClose] () {
await promisify(this[kOriginalClose])()
this[kConnected] = 0
this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
}
module.exports = MockPool
/***/ }),
/***/ 24347:
/***/ ((module) => {
"use strict";
module.exports = {
kAgent: Symbol('agent'),
kOptions: Symbol('options'),
kFactory: Symbol('factory'),
kDispatches: Symbol('dispatches'),
kDispatchKey: Symbol('dispatch key'),
kDefaultHeaders: Symbol('default headers'),
kDefaultTrailers: Symbol('default trailers'),
kContentLength: Symbol('content length'),
kMockAgent: Symbol('mock agent'),
kMockAgentSet: Symbol('mock agent set'),
kMockAgentGet: Symbol('mock agent get'),
kMockDispatch: Symbol('mock dispatch'),
kClose: Symbol('close'),
kOriginalClose: Symbol('original agent close'),
kOrigin: Symbol('origin'),
kIsMockActive: Symbol('is mock active'),
kNetConnect: Symbol('net connect'),
kGetNetConnect: Symbol('get net connect'),
kConnected: Symbol('connected')
}
/***/ }),
/***/ 79323:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { MockNotMatchedError } = __nccwpck_require__(50888)
const {
kDispatches,
kMockAgent,
kOriginalDispatch,
kOrigin,
kGetNetConnect
} = __nccwpck_require__(24347)
const { buildURL, nop } = __nccwpck_require__(83983)
const { STATUS_CODES } = __nccwpck_require__(13685)
const {
types: {
isPromise
}
} = __nccwpck_require__(73837)
function matchValue (match, value) {
if (typeof match === 'string') {
return match === value
}
if (match instanceof RegExp) {
return match.test(value)
}
if (typeof match === 'function') {
return match(value) === true
}
return false
}
function lowerCaseEntries (headers) {
return Object.fromEntries(
Object.entries(headers).map(([headerName, headerValue]) => {
return [headerName.toLocaleLowerCase(), headerValue]
})
)
}
/**
* @param {import('../../index').Headers|string[]|Record<string, string>} headers
* @param {string} key
*/
function getHeaderByName (headers, key) {
if (Array.isArray(headers)) {
for (let i = 0; i < headers.length; i += 2) {
if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
return headers[i + 1]
}
}
return undefined
} else if (typeof headers.get === 'function') {
return headers.get(key)
} else {
return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
}
}
/** @param {string[]} headers */
function buildHeadersFromArray (headers) { // fetch HeadersList
const clone = headers.slice()
const entries = []
for (let index = 0; index < clone.length; index += 2) {
entries.push([clone[index], clone[index + 1]])
}
return Object.fromEntries(entries)
}
function matchHeaders (mockDispatch, headers) {
if (typeof mockDispatch.headers === 'function') {
if (Array.isArray(headers)) { // fetch HeadersList
headers = buildHeadersFromArray(headers)
}
return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
}
if (typeof mockDispatch.headers === 'undefined') {
return true
}
if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
return false
}
for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
const headerValue = getHeaderByName(headers, matchHeaderName)
if (!matchValue(matchHeaderValue, headerValue)) {
return false
}
}
return true
}
function safeUrl (path) {
if (typeof path !== 'string') {
return path
}
const pathSegments = path.split('?')
if (pathSegments.length !== 2) {
return path
}
const qp = new URLSearchParams(pathSegments.pop())
qp.sort()
return [...pathSegments, qp.toString()].join('?')
}
function matchKey (mockDispatch, { path, method, body, headers }) {
const pathMatch = matchValue(mockDispatch.path, path)
const methodMatch = matchValue(mockDispatch.method, method)
const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
const headersMatch = matchHeaders(mockDispatch, headers)
return pathMatch && methodMatch && bodyMatch && headersMatch
}
function getResponseData (data) {
if (Buffer.isBuffer(data)) {
return data
} else if (typeof data === 'object') {
return JSON.stringify(data)
} else {
return data.toString()
}
}
function getMockDispatch (mockDispatches, key) {
const basePath = key.query ? buildURL(key.path, key.query) : key.path
const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
// Match path
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
}
// Match method
matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
}
// Match body
matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
}
// Match headers
matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
}
return matchedMockDispatches[0]
}
function addMockDispatch (mockDispatches, key, data) {
const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
const replyData = typeof data === 'function' ? { callback: data } : { ...data }
const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
mockDispatches.push(newMockDispatch)
return newMockDispatch
}
function deleteMockDispatch (mockDispatches, key) {
const index = mockDispatches.findIndex(dispatch => {
if (!dispatch.consumed) {
return false
}
return matchKey(dispatch, key)
})
if (index !== -1) {
mockDispatches.splice(index, 1)
}
}
function buildKey (opts) {
const { path, method, body, headers, query } = opts
return {
path,
method,
body,
headers,
query
}
}
function generateKeyValues (data) {
return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
...keyValuePairs,
Buffer.from(`${key}`),
Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
], [])
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
* @param {number} statusCode
*/
function getStatusText (statusCode) {
return STATUS_CODES[statusCode] || 'unknown'
}
async function getResponse (body) {
const buffers = []
for await (const data of body) {
buffers.push(data)
}
return Buffer.concat(buffers).toString('utf8')
}
/**
* Mock dispatch function used to simulate undici dispatches
*/
function mockDispatch (opts, handler) {
// Get mock dispatch from built key
const key = buildKey(opts)
const mockDispatch = getMockDispatch(this[kDispatches], key)
mockDispatch.timesInvoked++
// Here's where we resolve a callback if a callback is present for the dispatch data.
if (mockDispatch.data.callback) {
mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
}
// Parse mockDispatch data
const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
const { timesInvoked, times } = mockDispatch
// If it's used up and not persistent, mark as consumed
mockDispatch.consumed = !persist && timesInvoked >= times
mockDispatch.pending = timesInvoked < times
// If specified, trigger dispatch error
if (error !== null) {
deleteMockDispatch(this[kDispatches], key)
handler.onError(error)
return true
}
// Handle the request with a delay if necessary
if (typeof delay === 'number' && delay > 0) {
setTimeout(() => {
handleReply(this[kDispatches])
}, delay)
} else {
handleReply(this[kDispatches])
}
function handleReply (mockDispatches, _data = data) {
// fetch's HeadersList is a 1D string array
const optsHeaders = Array.isArray(opts.headers)
? buildHeadersFromArray(opts.headers)
: opts.headers
const body = typeof _data === 'function'
? _data({ ...opts, headers: optsHeaders })
: _data
// util.types.isPromise is likely needed for jest.
if (isPromise(body)) {
// If handleReply is asynchronous, throwing an error
// in the callback will reject the promise, rather than
// synchronously throw the error, which breaks some tests.
// Rather, we wait for the callback to resolve if it is a
// promise, and then re-run handleReply with the new body.
body.then((newData) => handleReply(mockDispatches, newData))
return
}
const responseData = getResponseData(body)
const responseHeaders = generateKeyValues(headers)
const responseTrailers = generateKeyValues(trailers)
handler.abort = nop
handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
handler.onData(Buffer.from(responseData))
handler.onComplete(responseTrailers)
deleteMockDispatch(mockDispatches, key)
}
function resume () {}
return true
}
function buildMockDispatch () {
const agent = this[kMockAgent]
const origin = this[kOrigin]
const originalDispatch = this[kOriginalDispatch]
return function dispatch (opts, handler) {
if (agent.isMockActive) {
try {
mockDispatch.call(this, opts, handler)
} catch (error) {
if (error instanceof MockNotMatchedError) {
const netConnect = agent[kGetNetConnect]()
if (netConnect === false) {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
}
if (checkNetConnect(netConnect, origin)) {
originalDispatch.call(this, opts, handler)
} else {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
}
} else {
throw error
}
}
} else {
originalDispatch.call(this, opts, handler)
}
}
}
function checkNetConnect (netConnect, origin) {
const url = new URL(origin)
if (netConnect === true) {
return true
} else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
return true
}
return false
}
function buildMockOptions (opts) {
if (opts) {
const { agent, ...mockOptions } = opts
return mockOptions
}
}
module.exports = {
getResponseData,
getMockDispatch,
addMockDispatch,
deleteMockDispatch,
buildKey,
generateKeyValues,
matchValue,
getResponse,
getStatusText,
mockDispatch,
buildMockDispatch,
checkNetConnect,
buildMockOptions,
getHeaderByName
}
/***/ }),
/***/ 86823:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { Transform } = __nccwpck_require__(12781)
const { Console } = __nccwpck_require__(96206)
/**
* Gets the output of `console.table(…)` as a string.
*/
module.exports = class PendingInterceptorsFormatter {
constructor ({ disableColors } = {}) {
this.transform = new Transform({
transform (chunk, _enc, cb) {
cb(null, chunk)
}
})
this.logger = new Console({
stdout: this.transform,
inspectOptions: {
colors: !disableColors && !process.env.CI
}
})
}
format (pendingInterceptors) {
const withPrettyHeaders = pendingInterceptors.map(
({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
Method: method,
Origin: origin,
Path: path,
'Status code': statusCode,
Persistent: persist ? '✅' : '❌',
Invocations: timesInvoked,
Remaining: persist ? Infinity : times - timesInvoked
}))
this.logger.table(withPrettyHeaders)
return this.transform.read().toString()
}
}
/***/ }),
/***/ 78891:
/***/ ((module) => {
"use strict";
const singulars = {
pronoun: 'it',
is: 'is',
was: 'was',
this: 'this'
}
const plurals = {
pronoun: 'they',
is: 'are',
was: 'were',
this: 'these'
}
module.exports = class Pluralizer {
constructor (singular, plural) {
this.singular = singular
this.plural = plural
}
pluralize (count) {
const one = count === 1
const keys = one ? singulars : plurals
const noun = one ? this.singular : this.plural
return { ...keys, count, noun }
}
}
/***/ }),
/***/ 68266:
/***/ ((module) => {
"use strict";
/* eslint-disable */
// Extracted from node/lib/internal/fixed_queue.js
// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
const kSize = 2048;
const kMask = kSize - 1;
// The FixedQueue is implemented as a singly-linked list of fixed-size
// circular buffers. It looks something like this:
//
// head tail
// | |
// v v
// +-----------+ <-----\ +-----------+ <------\ +-----------+
// | [null] | \----- | next | \------- | next |
// +-----------+ +-----------+ +-----------+
// | item | <-- bottom | item | <-- bottom | [empty] |
// | item | | item | | [empty] |
// | item | | item | | [empty] |
// | item | | item | | [empty] |
// | item | | item | bottom --> | item |
// | item | | item | | item |
// | ... | | ... | | ... |
// | item | | item | | item |
// | item | | item | | item |
// | [empty] | <-- top | item | | item |
// | [empty] | | item | | item |
// | [empty] | | [empty] | <-- top top --> | [empty] |
// +-----------+ +-----------+ +-----------+
//
// Or, if there is only one circular buffer, it looks something
// like either of these:
//
// head tail head tail
// | | | |
// v v v v
// +-----------+ +-----------+
// | [null] | | [null] |
// +-----------+ +-----------+
// | [empty] | | item |
// | [empty] | | item |
// | item | <-- bottom top --> | [empty] |
// | item | | [empty] |
// | [empty] | <-- top bottom --> | item |
// | [empty] | | item |
// +-----------+ +-----------+
//
// Adding a value means moving `top` forward by one, removing means
// moving `bottom` forward by one. After reaching the end, the queue
// wraps around.
//
// When `top === bottom` the current queue is empty and when
// `top + 1 === bottom` it's full. This wastes a single space of storage
// but allows much quicker checks.
class FixedCircularBuffer {
constructor() {
this.bottom = 0;
this.top = 0;
this.list = new Array(kSize);
this.next = null;
}
isEmpty() {
return this.top === this.bottom;
}
isFull() {
return ((this.top + 1) & kMask) === this.bottom;
}
push(data) {
this.list[this.top] = data;
this.top = (this.top + 1) & kMask;
}
shift() {
const nextItem = this.list[this.bottom];
if (nextItem === undefined)
return null;
this.list[this.bottom] = undefined;
this.bottom = (this.bottom + 1) & kMask;
return nextItem;
}
}
module.exports = class FixedQueue {
constructor() {
this.head = this.tail = new FixedCircularBuffer();
}
isEmpty() {
return this.head.isEmpty();
}
push(data) {
if (this.head.isFull()) {
// Head is full: Creates a new queue, sets the old queue's `.next` to it,
// and sets it as the new main queue.
this.head = this.head.next = new FixedCircularBuffer();
}
this.head.push(data);
}
shift() {
const tail = this.tail;
const next = tail.shift();
if (tail.isEmpty() && tail.next !== null) {
// If there is another queue, it forms the new tail.
this.tail = tail.next;
}
return next;
}
};
/***/ }),
/***/ 73198:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const DispatcherBase = __nccwpck_require__(74839)
const FixedQueue = __nccwpck_require__(68266)
const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(72785)
const PoolStats = __nccwpck_require__(39689)
const kClients = Symbol('clients')
const kNeedDrain = Symbol('needDrain')
const kQueue = Symbol('queue')
const kClosedResolve = Symbol('closed resolve')
const kOnDrain = Symbol('onDrain')
const kOnConnect = Symbol('onConnect')
const kOnDisconnect = Symbol('onDisconnect')
const kOnConnectionError = Symbol('onConnectionError')
const kGetDispatcher = Symbol('get dispatcher')
const kAddClient = Symbol('add client')
const kRemoveClient = Symbol('remove client')
const kStats = Symbol('stats')
class PoolBase extends DispatcherBase {
constructor () {
super()
this[kQueue] = new FixedQueue()
this[kClients] = []
this[kQueued] = 0
const pool = this
this[kOnDrain] = function onDrain (origin, targets) {
const queue = pool[kQueue]
let needDrain = false
while (!needDrain) {
const item = queue.shift()
if (!item) {
break
}
pool[kQueued]--
needDrain = !this.dispatch(item.opts, item.handler)
}
this[kNeedDrain] = needDrain
if (!this[kNeedDrain] && pool[kNeedDrain]) {
pool[kNeedDrain] = false
pool.emit('drain', origin, [pool, ...targets])
}
if (pool[kClosedResolve] && queue.isEmpty()) {
Promise
.all(pool[kClients].map(c => c.close()))
.then(pool[kClosedResolve])
}
}
this[kOnConnect] = (origin, targets) => {
pool.emit('connect', origin, [pool, ...targets])
}
this[kOnDisconnect] = (origin, targets, err) => {
pool.emit('disconnect', origin, [pool, ...targets], err)
}
this[kOnConnectionError] = (origin, targets, err) => {
pool.emit('connectionError', origin, [pool, ...targets], err)
}
this[kStats] = new PoolStats(this)
}
get [kBusy] () {
return this[kNeedDrain]
}
get [kConnected] () {
return this[kClients].filter(client => client[kConnected]).length
}
get [kFree] () {
return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
}
get [kPending] () {
let ret = this[kQueued]
for (const { [kPending]: pending } of this[kClients]) {
ret += pending
}
return ret
}
get [kRunning] () {
let ret = 0
for (const { [kRunning]: running } of this[kClients]) {
ret += running
}
return ret
}
get [kSize] () {
let ret = this[kQueued]
for (const { [kSize]: size } of this[kClients]) {
ret += size
}
return ret
}
get stats () {
return this[kStats]
}
async [kClose] () {
if (this[kQueue].isEmpty()) {
return Promise.all(this[kClients].map(c => c.close()))
} else {
return new Promise((resolve) => {
this[kClosedResolve] = resolve
})
}
}
async [kDestroy] (err) {
while (true) {
const item = this[kQueue].shift()
if (!item) {
break
}
item.handler.onError(err)
}
return Promise.all(this[kClients].map(c => c.destroy(err)))
}
[kDispatch] (opts, handler) {
const dispatcher = this[kGetDispatcher]()
if (!dispatcher) {
this[kNeedDrain] = true
this[kQueue].push({ opts, handler })
this[kQueued]++
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain] = true
this[kNeedDrain] = !this[kGetDispatcher]()
}
return !this[kNeedDrain]
}
[kAddClient] (client) {
client
.on('drain', this[kOnDrain])
.on('connect', this[kOnConnect])
.on('disconnect', this[kOnDisconnect])
.on('connectionError', this[kOnConnectionError])
this[kClients].push(client)
if (this[kNeedDrain]) {
process.nextTick(() => {
if (this[kNeedDrain]) {
this[kOnDrain](client[kUrl], [this, client])
}
})
}
return this
}
[kRemoveClient] (client) {
client.close(() => {
const idx = this[kClients].indexOf(client)
if (idx !== -1) {
this[kClients].splice(idx, 1)
}
})
this[kNeedDrain] = this[kClients].some(dispatcher => (
!dispatcher[kNeedDrain] &&
dispatcher.closed !== true &&
dispatcher.destroyed !== true
))
}
}
module.exports = {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
}
/***/ }),
/***/ 39689:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(72785)
const kPool = Symbol('pool')
class PoolStats {
constructor (pool) {
this[kPool] = pool
}
get connected () {
return this[kPool][kConnected]
}
get free () {
return this[kPool][kFree]
}
get pending () {
return this[kPool][kPending]
}
get queued () {
return this[kPool][kQueued]
}
get running () {
return this[kPool][kRunning]
}
get size () {
return this[kPool][kSize]
}
}
module.exports = PoolStats
/***/ }),
/***/ 4634:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kGetDispatcher
} = __nccwpck_require__(73198)
const Client = __nccwpck_require__(33598)
const {
InvalidArgumentError
} = __nccwpck_require__(48045)
const util = __nccwpck_require__(83983)
const { kUrl, kInterceptors } = __nccwpck_require__(72785)
const buildConnector = __nccwpck_require__(82067)
const kOptions = Symbol('options')
const kConnections = Symbol('connections')
const kFactory = Symbol('factory')
function defaultFactory (origin, opts) {
return new Client(origin, opts)
}
class Pool extends PoolBase {
constructor (origin, {
connections,
factory = defaultFactory,
connect,
connectTimeout,
tls,
maxCachedSessions,
socketPath,
autoSelectFamily,
autoSelectFamilyAttemptTimeout,
allowH2,
...options
} = {}) {
super()
if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
throw new InvalidArgumentError('invalid connections')
}
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}
if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
throw new InvalidArgumentError('connect must be a function or an object')
}
if (typeof connect !== 'function') {
connect = buildConnector({
...tls,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
...connect
})
}
this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
? options.interceptors.Pool
: []
this[kConnections] = connections || null
this[kUrl] = util.parseOrigin(origin)
this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
this[kOptions].interceptors = options.interceptors
? { ...options.interceptors }
: undefined
this[kFactory] = factory
}
[kGetDispatcher] () {
let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
if (dispatcher) {
return dispatcher
}
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
dispatcher = this[kFactory](this[kUrl], this[kOptions])
this[kAddClient](dispatcher)
}
return dispatcher
}
}
module.exports = Pool
/***/ }),
/***/ 97858:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(72785)
const { URL } = __nccwpck_require__(57310)
const Agent = __nccwpck_require__(7890)
const Pool = __nccwpck_require__(4634)
const DispatcherBase = __nccwpck_require__(74839)
const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(48045)
const buildConnector = __nccwpck_require__(82067)
const kAgent = Symbol('proxy agent')
const kClient = Symbol('proxy client')
const kProxyHeaders = Symbol('proxy headers')
const kRequestTls = Symbol('request tls settings')
const kProxyTls = Symbol('proxy tls settings')
const kConnectEndpoint = Symbol('connect endpoint function')
function defaultProtocolPort (protocol) {
return protocol === 'https:' ? 443 : 80
}
function buildProxyOptions (opts) {
if (typeof opts === 'string') {
opts = { uri: opts }
}
if (!opts || !opts.uri) {
throw new InvalidArgumentError('Proxy opts.uri is mandatory')
}
return {
uri: opts.uri,
protocol: opts.protocol || 'https'
}
}
function defaultFactory (origin, opts) {
return new Pool(origin, opts)
}
class ProxyAgent extends DispatcherBase {
constructor (opts) {
super(opts)
this[kProxy] = buildProxyOptions(opts)
this[kAgent] = new Agent(opts)
this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
? opts.interceptors.ProxyAgent
: []
if (typeof opts === 'string') {
opts = { uri: opts }
}
if (!opts || !opts.uri) {
throw new InvalidArgumentError('Proxy opts.uri is mandatory')
}
const { clientFactory = defaultFactory } = opts
if (typeof clientFactory !== 'function') {
throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
}
this[kRequestTls] = opts.requestTls
this[kProxyTls] = opts.proxyTls
this[kProxyHeaders] = opts.headers || {}
const resolvedUrl = new URL(opts.uri)
const { origin, port, host, username, password } = resolvedUrl
if (opts.auth && opts.token) {
throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
} else if (opts.auth) {
/* @deprecated in favour of opts.token */
this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
} else if (opts.token) {
this[kProxyHeaders]['proxy-authorization'] = opts.token
} else if (username && password) {
this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
}
const connect = buildConnector({ ...opts.proxyTls })
this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
this[kClient] = clientFactory(resolvedUrl, { connect })
this[kAgent] = new Agent({
...opts,
connect: async (opts, callback) => {
let requestedHost = opts.host
if (!opts.port) {
requestedHost += `:${defaultProtocolPort(opts.protocol)}`
}
try {
const { socket, statusCode } = await this[kClient].connect({
origin,
port,
path: requestedHost,
signal: opts.signal,
headers: {
...this[kProxyHeaders],
host
}
})
if (statusCode !== 200) {
socket.on('error', () => {}).destroy()
callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
}
if (opts.protocol !== 'https:') {
callback(null, socket)
return
}
let servername
if (this[kRequestTls]) {
servername = this[kRequestTls].servername
} else {
servername = opts.servername
}
this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
} catch (err) {
callback(err)
}
}
})
}
dispatch (opts, handler) {
const { host } = new URL(opts.origin)
const headers = buildHeaders(opts.headers)
throwIfProxyAuthIsSent(headers)
return this[kAgent].dispatch(
{
...opts,
headers: {
...headers,
host
}
},
handler
)
}
async [kClose] () {
await this[kAgent].close()
await this[kClient].close()
}
async [kDestroy] () {
await this[kAgent].destroy()
await this[kClient].destroy()
}
}
/**
* @param {string[] | Record<string, string>} headers
* @returns {Record<string, string>}
*/
function buildHeaders (headers) {
// When using undici.fetch, the headers list is stored
// as an array.
if (Array.isArray(headers)) {
/** @type {Record<string, string>} */
const headersPair = {}
for (let i = 0; i < headers.length; i += 2) {
headersPair[headers[i]] = headers[i + 1]
}
return headersPair
}
return headers
}
/**
* @param {Record<string, string>} headers
*
* Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
* Nevertheless, it was changed and to avoid a security vulnerability by end users
* this check was created.
* It should be removed in the next major version for performance reasons
*/
function throwIfProxyAuthIsSent (headers) {
const existProxyAuth = headers && Object.keys(headers)
.find((key) => key.toLowerCase() === 'proxy-authorization')
if (existProxyAuth) {
throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
}
}
module.exports = ProxyAgent
/***/ }),
/***/ 29459:
/***/ ((module) => {
"use strict";
let fastNow = Date.now()
let fastNowTimeout
const fastTimers = []
function onTimeout () {
fastNow = Date.now()
let len = fastTimers.length
let idx = 0
while (idx < len) {
const timer = fastTimers[idx]
if (timer.state === 0) {
timer.state = fastNow + timer.delay
} else if (timer.state > 0 && fastNow >= timer.state) {
timer.state = -1
timer.callback(timer.opaque)
}
if (timer.state === -1) {
timer.state = -2
if (idx !== len - 1) {
fastTimers[idx] = fastTimers.pop()
} else {
fastTimers.pop()
}
len -= 1
} else {
idx += 1
}
}
if (fastTimers.length > 0) {
refreshTimeout()
}
}
function refreshTimeout () {
if (fastNowTimeout && fastNowTimeout.refresh) {
fastNowTimeout.refresh()
} else {
clearTimeout(fastNowTimeout)
fastNowTimeout = setTimeout(onTimeout, 1e3)
if (fastNowTimeout.unref) {
fastNowTimeout.unref()
}
}
}
class Timeout {
constructor (callback, delay, opaque) {
this.callback = callback
this.delay = delay
this.opaque = opaque
// -2 not in timer list
// -1 in timer list but inactive
// 0 in timer list waiting for time
// > 0 in timer list waiting for time to expire
this.state = -2
this.refresh()
}
refresh () {
if (this.state === -2) {
fastTimers.push(this)
if (!fastNowTimeout || fastTimers.length === 1) {
refreshTimeout()
}
}
this.state = 0
}
clear () {
this.state = -1
}
}
module.exports = {
setTimeout (callback, delay, opaque) {
return delay < 1e3
? setTimeout(callback, delay, opaque)
: new Timeout(callback, delay, opaque)
},
clearTimeout (timeout) {
if (timeout instanceof Timeout) {
timeout.clear()
} else {
clearTimeout(timeout)
}
}
}
/***/ }),
/***/ 35354:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const diagnosticsChannel = __nccwpck_require__(67643)
const { uid, states } = __nccwpck_require__(19188)
const {
kReadyState,
kSentClose,
kByteParser,
kReceivedClose
} = __nccwpck_require__(37578)
const { fireEvent, failWebsocketConnection } = __nccwpck_require__(25515)
const { CloseEvent } = __nccwpck_require__(52611)
const { makeRequest } = __nccwpck_require__(48359)
const { fetching } = __nccwpck_require__(74881)
const { Headers } = __nccwpck_require__(10554)
const { getGlobalDispatcher } = __nccwpck_require__(21892)
const { kHeadersList } = __nccwpck_require__(72785)
const channels = {}
channels.open = diagnosticsChannel.channel('undici:websocket:open')
channels.close = diagnosticsChannel.channel('undici:websocket:close')
channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
/** @type {import('crypto')} */
let crypto
try {
crypto = __nccwpck_require__(6113)
} catch {
}
/**
* @see https://websockets.spec.whatwg.org/#concept-websocket-establish
* @param {URL} url
* @param {string|string[]} protocols
* @param {import('./websocket').WebSocket} ws
* @param {(response: any) => void} onEstablish
* @param {Partial<import('../../types/websocket').WebSocketInit>} options
*/
function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
// 1. Let requestURL be a copy of url, with its scheme set to "http", if urls
// scheme is "ws", and to "https" otherwise.
const requestURL = url
requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
// 2. Let request be a new request, whose URL is requestURL, client is client,
// service-workers mode is "none", referrer is "no-referrer", mode is
// "websocket", credentials mode is "include", cache mode is "no-store" ,
// and redirect mode is "error".
const request = makeRequest({
urlList: [requestURL],
serviceWorkers: 'none',
referrer: 'no-referrer',
mode: 'websocket',
credentials: 'include',
cache: 'no-store',
redirect: 'error'
})
// Note: undici extension, allow setting custom headers.
if (options.headers) {
const headersList = new Headers(options.headers)[kHeadersList]
request.headersList = headersList
}
// 3. Append (`Upgrade`, `websocket`) to requests header list.
// 4. Append (`Connection`, `Upgrade`) to requests header list.
// Note: both of these are handled by undici currently.
// https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
// 5. Let keyValue be a nonce consisting of a randomly selected
// 16-byte value that has been forgiving-base64-encoded and
// isomorphic encoded.
const keyValue = crypto.randomBytes(16).toString('base64')
// 6. Append (`Sec-WebSocket-Key`, keyValue) to requests
// header list.
request.headersList.append('sec-websocket-key', keyValue)
// 7. Append (`Sec-WebSocket-Version`, `13`) to requests
// header list.
request.headersList.append('sec-websocket-version', '13')
// 8. For each protocol in protocols, combine
// (`Sec-WebSocket-Protocol`, protocol) in requests header
// list.
for (const protocol of protocols) {
request.headersList.append('sec-websocket-protocol', protocol)
}
// 9. Let permessageDeflate be a user-agent defined
// "permessage-deflate" extension header value.
// https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
// TODO: enable once permessage-deflate is supported
const permessageDeflate = '' // 'permessage-deflate; 15'
// 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
// requests header list.
// request.headersList.append('sec-websocket-extensions', permessageDeflate)
// 11. Fetch request with useParallelQueue set to true, and
// processResponse given response being these steps:
const controller = fetching({
request,
useParallelQueue: true,
dispatcher: options.dispatcher ?? getGlobalDispatcher(),
processResponse (response) {
// 1. If response is a network error or its status is not 101,
// fail the WebSocket connection.
if (response.type === 'error' || response.status !== 101) {
failWebsocketConnection(ws, 'Received network error or non-101 status code.')
return
}
// 2. If protocols is not the empty list and extracting header
// list values given `Sec-WebSocket-Protocol` and responses
// header list results in null, failure, or the empty byte
// sequence, then fail the WebSocket connection.
if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
return
}
// 3. Follow the requirements stated step 2 to step 6, inclusive,
// of the last set of steps in section 4.1 of The WebSocket
// Protocol to validate response. This either results in fail
// the WebSocket connection or the WebSocket connection is
// established.
// 2. If the response lacks an |Upgrade| header field or the |Upgrade|
// header field contains a value that is not an ASCII case-
// insensitive match for the value "websocket", the client MUST
// _Fail the WebSocket Connection_.
if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
return
}
// 3. If the response lacks a |Connection| header field or the
// |Connection| header field doesn't contain a token that is an
// ASCII case-insensitive match for the value "Upgrade", the client
// MUST _Fail the WebSocket Connection_.
if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
return
}
// 4. If the response lacks a |Sec-WebSocket-Accept| header field or
// the |Sec-WebSocket-Accept| contains a value other than the
// base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
// Key| (as a string, not base64-decoded) with the string "258EAFA5-
// E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
// trailing whitespace, the client MUST _Fail the WebSocket
// Connection_.
const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
if (secWSAccept !== digest) {
failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
return
}
// 5. If the response includes a |Sec-WebSocket-Extensions| header
// field and this header field indicates the use of an extension
// that was not present in the client's handshake (the server has
// indicated an extension not requested by the client), the client
// MUST _Fail the WebSocket Connection_. (The parsing of this
// header field to determine which extensions are requested is
// discussed in Section 9.1.)
const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
if (secExtension !== null && secExtension !== permessageDeflate) {
failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
return
}
// 6. If the response includes a |Sec-WebSocket-Protocol| header field
// and this header field indicates the use of a subprotocol that was
// not present in the client's handshake (the server has indicated a
// subprotocol not requested by the client), the client MUST _Fail
// the WebSocket Connection_.
const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
return
}
response.socket.on('data', onSocketData)
response.socket.on('close', onSocketClose)
response.socket.on('error', onSocketError)
if (channels.open.hasSubscribers) {
channels.open.publish({
address: response.socket.address(),
protocol: secProtocol,
extensions: secExtension
})
}
onEstablish(response)
}
})
return controller
}
/**
* @param {Buffer} chunk
*/
function onSocketData (chunk) {
if (!this.ws[kByteParser].write(chunk)) {
this.pause()
}
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
*/
function onSocketClose () {
const { ws } = this
// If the TCP connection was closed after the
// WebSocket closing handshake was completed, the WebSocket connection
// is said to have been closed _cleanly_.
const wasClean = ws[kSentClose] && ws[kReceivedClose]
let code = 1005
let reason = ''
const result = ws[kByteParser].closingInfo
if (result) {
code = result.code ?? 1005
reason = result.reason
} else if (!ws[kSentClose]) {
// If _The WebSocket
// Connection is Closed_ and no Close control frame was received by the
// endpoint (such as could occur if the underlying transport connection
// is lost), _The WebSocket Connection Close Code_ is considered to be
// 1006.
code = 1006
}
// 1. Change the ready state to CLOSED (3).
ws[kReadyState] = states.CLOSED
// 2. If the user agent was required to fail the WebSocket
// connection, or if the WebSocket connection was closed
// after being flagged as full, fire an event named error
// at the WebSocket object.
// TODO
// 3. Fire an event named close at the WebSocket object,
// using CloseEvent, with the wasClean attribute
// initialized to true if the connection closed cleanly
// and false otherwise, the code attribute initialized to
// the WebSocket connection close code, and the reason
// attribute initialized to the result of applying UTF-8
// decode without BOM to the WebSocket connection close
// reason.
fireEvent('close', ws, CloseEvent, {
wasClean, code, reason
})
if (channels.close.hasSubscribers) {
channels.close.publish({
websocket: ws,
code,
reason
})
}
}
function onSocketError (error) {
const { ws } = this
ws[kReadyState] = states.CLOSING
if (channels.socketError.hasSubscribers) {
channels.socketError.publish(error)
}
this.destroy()
}
module.exports = {
establishWebSocketConnection
}
/***/ }),
/***/ 19188:
/***/ ((module) => {
"use strict";
// This is a Globally Unique Identifier unique used
// to validate that the endpoint accepts websocket
// connections.
// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
/** @type {PropertyDescriptor} */
const staticPropertyDescriptors = {
enumerable: true,
writable: false,
configurable: false
}
const states = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
}
const opcodes = {
CONTINUATION: 0x0,
TEXT: 0x1,
BINARY: 0x2,
CLOSE: 0x8,
PING: 0x9,
PONG: 0xA
}
const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
const parserStates = {
INFO: 0,
PAYLOADLENGTH_16: 2,
PAYLOADLENGTH_64: 3,
READ_DATA: 4
}
const emptyBuffer = Buffer.allocUnsafe(0)
module.exports = {
uid,
staticPropertyDescriptors,
states,
opcodes,
maxUnsigned16Bit,
parserStates,
emptyBuffer
}
/***/ }),
/***/ 52611:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { webidl } = __nccwpck_require__(21744)
const { kEnumerableProperty } = __nccwpck_require__(83983)
const { MessagePort } = __nccwpck_require__(71267)
/**
* @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
*/
class MessageEvent extends Event {
#eventInit
constructor (type, eventInitDict = {}) {
webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
type = webidl.converters.DOMString(type)
eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
super(type, eventInitDict)
this.#eventInit = eventInitDict
}
get data () {
webidl.brandCheck(this, MessageEvent)
return this.#eventInit.data
}
get origin () {
webidl.brandCheck(this, MessageEvent)
return this.#eventInit.origin
}
get lastEventId () {
webidl.brandCheck(this, MessageEvent)
return this.#eventInit.lastEventId
}
get source () {
webidl.brandCheck(this, MessageEvent)
return this.#eventInit.source
}
get ports () {
webidl.brandCheck(this, MessageEvent)
if (!Object.isFrozen(this.#eventInit.ports)) {
Object.freeze(this.#eventInit.ports)
}
return this.#eventInit.ports
}
initMessageEvent (
type,
bubbles = false,
cancelable = false,
data = null,
origin = '',
lastEventId = '',
source = null,
ports = []
) {
webidl.brandCheck(this, MessageEvent)
webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
return new MessageEvent(type, {
bubbles, cancelable, data, origin, lastEventId, source, ports
})
}
}
/**
* @see https://websockets.spec.whatwg.org/#the-closeevent-interface
*/
class CloseEvent extends Event {
#eventInit
constructor (type, eventInitDict = {}) {
webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
type = webidl.converters.DOMString(type)
eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
super(type, eventInitDict)
this.#eventInit = eventInitDict
}
get wasClean () {
webidl.brandCheck(this, CloseEvent)
return this.#eventInit.wasClean
}
get code () {
webidl.brandCheck(this, CloseEvent)
return this.#eventInit.code
}
get reason () {
webidl.brandCheck(this, CloseEvent)
return this.#eventInit.reason
}
}
// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
class ErrorEvent extends Event {
#eventInit
constructor (type, eventInitDict) {
webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
super(type, eventInitDict)
type = webidl.converters.DOMString(type)
eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
this.#eventInit = eventInitDict
}
get message () {
webidl.brandCheck(this, ErrorEvent)
return this.#eventInit.message
}
get filename () {
webidl.brandCheck(this, ErrorEvent)
return this.#eventInit.filename
}
get lineno () {
webidl.brandCheck(this, ErrorEvent)
return this.#eventInit.lineno
}
get colno () {
webidl.brandCheck(this, ErrorEvent)
return this.#eventInit.colno
}
get error () {
webidl.brandCheck(this, ErrorEvent)
return this.#eventInit.error
}
}
Object.defineProperties(MessageEvent.prototype, {
[Symbol.toStringTag]: {
value: 'MessageEvent',
configurable: true
},
data: kEnumerableProperty,
origin: kEnumerableProperty,
lastEventId: kEnumerableProperty,
source: kEnumerableProperty,
ports: kEnumerableProperty,
initMessageEvent: kEnumerableProperty
})
Object.defineProperties(CloseEvent.prototype, {
[Symbol.toStringTag]: {
value: 'CloseEvent',
configurable: true
},
reason: kEnumerableProperty,
code: kEnumerableProperty,
wasClean: kEnumerableProperty
})
Object.defineProperties(ErrorEvent.prototype, {
[Symbol.toStringTag]: {
value: 'ErrorEvent',
configurable: true
},
message: kEnumerableProperty,
filename: kEnumerableProperty,
lineno: kEnumerableProperty,
colno: kEnumerableProperty,
error: kEnumerableProperty
})
webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
webidl.converters['sequence<MessagePort>'] = webidl.sequenceConverter(
webidl.converters.MessagePort
)
const eventInit = [
{
key: 'bubbles',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'cancelable',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'composed',
converter: webidl.converters.boolean,
defaultValue: false
}
]
webidl.converters.MessageEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: 'data',
converter: webidl.converters.any,
defaultValue: null
},
{
key: 'origin',
converter: webidl.converters.USVString,
defaultValue: ''
},
{
key: 'lastEventId',
converter: webidl.converters.DOMString,
defaultValue: ''
},
{
key: 'source',
// Node doesn't implement WindowProxy or ServiceWorker, so the only
// valid value for source is a MessagePort.
converter: webidl.nullableConverter(webidl.converters.MessagePort),
defaultValue: null
},
{
key: 'ports',
converter: webidl.converters['sequence<MessagePort>'],
get defaultValue () {
return []
}
}
])
webidl.converters.CloseEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: 'wasClean',
converter: webidl.converters.boolean,
defaultValue: false
},
{
key: 'code',
converter: webidl.converters['unsigned short'],
defaultValue: 0
},
{
key: 'reason',
converter: webidl.converters.USVString,
defaultValue: ''
}
])
webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: 'message',
converter: webidl.converters.DOMString,
defaultValue: ''
},
{
key: 'filename',
converter: webidl.converters.USVString,
defaultValue: ''
},
{
key: 'lineno',
converter: webidl.converters['unsigned long'],
defaultValue: 0
},
{
key: 'colno',
converter: webidl.converters['unsigned long'],
defaultValue: 0
},
{
key: 'error',
converter: webidl.converters.any
}
])
module.exports = {
MessageEvent,
CloseEvent,
ErrorEvent
}
/***/ }),
/***/ 25444:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { maxUnsigned16Bit } = __nccwpck_require__(19188)
/** @type {import('crypto')} */
let crypto
try {
crypto = __nccwpck_require__(6113)
} catch {
}
class WebsocketFrameSend {
/**
* @param {Buffer|undefined} data
*/
constructor (data) {
this.frameData = data
this.maskKey = crypto.randomBytes(4)
}
createFrame (opcode) {
const bodyLength = this.frameData?.byteLength ?? 0
/** @type {number} */
let payloadLength = bodyLength // 0-125
let offset = 6
if (bodyLength > maxUnsigned16Bit) {
offset += 8 // payload length is next 8 bytes
payloadLength = 127
} else if (bodyLength > 125) {
offset += 2 // payload length is next 2 bytes
payloadLength = 126
}
const buffer = Buffer.allocUnsafe(bodyLength + offset)
// Clear first 2 bytes, everything else is overwritten
buffer[0] = buffer[1] = 0
buffer[0] |= 0x80 // FIN
buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */
buffer[offset - 4] = this.maskKey[0]
buffer[offset - 3] = this.maskKey[1]
buffer[offset - 2] = this.maskKey[2]
buffer[offset - 1] = this.maskKey[3]
buffer[1] = payloadLength
if (payloadLength === 126) {
buffer.writeUInt16BE(bodyLength, 2)
} else if (payloadLength === 127) {
// Clear extended payload length
buffer[2] = buffer[3] = 0
buffer.writeUIntBE(bodyLength, 4, 6)
}
buffer[1] |= 0x80 // MASK
// mask body
for (let i = 0; i < bodyLength; i++) {
buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
}
return buffer
}
}
module.exports = {
WebsocketFrameSend
}
/***/ }),
/***/ 11688:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { Writable } = __nccwpck_require__(12781)
const diagnosticsChannel = __nccwpck_require__(67643)
const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(19188)
const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(37578)
const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(25515)
const { WebsocketFrameSend } = __nccwpck_require__(25444)
// This code was influenced by ws released under the MIT license.
// Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
// Copyright (c) 2013 Arnout Kazemier and contributors
// Copyright (c) 2016 Luigi Pinca and contributors
const channels = {}
channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
class ByteParser extends Writable {
#buffers = []
#byteOffset = 0
#state = parserStates.INFO
#info = {}
#fragments = []
constructor (ws) {
super()
this.ws = ws
}
/**
* @param {Buffer} chunk
* @param {() => void} callback
*/
_write (chunk, _, callback) {
this.#buffers.push(chunk)
this.#byteOffset += chunk.length
this.run(callback)
}
/**
* Runs whenever a new chunk is received.
* Callback is called whenever there are no more chunks buffering,
* or not enough bytes are buffered to parse.
*/
run (callback) {
while (true) {
if (this.#state === parserStates.INFO) {
// If there aren't enough bytes to parse the payload length, etc.
if (this.#byteOffset < 2) {
return callback()
}
const buffer = this.consume(2)
this.#info.fin = (buffer[0] & 0x80) !== 0
this.#info.opcode = buffer[0] & 0x0F
// If we receive a fragmented message, we use the type of the first
// frame to parse the full message as binary/text, when it's terminated
this.#info.originalOpcode ??= this.#info.opcode
this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
// Only text and binary frames can be fragmented
failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
return
}
const payloadLength = buffer[1] & 0x7F
if (payloadLength <= 125) {
this.#info.payloadLength = payloadLength
this.#state = parserStates.READ_DATA
} else if (payloadLength === 126) {
this.#state = parserStates.PAYLOADLENGTH_16
} else if (payloadLength === 127) {
this.#state = parserStates.PAYLOADLENGTH_64
}
if (this.#info.fragmented && payloadLength > 125) {
// A fragmented frame can't be fragmented itself
failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
return
} else if (
(this.#info.opcode === opcodes.PING ||
this.#info.opcode === opcodes.PONG ||
this.#info.opcode === opcodes.CLOSE) &&
payloadLength > 125
) {
// Control frames can have a payload length of 125 bytes MAX
failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
return
} else if (this.#info.opcode === opcodes.CLOSE) {
if (payloadLength === 1) {
failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
return
}
const body = this.consume(payloadLength)
this.#info.closeInfo = this.parseCloseBody(false, body)
if (!this.ws[kSentClose]) {
// If an endpoint receives a Close frame and did not previously send a
// Close frame, the endpoint MUST send a Close frame in response. (When
// sending a Close frame in response, the endpoint typically echos the
// status code it received.)
const body = Buffer.allocUnsafe(2)
body.writeUInt16BE(this.#info.closeInfo.code, 0)
const closeFrame = new WebsocketFrameSend(body)
this.ws[kResponse].socket.write(
closeFrame.createFrame(opcodes.CLOSE),
(err) => {
if (!err) {
this.ws[kSentClose] = true
}
}
)
}
// Upon either sending or receiving a Close control frame, it is said
// that _The WebSocket Closing Handshake is Started_ and that the
// WebSocket connection is in the CLOSING state.
this.ws[kReadyState] = states.CLOSING
this.ws[kReceivedClose] = true
this.end()
return
} else if (this.#info.opcode === opcodes.PING) {
// Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
// response, unless it already received a Close frame.
// A Pong frame sent in response to a Ping frame must have identical
// "Application data"
const body = this.consume(payloadLength)
if (!this.ws[kReceivedClose]) {
const frame = new WebsocketFrameSend(body)
this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
if (channels.ping.hasSubscribers) {
channels.ping.publish({
payload: body
})
}
}
this.#state = parserStates.INFO
if (this.#byteOffset > 0) {
continue
} else {
callback()
return
}
} else if (this.#info.opcode === opcodes.PONG) {
// A Pong frame MAY be sent unsolicited. This serves as a
// unidirectional heartbeat. A response to an unsolicited Pong frame is
// not expected.
const body = this.consume(payloadLength)
if (channels.pong.hasSubscribers) {
channels.pong.publish({
payload: body
})
}
if (this.#byteOffset > 0) {
continue
} else {
callback()
return
}
}
} else if (this.#state === parserStates.PAYLOADLENGTH_16) {
if (this.#byteOffset < 2) {
return callback()
}
const buffer = this.consume(2)
this.#info.payloadLength = buffer.readUInt16BE(0)
this.#state = parserStates.READ_DATA
} else if (this.#state === parserStates.PAYLOADLENGTH_64) {
if (this.#byteOffset < 8) {
return callback()
}
const buffer = this.consume(8)
const upper = buffer.readUInt32BE(0)
// 2^31 is the maxinimum bytes an arraybuffer can contain
// on 32-bit systems. Although, on 64-bit systems, this is
// 2^53-1 bytes.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
if (upper > 2 ** 31 - 1) {
failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
return
}
const lower = buffer.readUInt32BE(4)
this.#info.payloadLength = (upper << 8) + lower
this.#state = parserStates.READ_DATA
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) {
// If there is still more data in this chunk that needs to be read
return callback()
} else if (this.#byteOffset >= this.#info.payloadLength) {
// If the server sent multiple frames in a single chunk
const body = this.consume(this.#info.payloadLength)
this.#fragments.push(body)
// If the frame is unfragmented, or a fragmented frame was terminated,
// a message was received
if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
const fullMessage = Buffer.concat(this.#fragments)
websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
this.#info = {}
this.#fragments.length = 0
}
this.#state = parserStates.INFO
}
}
if (this.#byteOffset > 0) {
continue
} else {
callback()
break
}
}
}
/**
* Take n bytes from the buffered Buffers
* @param {number} n
* @returns {Buffer|null}
*/
consume (n) {
if (n > this.#byteOffset) {
return null
} else if (n === 0) {
return emptyBuffer
}
if (this.#buffers[0].length === n) {
this.#byteOffset -= this.#buffers[0].length
return this.#buffers.shift()
}
const buffer = Buffer.allocUnsafe(n)
let offset = 0
while (offset !== n) {
const next = this.#buffers[0]
const { length } = next
if (length + offset === n) {
buffer.set(this.#buffers.shift(), offset)
break
} else if (length + offset > n) {
buffer.set(next.subarray(0, n - offset), offset)
this.#buffers[0] = next.subarray(n - offset)
break
} else {
buffer.set(this.#buffers.shift(), offset)
offset += next.length
}
}
this.#byteOffset -= n
return buffer
}
parseCloseBody (onlyCode, data) {
// https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
/** @type {number|undefined} */
let code
if (data.length >= 2) {
// _The WebSocket Connection Close Code_ is
// defined as the status code (Section 7.4) contained in the first Close
// control frame received by the application
code = data.readUInt16BE(0)
}
if (onlyCode) {
if (!isValidStatusCode(code)) {
return null
}
return { code }
}
// https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
/** @type {Buffer} */
let reason = data.subarray(2)
// Remove BOM
if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
reason = reason.subarray(3)
}
if (code !== undefined && !isValidStatusCode(code)) {
return null
}
try {
// TODO: optimize this
reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
} catch {
return null
}
return { code, reason }
}
get closingInfo () {
return this.#info.closeInfo
}
}
module.exports = {
ByteParser
}
/***/ }),
/***/ 37578:
/***/ ((module) => {
"use strict";
module.exports = {
kWebSocketURL: Symbol('url'),
kReadyState: Symbol('ready state'),
kController: Symbol('controller'),
kResponse: Symbol('response'),
kBinaryType: Symbol('binary type'),
kSentClose: Symbol('sent close'),
kReceivedClose: Symbol('received close'),
kByteParser: Symbol('byte parser')
}
/***/ }),
/***/ 25515:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(37578)
const { states, opcodes } = __nccwpck_require__(19188)
const { MessageEvent, ErrorEvent } = __nccwpck_require__(52611)
/* globals Blob */
/**
* @param {import('./websocket').WebSocket} ws
*/
function isEstablished (ws) {
// If the server's response is validated as provided for above, it is
// said that _The WebSocket Connection is Established_ and that the
// WebSocket Connection is in the OPEN state.
return ws[kReadyState] === states.OPEN
}
/**
* @param {import('./websocket').WebSocket} ws
*/
function isClosing (ws) {
// Upon either sending or receiving a Close control frame, it is said
// that _The WebSocket Closing Handshake is Started_ and that the
// WebSocket connection is in the CLOSING state.
return ws[kReadyState] === states.CLOSING
}
/**
* @param {import('./websocket').WebSocket} ws
*/
function isClosed (ws) {
return ws[kReadyState] === states.CLOSED
}
/**
* @see https://dom.spec.whatwg.org/#concept-event-fire
* @param {string} e
* @param {EventTarget} target
* @param {EventInit | undefined} eventInitDict
*/
function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
// 1. If eventConstructor is not given, then let eventConstructor be Event.
// 2. Let event be the result of creating an event given eventConstructor,
// in the relevant realm of target.
// 3. Initialize events type attribute to e.
const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
// 4. Initialize any other IDL attributes of event as described in the
// invocation of this algorithm.
// 5. Return the result of dispatching event at target, with legacy target
// override flag set if set.
target.dispatchEvent(event)
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
* @param {import('./websocket').WebSocket} ws
* @param {number} type Opcode
* @param {Buffer} data application data
*/
function websocketMessageReceived (ws, type, data) {
// 1. If ready state is not OPEN (1), then return.
if (ws[kReadyState] !== states.OPEN) {
return
}
// 2. Let dataForEvent be determined by switching on type and binary type:
let dataForEvent
if (type === opcodes.TEXT) {
// -> type indicates that the data is Text
// a new DOMString containing data
try {
dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
} catch {
failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
return
}
} else if (type === opcodes.BINARY) {
if (ws[kBinaryType] === 'blob') {
// -> type indicates that the data is Binary and binary type is "blob"
// a new Blob object, created in the relevant Realm of the WebSocket
// object, that represents data as its raw data
dataForEvent = new Blob([data])
} else {
// -> type indicates that the data is Binary and binary type is "arraybuffer"
// a new ArrayBuffer object, created in the relevant Realm of the
// WebSocket object, whose contents are data
dataForEvent = new Uint8Array(data).buffer
}
}
// 3. Fire an event named message at the WebSocket object, using MessageEvent,
// with the origin attribute initialized to the serialization of the WebSocket
// objects url's origin, and the data attribute initialized to dataForEvent.
fireEvent('message', ws, MessageEvent, {
origin: ws[kWebSocketURL].origin,
data: dataForEvent
})
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc6455
* @see https://datatracker.ietf.org/doc/html/rfc2616
* @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
* @param {string} protocol
*/
function isValidSubprotocol (protocol) {
// If present, this value indicates one
// or more comma-separated subprotocol the client wishes to speak,
// ordered by preference. The elements that comprise this value
// MUST be non-empty strings with characters in the range U+0021 to
// U+007E not including separator characters as defined in
// [RFC2616] and MUST all be unique strings.
if (protocol.length === 0) {
return false
}
for (const char of protocol) {
const code = char.charCodeAt(0)
if (
code < 0x21 ||
code > 0x7E ||
char === '(' ||
char === ')' ||
char === '<' ||
char === '>' ||
char === '@' ||
char === ',' ||
char === ';' ||
char === ':' ||
char === '\\' ||
char === '"' ||
char === '/' ||
char === '[' ||
char === ']' ||
char === '?' ||
char === '=' ||
char === '{' ||
char === '}' ||
code === 32 || // SP
code === 9 // HT
) {
return false
}
}
return true
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
* @param {number} code
*/
function isValidStatusCode (code) {
if (code >= 1000 && code < 1015) {
return (
code !== 1004 && // reserved
code !== 1005 && // "MUST NOT be set as a status code"
code !== 1006 // "MUST NOT be set as a status code"
)
}
return code >= 3000 && code <= 4999
}
/**
* @param {import('./websocket').WebSocket} ws
* @param {string|undefined} reason
*/
function failWebsocketConnection (ws, reason) {
const { [kController]: controller, [kResponse]: response } = ws
controller.abort()
if (response?.socket && !response.socket.destroyed) {
response.socket.destroy()
}
if (reason) {
fireEvent('error', ws, ErrorEvent, {
error: new Error(reason)
})
}
}
module.exports = {
isEstablished,
isClosing,
isClosed,
fireEvent,
isValidSubprotocol,
isValidStatusCode,
failWebsocketConnection,
websocketMessageReceived
}
/***/ }),
/***/ 54284:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { webidl } = __nccwpck_require__(21744)
const { DOMException } = __nccwpck_require__(41037)
const { URLSerializer } = __nccwpck_require__(685)
const { getGlobalOrigin } = __nccwpck_require__(71246)
const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(19188)
const {
kWebSocketURL,
kReadyState,
kController,
kBinaryType,
kResponse,
kSentClose,
kByteParser
} = __nccwpck_require__(37578)
const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(25515)
const { establishWebSocketConnection } = __nccwpck_require__(35354)
const { WebsocketFrameSend } = __nccwpck_require__(25444)
const { ByteParser } = __nccwpck_require__(11688)
const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(83983)
const { getGlobalDispatcher } = __nccwpck_require__(21892)
const { types } = __nccwpck_require__(73837)
let experimentalWarned = false
// https://websockets.spec.whatwg.org/#interface-definition
class WebSocket extends EventTarget {
#events = {
open: null,
error: null,
close: null,
message: null
}
#bufferedAmount = 0
#protocol = ''
#extensions = ''
/**
* @param {string} url
* @param {string|string[]} protocols
*/
constructor (url, protocols = []) {
super()
webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
if (!experimentalWarned) {
experimentalWarned = true
process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
code: 'UNDICI-WS'
})
}
const options = webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'](protocols)
url = webidl.converters.USVString(url)
protocols = options.protocols
// 1. Let baseURL be this's relevant settings object's API base URL.
const baseURL = getGlobalOrigin()
// 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
let urlRecord
try {
urlRecord = new URL(url, baseURL)
} catch (e) {
// 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
throw new DOMException(e, 'SyntaxError')
}
// 4. If urlRecords scheme is "http", then set urlRecords scheme to "ws".
if (urlRecord.protocol === 'http:') {
urlRecord.protocol = 'ws:'
} else if (urlRecord.protocol === 'https:') {
// 5. Otherwise, if urlRecords scheme is "https", set urlRecords scheme to "wss".
urlRecord.protocol = 'wss:'
}
// 6. If urlRecords scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
throw new DOMException(
`Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
'SyntaxError'
)
}
// 7. If urlRecords fragment is non-null, then throw a "SyntaxError"
// DOMException.
if (urlRecord.hash || urlRecord.href.endsWith('#')) {
throw new DOMException('Got fragment', 'SyntaxError')
}
// 8. If protocols is a string, set protocols to a sequence consisting
// of just that string.
if (typeof protocols === 'string') {
protocols = [protocols]
}
// 9. If any of the values in protocols occur more than once or otherwise
// fail to match the requirements for elements that comprise the value
// of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
// protocol, then throw a "SyntaxError" DOMException.
if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
}
if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
}
// 10. Set this's url to urlRecord.
this[kWebSocketURL] = new URL(urlRecord.href)
// 11. Let client be this's relevant settings object.
// 12. Run this step in parallel:
// 1. Establish a WebSocket connection given urlRecord, protocols,
// and client.
this[kController] = establishWebSocketConnection(
urlRecord,
protocols,
this,
(response) => this.#onConnectionEstablished(response),
options
)
// Each WebSocket object has an associated ready state, which is a
// number representing the state of the connection. Initially it must
// be CONNECTING (0).
this[kReadyState] = WebSocket.CONNECTING
// The extensions attribute must initially return the empty string.
// The protocol attribute must initially return the empty string.
// Each WebSocket object has an associated binary type, which is a
// BinaryType. Initially it must be "blob".
this[kBinaryType] = 'blob'
}
/**
* @see https://websockets.spec.whatwg.org/#dom-websocket-close
* @param {number|undefined} code
* @param {string|undefined} reason
*/
close (code = undefined, reason = undefined) {
webidl.brandCheck(this, WebSocket)
if (code !== undefined) {
code = webidl.converters['unsigned short'](code, { clamp: true })
}
if (reason !== undefined) {
reason = webidl.converters.USVString(reason)
}
// 1. If code is present, but is neither an integer equal to 1000 nor an
// integer in the range 3000 to 4999, inclusive, throw an
// "InvalidAccessError" DOMException.
if (code !== undefined) {
if (code !== 1000 && (code < 3000 || code > 4999)) {
throw new DOMException('invalid code', 'InvalidAccessError')
}
}
let reasonByteLength = 0
// 2. If reason is present, then run these substeps:
if (reason !== undefined) {
// 1. Let reasonBytes be the result of encoding reason.
// 2. If reasonBytes is longer than 123 bytes, then throw a
// "SyntaxError" DOMException.
reasonByteLength = Buffer.byteLength(reason)
if (reasonByteLength > 123) {
throw new DOMException(
`Reason must be less than 123 bytes; received ${reasonByteLength}`,
'SyntaxError'
)
}
}
// 3. Run the first matching steps from the following list:
if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
// If this's ready state is CLOSING (2) or CLOSED (3)
// Do nothing.
} else if (!isEstablished(this)) {
// If the WebSocket connection is not yet established
// Fail the WebSocket connection and set this's ready state
// to CLOSING (2).
failWebsocketConnection(this, 'Connection was closed before it was established.')
this[kReadyState] = WebSocket.CLOSING
} else if (!isClosing(this)) {
// If the WebSocket closing handshake has not yet been started
// Start the WebSocket closing handshake and set this's ready
// state to CLOSING (2).
// - If neither code nor reason is present, the WebSocket Close
// message must not have a body.
// - If code is present, then the status code to use in the
// WebSocket Close message must be the integer given by code.
// - If reason is also present, then reasonBytes must be
// provided in the Close message after the status code.
const frame = new WebsocketFrameSend()
// If neither code nor reason is present, the WebSocket Close
// message must not have a body.
// If code is present, then the status code to use in the
// WebSocket Close message must be the integer given by code.
if (code !== undefined && reason === undefined) {
frame.frameData = Buffer.allocUnsafe(2)
frame.frameData.writeUInt16BE(code, 0)
} else if (code !== undefined && reason !== undefined) {
// If reason is also present, then reasonBytes must be
// provided in the Close message after the status code.
frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
frame.frameData.writeUInt16BE(code, 0)
// the body MAY contain UTF-8-encoded data with value /reason/
frame.frameData.write(reason, 2, 'utf-8')
} else {
frame.frameData = emptyBuffer
}
/** @type {import('stream').Duplex} */
const socket = this[kResponse].socket
socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
if (!err) {
this[kSentClose] = true
}
})
// Upon either sending or receiving a Close control frame, it is said
// that _The WebSocket Closing Handshake is Started_ and that the
// WebSocket connection is in the CLOSING state.
this[kReadyState] = states.CLOSING
} else {
// Otherwise
// Set this's ready state to CLOSING (2).
this[kReadyState] = WebSocket.CLOSING
}
}
/**
* @see https://websockets.spec.whatwg.org/#dom-websocket-send
* @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
*/
send (data) {
webidl.brandCheck(this, WebSocket)
webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
data = webidl.converters.WebSocketSendData(data)
// 1. If this's ready state is CONNECTING, then throw an
// "InvalidStateError" DOMException.
if (this[kReadyState] === WebSocket.CONNECTING) {
throw new DOMException('Sent before connected.', 'InvalidStateError')
}
// 2. Run the appropriate set of steps from the following list:
// https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
// https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
if (!isEstablished(this) || isClosing(this)) {
return
}
/** @type {import('stream').Duplex} */
const socket = this[kResponse].socket
// If data is a string
if (typeof data === 'string') {
// If the WebSocket connection is established and the WebSocket
// closing handshake has not yet started, then the user agent
// must send a WebSocket Message comprised of the data argument
// using a text frame opcode; if the data cannot be sent, e.g.
// because it would need to be buffered but the buffer is full,
// the user agent must flag the WebSocket as full and then close
// the WebSocket connection. Any invocation of this method with a
// string argument that does not throw an exception must increase
// the bufferedAmount attribute by the number of bytes needed to
// express the argument as UTF-8.
const value = Buffer.from(data)
const frame = new WebsocketFrameSend(value)
const buffer = frame.createFrame(opcodes.TEXT)
this.#bufferedAmount += value.byteLength
socket.write(buffer, () => {
this.#bufferedAmount -= value.byteLength
})
} else if (types.isArrayBuffer(data)) {
// If the WebSocket connection is established, and the WebSocket
// closing handshake has not yet started, then the user agent must
// send a WebSocket Message comprised of data using a binary frame
// opcode; if the data cannot be sent, e.g. because it would need
// to be buffered but the buffer is full, the user agent must flag
// the WebSocket as full and then close the WebSocket connection.
// The data to be sent is the data stored in the buffer described
// by the ArrayBuffer object. Any invocation of this method with an
// ArrayBuffer argument that does not throw an exception must
// increase the bufferedAmount attribute by the length of the
// ArrayBuffer in bytes.
const value = Buffer.from(data)
const frame = new WebsocketFrameSend(value)
const buffer = frame.createFrame(opcodes.BINARY)
this.#bufferedAmount += value.byteLength
socket.write(buffer, () => {
this.#bufferedAmount -= value.byteLength
})
} else if (ArrayBuffer.isView(data)) {
// If the WebSocket connection is established, and the WebSocket
// closing handshake has not yet started, then the user agent must
// send a WebSocket Message comprised of data using a binary frame
// opcode; if the data cannot be sent, e.g. because it would need to
// be buffered but the buffer is full, the user agent must flag the
// WebSocket as full and then close the WebSocket connection. The
// data to be sent is the data stored in the section of the buffer
// described by the ArrayBuffer object that data references. Any
// invocation of this method with this kind of argument that does
// not throw an exception must increase the bufferedAmount attribute
// by the length of datas buffer in bytes.
const ab = Buffer.from(data, data.byteOffset, data.byteLength)
const frame = new WebsocketFrameSend(ab)
const buffer = frame.createFrame(opcodes.BINARY)
this.#bufferedAmount += ab.byteLength
socket.write(buffer, () => {
this.#bufferedAmount -= ab.byteLength
})
} else if (isBlobLike(data)) {
// If the WebSocket connection is established, and the WebSocket
// closing handshake has not yet started, then the user agent must
// send a WebSocket Message comprised of data using a binary frame
// opcode; if the data cannot be sent, e.g. because it would need to
// be buffered but the buffer is full, the user agent must flag the
// WebSocket as full and then close the WebSocket connection. The data
// to be sent is the raw data represented by the Blob object. Any
// invocation of this method with a Blob argument that does not throw
// an exception must increase the bufferedAmount attribute by the size
// of the Blob objects raw data, in bytes.
const frame = new WebsocketFrameSend()
data.arrayBuffer().then((ab) => {
const value = Buffer.from(ab)
frame.frameData = value
const buffer = frame.createFrame(opcodes.BINARY)
this.#bufferedAmount += value.byteLength
socket.write(buffer, () => {
this.#bufferedAmount -= value.byteLength
})
})
}
}
get readyState () {
webidl.brandCheck(this, WebSocket)
// The readyState getter steps are to return this's ready state.
return this[kReadyState]
}
get bufferedAmount () {
webidl.brandCheck(this, WebSocket)
return this.#bufferedAmount
}
get url () {
webidl.brandCheck(this, WebSocket)
// The url getter steps are to return this's url, serialized.
return URLSerializer(this[kWebSocketURL])
}
get extensions () {
webidl.brandCheck(this, WebSocket)
return this.#extensions
}
get protocol () {
webidl.brandCheck(this, WebSocket)
return this.#protocol
}
get onopen () {
webidl.brandCheck(this, WebSocket)
return this.#events.open
}
set onopen (fn) {
webidl.brandCheck(this, WebSocket)
if (this.#events.open) {
this.removeEventListener('open', this.#events.open)
}
if (typeof fn === 'function') {
this.#events.open = fn
this.addEventListener('open', fn)
} else {
this.#events.open = null
}
}
get onerror () {
webidl.brandCheck(this, WebSocket)
return this.#events.error
}
set onerror (fn) {
webidl.brandCheck(this, WebSocket)
if (this.#events.error) {
this.removeEventListener('error', this.#events.error)
}
if (typeof fn === 'function') {
this.#events.error = fn
this.addEventListener('error', fn)
} else {
this.#events.error = null
}
}
get onclose () {
webidl.brandCheck(this, WebSocket)
return this.#events.close
}
set onclose (fn) {
webidl.brandCheck(this, WebSocket)
if (this.#events.close) {
this.removeEventListener('close', this.#events.close)
}
if (typeof fn === 'function') {
this.#events.close = fn
this.addEventListener('close', fn)
} else {
this.#events.close = null
}
}
get onmessage () {
webidl.brandCheck(this, WebSocket)
return this.#events.message
}
set onmessage (fn) {
webidl.brandCheck(this, WebSocket)
if (this.#events.message) {
this.removeEventListener('message', this.#events.message)
}
if (typeof fn === 'function') {
this.#events.message = fn
this.addEventListener('message', fn)
} else {
this.#events.message = null
}
}
get binaryType () {
webidl.brandCheck(this, WebSocket)
return this[kBinaryType]
}
set binaryType (type) {
webidl.brandCheck(this, WebSocket)
if (type !== 'blob' && type !== 'arraybuffer') {
this[kBinaryType] = 'blob'
} else {
this[kBinaryType] = type
}
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
*/
#onConnectionEstablished (response) {
// processResponse is called when the "responses header list has been received and initialized."
// once this happens, the connection is open
this[kResponse] = response
const parser = new ByteParser(this)
parser.on('drain', function onParserDrain () {
this.ws[kResponse].socket.resume()
})
response.socket.ws = this
this[kByteParser] = parser
// 1. Change the ready state to OPEN (1).
this[kReadyState] = states.OPEN
// 2. Change the extensions attributes value to the extensions in use, if
// it is not the null value.
// https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
const extensions = response.headersList.get('sec-websocket-extensions')
if (extensions !== null) {
this.#extensions = extensions
}
// 3. Change the protocol attributes value to the subprotocol in use, if
// it is not the null value.
// https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
const protocol = response.headersList.get('sec-websocket-protocol')
if (protocol !== null) {
this.#protocol = protocol
}
// 4. Fire an event named open at the WebSocket object.
fireEvent('open', this)
}
}
// https://websockets.spec.whatwg.org/#dom-websocket-connecting
WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
// https://websockets.spec.whatwg.org/#dom-websocket-open
WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
// https://websockets.spec.whatwg.org/#dom-websocket-closing
WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
// https://websockets.spec.whatwg.org/#dom-websocket-closed
WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
Object.defineProperties(WebSocket.prototype, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors,
url: kEnumerableProperty,
readyState: kEnumerableProperty,
bufferedAmount: kEnumerableProperty,
onopen: kEnumerableProperty,
onerror: kEnumerableProperty,
onclose: kEnumerableProperty,
close: kEnumerableProperty,
onmessage: kEnumerableProperty,
binaryType: kEnumerableProperty,
send: kEnumerableProperty,
extensions: kEnumerableProperty,
protocol: kEnumerableProperty,
[Symbol.toStringTag]: {
value: 'WebSocket',
writable: false,
enumerable: false,
configurable: true
}
})
Object.defineProperties(WebSocket, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors
})
webidl.converters['sequence<DOMString>'] = webidl.sequenceConverter(
webidl.converters.DOMString
)
webidl.converters['DOMString or sequence<DOMString>'] = function (V) {
if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
return webidl.converters['sequence<DOMString>'](V)
}
return webidl.converters.DOMString(V)
}
// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
webidl.converters.WebSocketInit = webidl.dictionaryConverter([
{
key: 'protocols',
converter: webidl.converters['DOMString or sequence<DOMString>'],
get defaultValue () {
return []
}
},
{
key: 'dispatcher',
converter: (V) => V,
get defaultValue () {
return getGlobalDispatcher()
}
},
{
key: 'headers',
converter: webidl.nullableConverter(webidl.converters.HeadersInit)
}
])
webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'] = function (V) {
if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
return webidl.converters.WebSocketInit(V)
}
return { protocols: webidl.converters['DOMString or sequence<DOMString>'](V) }
}
webidl.converters.WebSocketSendData = function (V) {
if (webidl.util.Type(V) === 'Object') {
if (isBlobLike(V)) {
return webidl.converters.Blob(V, { strict: false })
}
if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
return webidl.converters.BufferSource(V)
}
}
return webidl.converters.USVString(V)
}
module.exports = {
WebSocket
}
/***/ }),
/***/ 70020:
/***/ (function(__unused_webpack_module, exports) {
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function (global, factory) {
true ? factory(exports) :
0;
}(this, (function (exports) { 'use strict';
function merge() {
for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
sets[_key] = arguments[_key];
}
if (sets.length > 1) {
sets[0] = sets[0].slice(0, -1);
var xl = sets.length - 1;
for (var x = 1; x < xl; ++x) {
sets[x] = sets[x].slice(1, -1);
}
sets[xl] = sets[xl].slice(1);
return sets.join('');
} else {
return sets[0];
}
}
function subexp(str) {
return "(?:" + str + ")";
}
function typeOf(o) {
return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
}
function toUpperCase(str) {
return str.toUpperCase();
}
function toArray(obj) {
return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
}
function assign(target, source) {
var obj = target;
if (source) {
for (var key in source) {
obj[key] = source[key];
}
}
return obj;
}
function buildExps(isIRI) {
var ALPHA$$ = "[A-Za-z]",
CR$ = "[\\x0D]",
DIGIT$$ = "[0-9]",
DQUOTE$$ = "[\\x22]",
HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
//case-insensitive
LF$$ = "[\\x0A]",
SP$$ = "[\\x20]",
PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
//expanded
GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
//subset, excludes bidi control characters
IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
//subset
UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
//relaxed parsing rules
IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
H16$ = subexp(HEXDIG$$ + "{1,4}"),
LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
// 6( h16 ":" ) ls32
IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
// "::" 5( h16 ":" ) ls32
IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
//[ h16 ] "::" 4( h16 ":" ) ls32
IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
//[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
//[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
//[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
//[ *4( h16 ":" ) h16 ] "::" ls32
IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
//[ *5( h16 ":" ) h16 ] "::" h16
IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
//[ *6( h16 ":" ) h16 ] "::"
IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
//RFC 6874
IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
//RFC 6874
IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
//RFC 6874, with relaxed parsing rules
IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
//RFC 6874
REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
PORT$ = subexp(DIGIT$$ + "*"),
AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
SEGMENT$ = subexp(PCHAR$ + "*"),
SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
//simplified
PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
//simplified
PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
//simplified
PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
return {
NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
UNRESERVED: new RegExp(UNRESERVED$$, "g"),
OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
};
}
var URI_PROTOCOL = buildExps(false);
var IRI_PROTOCOL = buildExps(true);
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/** Highest positive signed 32-bit float value */
var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'
/** Regular expressions */
var regexPunycode = /^xn--/;
var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
/** Error messages */
var errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
};
/** Convenience shortcuts */
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error$1(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var result = [];
var length = array.length;
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
while (counter < length) {
var value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// Low surrogate.
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
var ucs2encode = function ucs2encode(array) {
return String.fromCodePoint.apply(String, toConsumableArray(array));
};
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
var basicToDigit = function basicToDigit(codePoint) {
if (codePoint - 0x30 < 0x0A) {
return codePoint - 0x16;
}
if (codePoint - 0x41 < 0x1A) {
return codePoint - 0x41;
}
if (codePoint - 0x61 < 0x1A) {
return codePoint - 0x61;
}
return base;
};
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
var digitToBasic = function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
var adapt = function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
var decode = function decode(input) {
// Don't use UCS-2.
var output = [];
var inputLength = input.length;
var i = 0;
var n = initialN;
var bias = initialBias;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
var basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (var j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error$1('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
var oldi = i;
for (var w = 1, k = base;; /* no condition */k += base) {
if (index >= inputLength) {
error$1('invalid-input');
}
var digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error$1('overflow');
}
i += digit * w;
var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
var baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error$1('overflow');
}
w *= baseMinusT;
}
var out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error$1('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output.
output.splice(i++, 0, n);
}
return String.fromCodePoint.apply(String, output);
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
var encode = function encode(input) {
var output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
var inputLength = input.length;
// Initialize the state.
var n = initialN;
var delta = 0;
var bias = initialBias;
// Handle the basic code points.
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _currentValue2 = _step.value;
if (_currentValue2 < 0x80) {
output.push(stringFromCharCode(_currentValue2));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var basicLength = output.length;
var handledCPCount = basicLength;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
var m = maxInt;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var currentValue = _step2.value;
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow.
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error$1('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var _currentValue = _step3.value;
if (_currentValue < n && ++delta > maxInt) {
error$1('overflow');
}
if (_currentValue == n) {
// Represent delta as a generalized variable-length integer.
var q = delta;
for (var k = base;; /* no condition */k += base) {
var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
var qMinusT = q - t;
var baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
++delta;
++n;
}
return output.join('');
};
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
var toUnicode = function toUnicode(input) {
return mapDomain(input, function (string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
};
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
var toASCII = function toASCII(input) {
return mapDomain(input, function (string) {
return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
});
};
/*--------------------------------------------------------------------------*/
/** Define the public API */
var punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '2.1.0',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/**
* URI.js
*
* @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/uri-js
*/
/**
* Copyright 2011 Gary Court. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Gary Court.
*/
var SCHEMES = {};
function pctEncChar(chr) {
var c = chr.charCodeAt(0);
var e = void 0;
if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
return e;
}
function pctDecChars(str) {
var newStr = "";
var i = 0;
var il = str.length;
while (i < il) {
var c = parseInt(str.substr(i + 1, 2), 16);
if (c < 128) {
newStr += String.fromCharCode(c);
i += 3;
} else if (c >= 194 && c < 224) {
if (il - i >= 6) {
var c2 = parseInt(str.substr(i + 4, 2), 16);
newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
} else {
newStr += str.substr(i, 6);
}
i += 6;
} else if (c >= 224) {
if (il - i >= 9) {
var _c = parseInt(str.substr(i + 4, 2), 16);
var c3 = parseInt(str.substr(i + 7, 2), 16);
newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
} else {
newStr += str.substr(i, 9);
}
i += 9;
} else {
newStr += str.substr(i, 3);
i += 3;
}
}
return newStr;
}
function _normalizeComponentEncoding(components, protocol) {
function decodeUnreserved(str) {
var decStr = pctDecChars(str);
return !decStr.match(protocol.UNRESERVED) ? str : decStr;
}
if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
return components;
}
function _stripLeadingZeros(str) {
return str.replace(/^0*(.*)/, "$1") || "0";
}
function _normalizeIPv4(host, protocol) {
var matches = host.match(protocol.IPV4ADDRESS) || [];
var _matches = slicedToArray(matches, 2),
address = _matches[1];
if (address) {
return address.split(".").map(_stripLeadingZeros).join(".");
} else {
return host;
}
}
function _normalizeIPv6(host, protocol) {
var matches = host.match(protocol.IPV6ADDRESS) || [];
var _matches2 = slicedToArray(matches, 3),
address = _matches2[1],
zone = _matches2[2];
if (address) {
var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
_address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
last = _address$toLowerCase$2[0],
first = _address$toLowerCase$2[1];
var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
var lastFields = last.split(":").map(_stripLeadingZeros);
var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
var fieldCount = isLastFieldIPv4Address ? 7 : 8;
var lastFieldsStart = lastFields.length - fieldCount;
var fields = Array(fieldCount);
for (var x = 0; x < fieldCount; ++x) {
fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
}
if (isLastFieldIPv4Address) {
fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
}
var allZeroFields = fields.reduce(function (acc, field, index) {
if (!field || field === "0") {
var lastLongest = acc[acc.length - 1];
if (lastLongest && lastLongest.index + lastLongest.length === index) {
lastLongest.length++;
} else {
acc.push({ index: index, length: 1 });
}
}
return acc;
}, []);
var longestZeroFields = allZeroFields.sort(function (a, b) {
return b.length - a.length;
})[0];
var newHost = void 0;
if (longestZeroFields && longestZeroFields.length > 1) {
var newFirst = fields.slice(0, longestZeroFields.index);
var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
newHost = newFirst.join(":") + "::" + newLast.join(":");
} else {
newHost = fields.join(":");
}
if (zone) {
newHost += "%" + zone;
}
return newHost;
} else {
return host;
}
}
var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
function parse(uriString) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var components = {};
var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
var matches = uriString.match(URI_PARSE);
if (matches) {
if (NO_MATCH_IS_UNDEFINED) {
//store each component
components.scheme = matches[1];
components.userinfo = matches[3];
components.host = matches[4];
components.port = parseInt(matches[5], 10);
components.path = matches[6] || "";
components.query = matches[7];
components.fragment = matches[8];
//fix port number
if (isNaN(components.port)) {
components.port = matches[5];
}
} else {
//IE FIX for improper RegExp matching
//store each component
components.scheme = matches[1] || undefined;
components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
components.port = parseInt(matches[5], 10);
components.path = matches[6] || "";
components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
//fix port number
if (isNaN(components.port)) {
components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
}
}
if (components.host) {
//normalize IP hosts
components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
}
//determine reference type
if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
components.reference = "same-document";
} else if (components.scheme === undefined) {
components.reference = "relative";
} else if (components.fragment === undefined) {
components.reference = "absolute";
} else {
components.reference = "uri";
}
//check for reference errors
if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
components.error = components.error || "URI is not a " + options.reference + " reference.";
}
//find scheme handler
var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
//check if scheme can't handle IRIs
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
//if host component is a domain name
if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
//convert Unicode IDN -> ASCII IDN
try {
components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
} catch (e) {
components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
}
}
//convert IRI -> URI
_normalizeComponentEncoding(components, URI_PROTOCOL);
} else {
//normalize encodings
_normalizeComponentEncoding(components, protocol);
}
//perform scheme specific parsing
if (schemeHandler && schemeHandler.parse) {
schemeHandler.parse(components, options);
}
} else {
components.error = components.error || "URI can not be parsed.";
}
return components;
}
function _recomposeAuthority(components, options) {
var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
var uriTokens = [];
if (components.userinfo !== undefined) {
uriTokens.push(components.userinfo);
uriTokens.push("@");
}
if (components.host !== undefined) {
//normalize IP hosts, add brackets and escape zone separator for IPv6
uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
}));
}
if (typeof components.port === "number" || typeof components.port === "string") {
uriTokens.push(":");
uriTokens.push(String(components.port));
}
return uriTokens.length ? uriTokens.join("") : undefined;
}
var RDS1 = /^\.\.?\//;
var RDS2 = /^\/\.(\/|$)/;
var RDS3 = /^\/\.\.(\/|$)/;
var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
function removeDotSegments(input) {
var output = [];
while (input.length) {
if (input.match(RDS1)) {
input = input.replace(RDS1, "");
} else if (input.match(RDS2)) {
input = input.replace(RDS2, "/");
} else if (input.match(RDS3)) {
input = input.replace(RDS3, "/");
output.pop();
} else if (input === "." || input === "..") {
input = "";
} else {
var im = input.match(RDS5);
if (im) {
var s = im[0];
input = input.slice(s.length);
output.push(s);
} else {
throw new Error("Unexpected dot segment condition");
}
}
}
return output.join("");
}
function serialize(components) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
var uriTokens = [];
//find scheme handler
var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
//perform scheme specific serialization
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
if (components.host) {
//if host component is an IPv6 address
if (protocol.IPV6ADDRESS.test(components.host)) {}
//TODO: normalize IPv6 address as per RFC 5952
//if host component is a domain name
else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
//convert IDN via punycode
try {
components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
} catch (e) {
components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
}
}
}
//normalize encoding
_normalizeComponentEncoding(components, protocol);
if (options.reference !== "suffix" && components.scheme) {
uriTokens.push(components.scheme);
uriTokens.push(":");
}
var authority = _recomposeAuthority(components, options);
if (authority !== undefined) {
if (options.reference !== "suffix") {
uriTokens.push("//");
}
uriTokens.push(authority);
if (components.path && components.path.charAt(0) !== "/") {
uriTokens.push("/");
}
}
if (components.path !== undefined) {
var s = components.path;
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
s = removeDotSegments(s);
}
if (authority === undefined) {
s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
}
uriTokens.push(s);
}
if (components.query !== undefined) {
uriTokens.push("?");
uriTokens.push(components.query);
}
if (components.fragment !== undefined) {
uriTokens.push("#");
uriTokens.push(components.fragment);
}
return uriTokens.join(""); //merge tokens into a string
}
function resolveComponents(base, relative) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var skipNormalization = arguments[3];
var target = {};
if (!skipNormalization) {
base = parse(serialize(base, options), options); //normalize base components
relative = parse(serialize(relative, options), options); //normalize relative components
}
options = options || {};
if (!options.tolerant && relative.scheme) {
target.scheme = relative.scheme;
//target.authority = relative.authority;
target.userinfo = relative.userinfo;
target.host = relative.host;
target.port = relative.port;
target.path = removeDotSegments(relative.path || "");
target.query = relative.query;
} else {
if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
//target.authority = relative.authority;
target.userinfo = relative.userinfo;
target.host = relative.host;
target.port = relative.port;
target.path = removeDotSegments(relative.path || "");
target.query = relative.query;
} else {
if (!relative.path) {
target.path = base.path;
if (relative.query !== undefined) {
target.query = relative.query;
} else {
target.query = base.query;
}
} else {
if (relative.path.charAt(0) === "/") {
target.path = removeDotSegments(relative.path);
} else {
if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
target.path = "/" + relative.path;
} else if (!base.path) {
target.path = relative.path;
} else {
target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
}
target.path = removeDotSegments(target.path);
}
target.query = relative.query;
}
//target.authority = base.authority;
target.userinfo = base.userinfo;
target.host = base.host;
target.port = base.port;
}
target.scheme = base.scheme;
}
target.fragment = relative.fragment;
return target;
}
function resolve(baseURI, relativeURI, options) {
var schemelessOptions = assign({ scheme: 'null' }, options);
return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
}
function normalize(uri, options) {
if (typeof uri === "string") {
uri = serialize(parse(uri, options), options);
} else if (typeOf(uri) === "object") {
uri = parse(serialize(uri, options), options);
}
return uri;
}
function equal(uriA, uriB, options) {
if (typeof uriA === "string") {
uriA = serialize(parse(uriA, options), options);
} else if (typeOf(uriA) === "object") {
uriA = serialize(uriA, options);
}
if (typeof uriB === "string") {
uriB = serialize(parse(uriB, options), options);
} else if (typeOf(uriB) === "object") {
uriB = serialize(uriB, options);
}
return uriA === uriB;
}
function escapeComponent(str, options) {
return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
}
function unescapeComponent(str, options) {
return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
}
var handler = {
scheme: "http",
domainHost: true,
parse: function parse(components, options) {
//report missing host
if (!components.host) {
components.error = components.error || "HTTP URIs must have a host.";
}
return components;
},
serialize: function serialize(components, options) {
var secure = String(components.scheme).toLowerCase() === "https";
//normalize the default port
if (components.port === (secure ? 443 : 80) || components.port === "") {
components.port = undefined;
}
//normalize the empty path
if (!components.path) {
components.path = "/";
}
//NOTE: We do not parse query strings for HTTP URIs
//as WWW Form Url Encoded query strings are part of the HTML4+ spec,
//and not the HTTP spec.
return components;
}
};
var handler$1 = {
scheme: "https",
domainHost: handler.domainHost,
parse: handler.parse,
serialize: handler.serialize
};
function isSecure(wsComponents) {
return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
}
//RFC 6455
var handler$2 = {
scheme: "ws",
domainHost: true,
parse: function parse(components, options) {
var wsComponents = components;
//indicate if the secure flag is set
wsComponents.secure = isSecure(wsComponents);
//construct resouce name
wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');
wsComponents.path = undefined;
wsComponents.query = undefined;
return wsComponents;
},
serialize: function serialize(wsComponents, options) {
//normalize the default port
if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
wsComponents.port = undefined;
}
//ensure scheme matches secure flag
if (typeof wsComponents.secure === 'boolean') {
wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws';
wsComponents.secure = undefined;
}
//reconstruct path from resource name
if (wsComponents.resourceName) {
var _wsComponents$resourc = wsComponents.resourceName.split('?'),
_wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2),
path = _wsComponents$resourc2[0],
query = _wsComponents$resourc2[1];
wsComponents.path = path && path !== '/' ? path : undefined;
wsComponents.query = query;
wsComponents.resourceName = undefined;
}
//forbid fragment component
wsComponents.fragment = undefined;
return wsComponents;
}
};
var handler$3 = {
scheme: "wss",
domainHost: handler$2.domainHost,
parse: handler$2.parse,
serialize: handler$2.serialize
};
var O = {};
var isIRI = true;
//RFC 3986
var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
//const VCHAR$$ = "[\\x21-\\x7E]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
var UNRESERVED = new RegExp(UNRESERVED$$, "g");
var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
var NOT_HFVALUE = NOT_HFNAME;
function decodeUnreserved(str) {
var decStr = pctDecChars(str);
return !decStr.match(UNRESERVED) ? str : decStr;
}
var handler$4 = {
scheme: "mailto",
parse: function parse$$1(components, options) {
var mailtoComponents = components;
var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
mailtoComponents.path = undefined;
if (mailtoComponents.query) {
var unknownHeaders = false;
var headers = {};
var hfields = mailtoComponents.query.split("&");
for (var x = 0, xl = hfields.length; x < xl; ++x) {
var hfield = hfields[x].split("=");
switch (hfield[0]) {
case "to":
var toAddrs = hfield[1].split(",");
for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
to.push(toAddrs[_x]);
}
break;
case "subject":
mailtoComponents.subject = unescapeComponent(hfield[1], options);
break;
case "body":
mailtoComponents.body = unescapeComponent(hfield[1], options);
break;
default:
unknownHeaders = true;
headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
break;
}
}
if (unknownHeaders) mailtoComponents.headers = headers;
}
mailtoComponents.query = undefined;
for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
var addr = to[_x2].split("@");
addr[0] = unescapeComponent(addr[0]);
if (!options.unicodeSupport) {
//convert Unicode IDN -> ASCII IDN
try {
addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
} catch (e) {
mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
}
} else {
addr[1] = unescapeComponent(addr[1], options).toLowerCase();
}
to[_x2] = addr.join("@");
}
return mailtoComponents;
},
serialize: function serialize$$1(mailtoComponents, options) {
var components = mailtoComponents;
var to = toArray(mailtoComponents.to);
if (to) {
for (var x = 0, xl = to.length; x < xl; ++x) {
var toAddr = String(to[x]);
var atIdx = toAddr.lastIndexOf("@");
var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
var domain = toAddr.slice(atIdx + 1);
//convert IDN via punycode
try {
domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
} catch (e) {
components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
}
to[x] = localPart + "@" + domain;
}
components.path = to.join(",");
}
var headers = mailtoComponents.headers = mailtoComponents.headers || {};
if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
var fields = [];
for (var name in headers) {
if (headers[name] !== O[name]) {
fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
}
}
if (fields.length) {
components.query = fields.join("&");
}
return components;
}
};
var URN_PARSE = /^([^\:]+)\:(.*)/;
//RFC 2141
var handler$5 = {
scheme: "urn",
parse: function parse$$1(components, options) {
var matches = components.path && components.path.match(URN_PARSE);
var urnComponents = components;
if (matches) {
var scheme = options.scheme || urnComponents.scheme || "urn";
var nid = matches[1].toLowerCase();
var nss = matches[2];
var urnScheme = scheme + ":" + (options.nid || nid);
var schemeHandler = SCHEMES[urnScheme];
urnComponents.nid = nid;
urnComponents.nss = nss;
urnComponents.path = undefined;
if (schemeHandler) {
urnComponents = schemeHandler.parse(urnComponents, options);
}
} else {
urnComponents.error = urnComponents.error || "URN can not be parsed.";
}
return urnComponents;
},
serialize: function serialize$$1(urnComponents, options) {
var scheme = options.scheme || urnComponents.scheme || "urn";
var nid = urnComponents.nid;
var urnScheme = scheme + ":" + (options.nid || nid);
var schemeHandler = SCHEMES[urnScheme];
if (schemeHandler) {
urnComponents = schemeHandler.serialize(urnComponents, options);
}
var uriComponents = urnComponents;
var nss = urnComponents.nss;
uriComponents.path = (nid || options.nid) + ":" + nss;
return uriComponents;
}
};
var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
//RFC 4122
var handler$6 = {
scheme: "urn:uuid",
parse: function parse(urnComponents, options) {
var uuidComponents = urnComponents;
uuidComponents.uuid = uuidComponents.nss;
uuidComponents.nss = undefined;
if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
uuidComponents.error = uuidComponents.error || "UUID is not valid.";
}
return uuidComponents;
},
serialize: function serialize(uuidComponents, options) {
var urnComponents = uuidComponents;
//normalize UUID
urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
return urnComponents;
}
};
SCHEMES[handler.scheme] = handler;
SCHEMES[handler$1.scheme] = handler$1;
SCHEMES[handler$2.scheme] = handler$2;
SCHEMES[handler$3.scheme] = handler$3;
SCHEMES[handler$4.scheme] = handler$4;
SCHEMES[handler$5.scheme] = handler$5;
SCHEMES[handler$6.scheme] = handler$6;
exports.SCHEMES = SCHEMES;
exports.pctEncChar = pctEncChar;
exports.pctDecChars = pctDecChars;
exports.parse = parse;
exports.removeDotSegments = removeDotSegments;
exports.serialize = serialize;
exports.resolveComponents = resolveComponents;
exports.resolve = resolve;
exports.normalize = normalize;
exports.equal = equal;
exports.escapeComponent = escapeComponent;
exports.unescapeComponent = unescapeComponent;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=uri.all.js.map
/***/ }),
/***/ 75840:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
Object.defineProperty(exports, "v1", ({
enumerable: true,
get: function () {
return _v.default;
}
}));
Object.defineProperty(exports, "v3", ({
enumerable: true,
get: function () {
return _v2.default;
}
}));
Object.defineProperty(exports, "v4", ({
enumerable: true,
get: function () {
return _v3.default;
}
}));
Object.defineProperty(exports, "v5", ({
enumerable: true,
get: function () {
return _v4.default;
}
}));
Object.defineProperty(exports, "NIL", ({
enumerable: true,
get: function () {
return _nil.default;
}
}));
Object.defineProperty(exports, "version", ({
enumerable: true,
get: function () {
return _version.default;
}
}));
Object.defineProperty(exports, "validate", ({
enumerable: true,
get: function () {
return _validate.default;
}
}));
Object.defineProperty(exports, "stringify", ({
enumerable: true,
get: function () {
return _stringify.default;
}
}));
Object.defineProperty(exports, "parse", ({
enumerable: true,
get: function () {
return _parse.default;
}
}));
var _v = _interopRequireDefault(__nccwpck_require__(78628));
var _v2 = _interopRequireDefault(__nccwpck_require__(86409));
var _v3 = _interopRequireDefault(__nccwpck_require__(85122));
var _v4 = _interopRequireDefault(__nccwpck_require__(79120));
var _nil = _interopRequireDefault(__nccwpck_require__(25332));
var _version = _interopRequireDefault(__nccwpck_require__(81595));
var _validate = _interopRequireDefault(__nccwpck_require__(66900));
var _stringify = _interopRequireDefault(__nccwpck_require__(18950));
var _parse = _interopRequireDefault(__nccwpck_require__(62746));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***/ }),
/***/ 4569:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function md5(bytes) {
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === 'string') {
bytes = Buffer.from(bytes, 'utf8');
}
return _crypto.default.createHash('md5').update(bytes).digest();
}
var _default = md5;
exports["default"] = _default;
/***/ }),
/***/ 25332:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _default = '00000000-0000-0000-0000-000000000000';
exports["default"] = _default;
/***/ }),
/***/ 62746:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _validate = _interopRequireDefault(__nccwpck_require__(66900));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError('Invalid UUID');
}
let v;
const arr = new Uint8Array(16); // Parse ########-....-....-....-............
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = v >>> 16 & 0xff;
arr[2] = v >>> 8 & 0xff;
arr[3] = v & 0xff; // Parse ........-####-....-....-............
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff; // Parse ........-....-####-....-............
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff; // Parse ........-....-....-####-............
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff; // Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
arr[11] = v / 0x100000000 & 0xff;
arr[12] = v >>> 24 & 0xff;
arr[13] = v >>> 16 & 0xff;
arr[14] = v >>> 8 & 0xff;
arr[15] = v & 0xff;
return arr;
}
var _default = parse;
exports["default"] = _default;
/***/ }),
/***/ 40814:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
exports["default"] = _default;
/***/ }),
/***/ 50807:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = rng;
var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
let poolPtr = rnds8Pool.length;
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
_crypto.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
/***/ }),
/***/ 85274:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function sha1(bytes) {
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === 'string') {
bytes = Buffer.from(bytes, 'utf8');
}
return _crypto.default.createHash('sha1').update(bytes).digest();
}
var _default = sha1;
exports["default"] = _default;
/***/ }),
/***/ 18950:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _validate = _interopRequireDefault(__nccwpck_require__(66900));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).substr(1));
}
function stringify(arr, offset = 0) {
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!(0, _validate.default)(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
var _default = stringify;
exports["default"] = _default;
/***/ }),
/***/ 78628:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _rng = _interopRequireDefault(__nccwpck_require__(50807));
var _stringify = _interopRequireDefault(__nccwpck_require__(18950));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
let _nodeId;
let _clockseq; // Previous uuid creation time
let _lastMSecs = 0;
let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
function v1(options, buf, offset) {
let i = buf && offset || 0;
const b = buf || new Array(16);
options = options || {};
let node = options.node || _nodeId;
let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
const seedBytes = options.random || (options.rng || _rng.default)();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
} // UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
} // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
} // Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000; // `time_low`
const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff; // `time_mid`
const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff; // `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
b[i++] = clockseq & 0xff; // `node`
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf || (0, _stringify.default)(b);
}
var _default = v1;
exports["default"] = _default;
/***/ }),
/***/ 86409:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _v = _interopRequireDefault(__nccwpck_require__(65998));
var _md = _interopRequireDefault(__nccwpck_require__(4569));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const v3 = (0, _v.default)('v3', 0x30, _md.default);
var _default = v3;
exports["default"] = _default;
/***/ }),
/***/ 65998:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = _default;
exports.URL = exports.DNS = void 0;
var _stringify = _interopRequireDefault(__nccwpck_require__(18950));
var _parse = _interopRequireDefault(__nccwpck_require__(62746));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringToBytes(str) {
str = unescape(encodeURIComponent(str)); // UTF8 escape
const bytes = [];
for (let i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
}
const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
exports.DNS = DNS;
const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
exports.URL = URL;
function _default(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
if (typeof value === 'string') {
value = stringToBytes(value);
}
if (typeof namespace === 'string') {
namespace = (0, _parse.default)(namespace);
}
if (namespace.length !== 16) {
throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
} // Compute hash of namespace and value, Per 4.3
// Future: Use spread syntax when supported on all platforms, e.g. `bytes =
// hashfunc([...namespace, ... value])`
let bytes = new Uint8Array(16 + value.length);
bytes.set(namespace);
bytes.set(value, namespace.length);
bytes = hashfunc(bytes);
bytes[6] = bytes[6] & 0x0f | version;
bytes[8] = bytes[8] & 0x3f | 0x80;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = bytes[i];
}
return buf;
}
return (0, _stringify.default)(bytes);
} // Function#name is not settable on some platforms (#270)
try {
generateUUID.name = name; // eslint-disable-next-line no-empty
} catch (err) {} // For CommonJS default export support
generateUUID.DNS = DNS;
generateUUID.URL = URL;
return generateUUID;
}
/***/ }),
/***/ 85122:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _rng = _interopRequireDefault(__nccwpck_require__(50807));
var _stringify = _interopRequireDefault(__nccwpck_require__(18950));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function v4(options, buf, offset) {
options = options || {};
const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return (0, _stringify.default)(rnds);
}
var _default = v4;
exports["default"] = _default;
/***/ }),
/***/ 79120:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _v = _interopRequireDefault(__nccwpck_require__(65998));
var _sha = _interopRequireDefault(__nccwpck_require__(85274));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const v5 = (0, _v.default)('v5', 0x50, _sha.default);
var _default = v5;
exports["default"] = _default;
/***/ }),
/***/ 66900:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _regex = _interopRequireDefault(__nccwpck_require__(40814));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function validate(uuid) {
return typeof uuid === 'string' && _regex.default.test(uuid);
}
var _default = validate;
exports["default"] = _default;
/***/ }),
/***/ 81595:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _validate = _interopRequireDefault(__nccwpck_require__(66900));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function version(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError('Invalid UUID');
}
return parseInt(uuid.substr(14, 1), 16);
}
var _default = version;
exports["default"] = _default;
/***/ }),
/***/ 69037:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fs = __nccwpck_require__(57147);
const { promisify } = __nccwpck_require__(73837);
const Joi = __nccwpck_require__(20918);
const https = __nccwpck_require__(95687);
const net = __nccwpck_require__(41808);
const util = __nccwpck_require__(73837);
const axiosPkg = (__nccwpck_require__(88757)["default"]);
const { isBoolean, isEmpty, negate, noop, once, partial, pick, zip } = __nccwpck_require__(14542);
const { NEVER, combineLatest, from, merge, throwError, timer } = __nccwpck_require__(1752);
const { distinctUntilChanged, map, mergeMap, scan, startWith, take, takeWhile } = __nccwpck_require__(50749);
// force http adapter for axios, otherwise if using jest/jsdom xhr might
// be used and it logs all errors polluting the logs
const axios = axiosPkg.create({ adapter: 'http' });
const isNotABoolean = negate(isBoolean);
const isNotEmpty = negate(isEmpty);
const fstat = promisify(fs.stat);
const PREFIX_RE = /^((https?-get|https?|tcp|socket|file):)(.+)$/;
const HOST_PORT_RE = /^(([^:]*):)?(\d+)$/;
const HTTP_GET_RE = /^https?-get:/;
const HTTP_UNIX_RE = /^http:\/\/unix:([^:]+):([^:]+)$/;
const TIMEOUT_ERR_MSG = 'Timed out waiting for';
const WAIT_ON_SCHEMA = Joi.object({
resources: Joi.array().items(Joi.string().required()).required(),
delay: Joi.number().integer().min(0).default(0),
httpTimeout: Joi.number().integer().min(0),
interval: Joi.number().integer().min(0).default(250),
log: Joi.boolean().default(false),
reverse: Joi.boolean().default(false),
simultaneous: Joi.number().integer().min(1).default(Infinity),
timeout: Joi.number().integer().min(0).default(Infinity),
validateStatus: Joi.function(),
verbose: Joi.boolean().default(false),
window: Joi.number().integer().min(0).default(750),
tcpTimeout: Joi.number().integer().min(0).default(300),
// http/https options
ca: [Joi.string(), Joi.binary()],
cert: [Joi.string(), Joi.binary()],
key: [Joi.string(), Joi.binary(), Joi.object()],
passphrase: Joi.string(),
proxy: [Joi.boolean(), Joi.object()],
auth: Joi.object({
username: Joi.string(),
password: Joi.string()
}),
strictSSL: Joi.boolean().default(false),
followRedirect: Joi.boolean().default(true), // HTTP 3XX responses
headers: Joi.object()
});
/**
Waits for resources to become available before calling callback
Polls file, http(s), tcp ports, sockets for availability.
Resource types are distinquished by their prefix with default being `file:`
- file:/path/to/file - waits for file to be available and size to stabilize
- http://foo.com:8000/bar verifies HTTP HEAD request returns 2XX
- https://my.bar.com/cat verifies HTTPS HEAD request returns 2XX
- http-get: - HTTP GET returns 2XX response. ex: http://m.com:90/foo
- https-get: - HTTPS GET returns 2XX response. ex: https://my/bar
- tcp:my.server.com:3000 verifies a service is listening on port
- socket:/path/sock verifies a service is listening on (UDS) socket
For http over socket, use http://unix:SOCK_PATH:URL_PATH
like http://unix:/path/to/sock:/foo/bar or
http-get://unix:/path/to/sock:/foo/bar
@param opts object configuring waitOn
@param opts.resources array of string resources to wait for. prefix determines the type of resource with the default type of `file:`
@param opts.delay integer - optional initial delay in ms, default 0
@param opts.httpTimeout integer - optional http HEAD/GET timeout to wait for request, default 0
@param opts.interval integer - optional poll resource interval in ms, default 250ms
@param opts.log boolean - optional flag to turn on logging to stdout
@param opts.reverse boolean - optional flag which reverses the mode, succeeds when resources are not available
@param opts.simultaneous integer - optional limit of concurrent connections to a resource, default Infinity
@param opts.tcpTimeout - Maximum time in ms for tcp connect, default 300ms
@param opts.timeout integer - optional timeout in ms, default Infinity. Aborts with error.
@param opts.verbose boolean - optional flag to turn on debug log
@param opts.window integer - optional stabilization time in ms, default 750ms. Waits this amount of time for file sizes to stabilize or other resource availability to remain unchanged. If less than interval then will be reset to interval
@param cb optional callback function with signature cb(err) - if err is provided then, resource checks did not succeed
if not specified, wait-on will return a promise that will be rejected if resource checks did not succeed or resolved otherwise
*/
function waitOn(opts, cb) {
if (cb !== undefined) {
return waitOnImpl(opts, cb);
} else {
// promise API
return new Promise(function (resolve, reject) {
waitOnImpl(opts, function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}
function waitOnImpl(opts, cbFunc) {
const cbOnce = once(cbFunc);
const validResult = WAIT_ON_SCHEMA.validate(opts);
if (validResult.error) {
return cbOnce(validResult.error);
}
const validatedOpts = {
...validResult.value, // use defaults
// window needs to be at least interval
...(validResult.value.window < validResult.value.interval ? { window: validResult.value.interval } : {}),
...(validResult.value.verbose ? { log: true } : {}) // if debug logging then normal log is also enabled
};
const { resources, log: shouldLog, timeout, verbose, reverse } = validatedOpts;
const output = verbose ? console.log.bind() : noop;
const log = shouldLog ? console.log.bind() : noop;
const logWaitingForWDeps = partial(logWaitingFor, [{ log, resources }]);
const createResourceWithDeps$ = partial(createResource$, [{ validatedOpts, output, log }]);
let lastResourcesState = resources; // the last state we had recorded
const timeoutError$ =
timeout !== Infinity
? timer(timeout).pipe(
mergeMap(() => {
const resourcesWaitingFor = determineRemainingResources(resources, lastResourcesState).join(', ');
return throwError(Error(`${TIMEOUT_ERR_MSG}: ${resourcesWaitingFor}`));
})
)
: NEVER;
function cleanup(err) {
if (err) {
if (err.message.startsWith(TIMEOUT_ERR_MSG)) {
log('wait-on(%s) %s; exiting with error', process.pid, err.message);
} else {
log('wait-on(%s) exiting with error', process.pid, err);
}
} else {
// no error, we are complete
log('wait-on(%s) complete', process.pid);
}
cbOnce(err);
}
if (reverse) {
log('wait-on reverse mode - waiting for resources to be unavailable');
}
logWaitingForWDeps(resources);
const resourcesCompleted$ = combineLatest(resources.map(createResourceWithDeps$));
merge(timeoutError$, resourcesCompleted$)
.pipe(takeWhile((resourceStates) => resourceStates.some((x) => !x)))
.subscribe({
next: (resourceStates) => {
lastResourcesState = resourceStates;
logWaitingForWDeps(resourceStates);
},
error: cleanup,
complete: cleanup
});
}
function logWaitingFor({ log, resources }, resourceStates) {
const remainingResources = determineRemainingResources(resources, resourceStates);
if (isNotEmpty(remainingResources)) {
log(`waiting for ${remainingResources.length} resources: ${remainingResources.join(', ')}`);
}
}
function determineRemainingResources(resources, resourceStates) {
// resourcesState is array of completed booleans
const resourceAndStateTuples = zip(resources, resourceStates);
return resourceAndStateTuples.filter(([, /* r */ s]) => !s).map(([r /*, s */]) => r);
}
function createResource$(deps, resource) {
const prefix = extractPrefix(resource);
switch (prefix) {
case 'https-get:':
case 'http-get:':
case 'https:':
case 'http:':
return createHTTP$(deps, resource);
case 'tcp:':
return createTCP$(deps, resource);
case 'socket:':
return createSocket$(deps, resource);
default:
return createFileResource$(deps, resource);
}
}
function createFileResource$(
{ validatedOpts: { delay, interval, reverse, simultaneous, window: stabilityWindow }, output },
resource
) {
const filePath = extractPath(resource);
const checkOperator = reverse
? map((size) => size === -1) // check that file does not exist
: scan(
// check that file exists and the size is stable
(acc, x) => {
if (x > -1) {
const { size, t } = acc;
const now = Date.now();
if (size !== -1 && x === size) {
if (now >= t + stabilityWindow) {
// file size has stabilized
output(` file stabilized at size:${size} file:${filePath}`);
return true;
}
output(` file exists, checking for size change during stability window, size:${size} file:${filePath}`);
return acc; // return acc unchanged, just waiting to pass stability window
}
output(` file exists, checking for size changes, size:${x} file:${filePath}`);
return { size: x, t: now }; // update acc with new value and timestamp
}
return acc;
},
{ size: -1, t: Date.now() }
);
return timer(delay, interval).pipe(
mergeMap(() => {
output(`checking file stat for file:${filePath} ...`);
return from(getFileSize(filePath));
}, simultaneous),
checkOperator,
map((x) => (isNotABoolean(x) ? false : x)),
startWith(false),
distinctUntilChanged(),
take(2)
);
}
function extractPath(resource) {
const m = PREFIX_RE.exec(resource);
if (m) {
return m[3];
}
return resource;
}
function extractPrefix(resource) {
const m = PREFIX_RE.exec(resource);
if (m) {
return m[1];
}
return '';
}
async function getFileSize(filePath) {
try {
const { size } = await fstat(filePath);
return size;
} catch (err) {
return -1;
}
}
function createHTTP$({ validatedOpts, output }, resource) {
const {
delay,
followRedirect,
httpTimeout: timeout,
interval,
proxy,
reverse,
simultaneous,
strictSSL: rejectUnauthorized
} = validatedOpts;
const method = HTTP_GET_RE.test(resource) ? 'get' : 'head';
const url = resource.replace('-get:', ':');
const matchHttpUnixSocket = HTTP_UNIX_RE.exec(url); // http://unix:/sock:/url
const urlSocketOptions = matchHttpUnixSocket
? { socketPath: matchHttpUnixSocket[1], url: matchHttpUnixSocket[2] }
: { url };
const socketPathDesc = urlSocketOptions.socketPath ? `socketPath:${urlSocketOptions.socketPath}` : '';
const httpOptions = {
...pick(['auth', 'headers', 'validateStatus'], validatedOpts),
httpsAgent: new https.Agent({
rejectUnauthorized,
...pick(['ca', 'cert', 'key', 'passphrase'], validatedOpts)
}),
...(followRedirect ? {} : { maxRedirects: 0 }), // defaults to 5 (enabled)
proxy, // can be undefined, false, or object
...(timeout && { timeout }),
...urlSocketOptions,
method
// by default it provides full response object
// validStatus is 2xx unless followRedirect is true (default)
};
const checkFn = reverse ? negateAsync(httpCallSucceeds) : httpCallSucceeds;
return timer(delay, interval).pipe(
mergeMap(() => {
output(`making HTTP(S) ${method} request to ${socketPathDesc} url:${urlSocketOptions.url} ...`);
return from(checkFn(output, httpOptions));
}, simultaneous),
startWith(false),
distinctUntilChanged(),
take(2)
);
}
async function httpCallSucceeds(output, httpOptions) {
try {
const result = await axios(httpOptions);
output(
` HTTP(S) result for ${httpOptions.url}: ${util.inspect(
pick(['status', 'statusText', 'headers', 'data'], result)
)}`
);
return true;
} catch (err) {
output(` HTTP(S) error for ${httpOptions.url} ${err.toString()}`);
return false;
}
}
function createTCP$({ validatedOpts: { delay, interval, tcpTimeout, reverse, simultaneous }, output }, resource) {
const tcpPath = extractPath(resource);
const checkFn = reverse ? negateAsync(tcpExists) : tcpExists;
return timer(delay, interval).pipe(
mergeMap(() => {
output(`making TCP connection to ${tcpPath} ...`);
return from(checkFn(output, tcpPath, tcpTimeout));
}, simultaneous),
startWith(false),
distinctUntilChanged(),
take(2)
);
}
async function tcpExists(output, tcpPath, tcpTimeout) {
const [, , /* full, hostWithColon */ hostMatched, port] = HOST_PORT_RE.exec(tcpPath);
const host = hostMatched || 'localhost';
return new Promise((resolve) => {
const conn = net
.connect(port, host)
.on('error', (err) => {
output(` error connecting to TCP host:${host} port:${port} ${err.toString()}`);
resolve(false);
})
.on('timeout', () => {
output(` timed out connecting to TCP host:${host} port:${port} tcpTimeout:${tcpTimeout}ms`);
conn.end();
resolve(false);
})
.on('connect', () => {
output(` TCP connection successful to host:${host} port:${port}`);
conn.end();
resolve(true);
});
conn.setTimeout(tcpTimeout);
});
}
function createSocket$({ validatedOpts: { delay, interval, reverse, simultaneous }, output }, resource) {
const socketPath = extractPath(resource);
const checkFn = reverse ? negateAsync(socketExists) : socketExists;
return timer(delay, interval).pipe(
mergeMap(() => {
output(`making socket connection to ${socketPath} ...`);
return from(checkFn(output, socketPath));
}, simultaneous),
startWith(false),
distinctUntilChanged(),
take(2)
);
}
async function socketExists(output, socketPath) {
return new Promise((resolve) => {
const conn = net
.connect(socketPath)
.on('error', (err) => {
output(` error connecting to socket socket:${socketPath} ${err.toString()}`);
resolve(false);
})
.on('connect', () => {
output(` connected to socket:${socketPath}`);
conn.end();
resolve(true);
});
});
}
function negateAsync(asyncFn) {
return async function (...args) {
return !(await asyncFn(...args));
};
}
module.exports = waitOn;
/***/ }),
/***/ 62940:
/***/ ((module) => {
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
/***/ }),
/***/ 81241:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCache = exports.saveCache = void 0;
const env_1 = __nccwpck_require__(42343);
const promises_1 = __nccwpck_require__(76402);
const node_fs_1 = __nccwpck_require__(87561);
const utils_1 = __nccwpck_require__(41303);
const constants_1 = __nccwpck_require__(80317);
//* Cache API
async function saveCache(ctx, hash, size, tag, stream) {
if (!env_1.env.valid) {
ctx.log.info(`Using filesystem cache because cache API env vars are not set`);
await (0, promises_1.pipeline)(stream, (0, node_fs_1.createWriteStream)(`/tmp/${hash}.tg.bin`));
return;
}
const client = (0, utils_1.getCacheClient)();
const existingCacheResponse = await client.create((0, constants_1.getCacheKey)(hash, tag), constants_1.cacheVersion);
// Silently exit when we have not been able to receive a cache-hit
if (existingCacheResponse.success === false) {
return;
}
const id = existingCacheResponse.data?.cacheId;
if (!id) {
throw new Error(`Unable to reserve cache (received: ${JSON.stringify(existingCacheResponse.data)})`);
}
ctx.log.info(`Reserved cache ${id}`);
await client.upload(id, stream, size);
await client.commit(id, size);
ctx.log.info(`Saved cache ${id} for ${hash} (${size} bytes)`);
}
exports.saveCache = saveCache;
async function getCache(ctx, hash) {
if (!env_1.env.valid) {
const path = `/tmp/${hash}.tg.bin`;
if (!(0, node_fs_1.existsSync)(path))
return null;
const size = (0, node_fs_1.statSync)(path).size;
return [size, (0, node_fs_1.createReadStream)(path), undefined];
}
const client = (0, utils_1.getCacheClient)();
const cacheKey = (0, constants_1.getCacheKey)(hash);
const { data } = await client.query(cacheKey, constants_1.cacheVersion);
ctx.log.info(`Cache lookup for ${cacheKey}`);
if (!data) {
ctx.log.info(`Cache lookup did not return data`);
return null;
}
const [foundCacheKey, artifactTag] = String(data.cacheKey).split('#');
if (foundCacheKey !== cacheKey) {
ctx.log.info(`Cache key mismatch: ${foundCacheKey} !== ${cacheKey}`);
return null;
}
const resp = await fetch(data.archiveLocation);
const size = +(resp.headers.get('content-length') || 0);
const readableStream = resp.body;
if (!readableStream) {
throw new Error('Failed to retrieve cache stream');
}
return [size, readableStream, artifactTag];
}
exports.getCache = getCache;
/***/ }),
/***/ 41303:
/***/ (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;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCacheClient = void 0;
const env_1 = __nccwpck_require__(42343);
const core = __importStar(__nccwpck_require__(42186));
const stream_to_promise_1 = __importDefault(__nccwpck_require__(92111));
class HandledError extends Error {
status;
statusText;
data;
constructor(status, statusText, data) {
super(`${status}: ${statusText}`);
this.status = status;
this.statusText = statusText;
this.data = data;
}
}
function handleFetchError(message) {
return (error) => {
if (error instanceof HandledError) {
core.error(`${message}: ${error.status} ${error.statusText}`);
core.error(JSON.stringify(error.data));
throw error;
}
core.error(`${message}: ${error}`);
throw error;
};
}
function getCacheClient() {
if (!env_1.env.valid) {
throw new Error('Cache API env vars are not set');
}
const baseURL = `${env_1.env.ACTIONS_CACHE_URL.replace(/\/$/, '')}/_apis/artifactcache`;
const headers = new Headers({
Authorization: `Bearer ${env_1.env.ACTIONS_RUNTIME_TOKEN}`,
Accept: 'application/json;api-version=6.0-preview.1'
});
const create = async (key, version) => {
try {
const res = await fetch(`${baseURL}/caches`, {
method: 'POST',
headers,
body: JSON.stringify({ key, version })
});
if (!res.ok) {
const { status, statusText } = res;
const data = await res.text();
if (status === 409) {
return { success: false };
}
const buildedError = new HandledError(status, statusText, data);
return handleFetchError('Unable to reserve cache')(buildedError);
}
const data = await res.json();
return { success: true, data };
}
catch (error) {
return handleFetchError('Unable to reserve cache')(error);
}
};
const upload = async (id, stream, size) => {
try {
const body = await (0, stream_to_promise_1.default)(stream);
await fetch(`${baseURL}/caches/${id}`, {
method: 'PATCH',
headers: {
...headers,
'Content-Length': size.toString(),
'Content-Type': 'application/octet-stream',
'Content-Range': `bytes 0-${size - 1}/*`
},
body
});
}
catch (error) {
handleFetchError('Unable to upload cache')(error);
}
};
const commit = async (id, size) => {
try {
await fetch(`${baseURL}/caches/${id}`, {
method: 'POST',
headers,
body: JSON.stringify({ size })
});
}
catch (error) {
handleFetchError('Unable to commit cache')(error);
}
};
const query = async (keys, version) => {
try {
const params = new URLSearchParams({ keys, version });
const res = await fetch(`${baseURL}/caches?${params}`, {
method: 'GET',
headers
});
if (!res.ok) {
const { status, statusText } = res;
const data = await res.text();
const buildedError = new HandledError(status, statusText, data);
return handleFetchError('Unable to query cache')(buildedError);
}
const text = await res.text();
core.info('Cache query response: ' + text);
const data = JSON.parse(text);
return { success: true, data };
}
catch (error) {
return handleFetchError('Unable to query cache')(error);
}
};
return {
create,
upload,
commit,
query
};
}
exports.getCacheClient = getCacheClient;
/***/ }),
/***/ 80317:
/***/ (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;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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.serverLogFile = exports.getCacheKey = exports.cachePrefix = exports.cacheVersion = exports.serverPort = void 0;
const core = __importStar(__nccwpck_require__(42186));
exports.serverPort = 41230;
exports.cacheVersion = 'turbogha_v2';
exports.cachePrefix = core.getInput('cache-prefix') || 'turbogha_';
const getCacheKey = (hash, tag) => `${exports.cachePrefix}${hash}${tag ? `#${tag}` : ''}`;
exports.getCacheKey = getCacheKey;
exports.serverLogFile = '/tmp/turbogha.log';
/***/ }),
/***/ 42343:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.env = void 0;
const envObject = {
ACTIONS_RUNTIME_TOKEN: process.env.ACTIONS_RUNTIME_TOKEN,
ACTIONS_CACHE_URL: process.env.ACTIONS_CACHE_URL
};
exports.env = {
valid: Object.values(envObject).every(value => value !== undefined),
...envObject
};
/***/ }),
/***/ 48872:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.server = void 0;
const fastify_1 = __importDefault(__nccwpck_require__(67834));
const constants_1 = __nccwpck_require__(80317);
const cache_1 = __nccwpck_require__(81241);
async function server() {
//* Create the server
const fastify = (0, fastify_1.default)({
logger: true
});
//? Server status check
fastify.get('/', async () => {
return { ok: true };
});
//? Shut down the server
const shutdown = () => {
setTimeout(() => process.exit(0), 100);
return { ok: true };
};
fastify.delete('/shutdown', async () => {
return shutdown();
});
//? Handle streaming requets body
// https://www.fastify.io/docs/latest/Reference/ContentTypeParser/#catch-all
fastify.addContentTypeParser('application/octet-stream', (_req, _payload, done) => {
done(null);
});
//? Upload cache
fastify.put('/v8/artifacts/:hash', async (request) => {
const hash = request.params.hash;
request.log.info(`Received artifact for ${hash}`);
await (0, cache_1.saveCache)(request, hash, +(request.headers['content-length'] || 0), String(request.headers['x-artifact-tag'] || ''), request.raw);
request.log.info(`Saved artifact for ${hash}`);
return { ok: true };
});
//? Download cache
fastify.get('/v8/artifacts/:hash', async (request, reply) => {
const hash = request.params.hash;
request.log.info(`Requested artifact for ${hash}`);
const result = await (0, cache_1.getCache)(request, hash);
if (result === null) {
request.log.info(`Artifact for ${hash} not found`);
reply.code(404);
return { ok: false };
}
const [size, stream, artifactTag] = result;
if (size) {
reply.header('Content-Length', size);
}
reply.header('Content-Type', 'application/octet-stream');
if (artifactTag) {
reply.header('x-artifact-tag', artifactTag);
}
request.log.info(`Sending artifact for ${hash}`);
return reply.send(stream);
});
//* Start the server
await fastify.listen({ port: constants_1.serverPort });
}
exports.server = server;
/***/ }),
/***/ 19697:
/***/ (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;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.killServer = exports.launchServer = exports.exportVariable = exports.waitForServer = void 0;
const wait_on_1 = __importDefault(__nccwpck_require__(69037));
const constants_1 = __nccwpck_require__(80317);
const core = __importStar(__nccwpck_require__(42186));
const fs_1 = __nccwpck_require__(57147);
const child_process_1 = __nccwpck_require__(32081);
const waitForServer = async () => {
await (0, wait_on_1.default)({
resources: [`http-get://localhost:${constants_1.serverPort}`],
timeout: 5000
});
};
exports.waitForServer = waitForServer;
const exportVariable = (name, value) => {
core.exportVariable(name, value);
core.info(` ${name}=${value}`);
};
exports.exportVariable = exportVariable;
async function launchServer(devRun) {
if (!devRun) {
//* Launch a detached child process to run the server
// See: https://nodejs.org/docs/latest-v16.x/api/child_process.html#optionsdetached
const out = (0, fs_1.openSync)(constants_1.serverLogFile, 'a');
const err = (0, fs_1.openSync)(constants_1.serverLogFile, 'a');
const child = (0, child_process_1.spawn)(process.argv[0], [process.argv[1], '--server'], {
detached: true,
stdio: ['ignore', out, err]
});
child.unref();
core.info(`Cache version: ${constants_1.cacheVersion}`);
core.info(`Cache prefix: ${constants_1.cachePrefix}`);
core.info(`Launched child process: ${child.pid}`);
core.info(`Server log file: ${constants_1.serverLogFile}`);
}
//* Wait for server
await (0, exports.waitForServer)();
core.info(`Server is now up and running.`);
//* Export the environment variables for Turbo
if (devRun) {
console.log('Execute:');
console.log(`export TURBOGHA_PORT=${constants_1.serverPort}`);
console.log(`export TURBO_API=http://localhost:${constants_1.serverPort}`);
console.log(`export TURBO_TOKEN=turbogha`);
console.log(`export TURBO_TEAM=turbogha`);
}
else {
core.info('The following environment variables are exported:');
(0, exports.exportVariable)('TURBOGHA_PORT', `${constants_1.serverPort}`);
(0, exports.exportVariable)('TURBO_API', `http://localhost:${constants_1.serverPort}`);
(0, exports.exportVariable)('TURBO_TOKEN', 'turbogha');
(0, exports.exportVariable)('TURBO_TEAM', 'turbogha');
}
}
exports.launchServer = launchServer;
async function killServer() {
//* Kill the server
await fetch(`http://localhost:${constants_1.serverPort}/shutdown`, {
method: 'DELETE'
});
}
exports.killServer = killServer;
/***/ }),
/***/ 70399:
/***/ (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;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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.run = void 0;
const core = __importStar(__nccwpck_require__(42186));
const server_1 = __nccwpck_require__(48872);
const utils_1 = __nccwpck_require__(19697);
/**
* The main function for the action.
* @returns {Promise<void>} Resolves when the action is complete.
*/
async function run() {
try {
//* Daemon process
if (process.argv[2] === '--server') {
return (0, server_1.server)();
}
//* Base process
return (0, utils_1.launchServer)();
}
catch (error) {
// Fail the workflow run if an error occurs
if (error instanceof Error)
core.setFailed(error.message);
}
}
exports.run = run;
/***/ }),
/***/ 39491:
/***/ ((module) => {
"use strict";
module.exports = require("assert");
/***/ }),
/***/ 50852:
/***/ ((module) => {
"use strict";
module.exports = require("async_hooks");
/***/ }),
/***/ 14300:
/***/ ((module) => {
"use strict";
module.exports = require("buffer");
/***/ }),
/***/ 32081:
/***/ ((module) => {
"use strict";
module.exports = require("child_process");
/***/ }),
/***/ 96206:
/***/ ((module) => {
"use strict";
module.exports = require("console");
/***/ }),
/***/ 6113:
/***/ ((module) => {
"use strict";
module.exports = require("crypto");
/***/ }),
/***/ 67643:
/***/ ((module) => {
"use strict";
module.exports = require("diagnostics_channel");
/***/ }),
/***/ 82361:
/***/ ((module) => {
"use strict";
module.exports = require("events");
/***/ }),
/***/ 57147:
/***/ ((module) => {
"use strict";
module.exports = require("fs");
/***/ }),
/***/ 13685:
/***/ ((module) => {
"use strict";
module.exports = require("http");
/***/ }),
/***/ 85158:
/***/ ((module) => {
"use strict";
module.exports = require("http2");
/***/ }),
/***/ 95687:
/***/ ((module) => {
"use strict";
module.exports = require("https");
/***/ }),
/***/ 98188:
/***/ ((module) => {
"use strict";
module.exports = require("module");
/***/ }),
/***/ 41808:
/***/ ((module) => {
"use strict";
module.exports = require("net");
/***/ }),
/***/ 98061:
/***/ ((module) => {
"use strict";
module.exports = require("node:assert");
/***/ }),
/***/ 92761:
/***/ ((module) => {
"use strict";
module.exports = require("node:async_hooks");
/***/ }),
/***/ 6005:
/***/ ((module) => {
"use strict";
module.exports = require("node:crypto");
/***/ }),
/***/ 65714:
/***/ ((module) => {
"use strict";
module.exports = require("node:diagnostics_channel");
/***/ }),
/***/ 30604:
/***/ ((module) => {
"use strict";
module.exports = require("node:dns");
/***/ }),
/***/ 15673:
/***/ ((module) => {
"use strict";
module.exports = require("node:events");
/***/ }),
/***/ 87561:
/***/ ((module) => {
"use strict";
module.exports = require("node:fs");
/***/ }),
/***/ 88849:
/***/ ((module) => {
"use strict";
module.exports = require("node:http");
/***/ }),
/***/ 42725:
/***/ ((module) => {
"use strict";
module.exports = require("node:http2");
/***/ }),
/***/ 22286:
/***/ ((module) => {
"use strict";
module.exports = require("node:https");
/***/ }),
/***/ 84492:
/***/ ((module) => {
"use strict";
module.exports = require("node:stream");
/***/ }),
/***/ 76402:
/***/ ((module) => {
"use strict";
module.exports = require("node:stream/promises");
/***/ }),
/***/ 41041:
/***/ ((module) => {
"use strict";
module.exports = require("node:url");
/***/ }),
/***/ 47261:
/***/ ((module) => {
"use strict";
module.exports = require("node:util");
/***/ }),
/***/ 22037:
/***/ ((module) => {
"use strict";
module.exports = require("os");
/***/ }),
/***/ 71017:
/***/ ((module) => {
"use strict";
module.exports = require("path");
/***/ }),
/***/ 4074:
/***/ ((module) => {
"use strict";
module.exports = require("perf_hooks");
/***/ }),
/***/ 63477:
/***/ ((module) => {
"use strict";
module.exports = require("querystring");
/***/ }),
/***/ 12781:
/***/ ((module) => {
"use strict";
module.exports = require("stream");
/***/ }),
/***/ 35356:
/***/ ((module) => {
"use strict";
module.exports = require("stream/web");
/***/ }),
/***/ 71576:
/***/ ((module) => {
"use strict";
module.exports = require("string_decoder");
/***/ }),
/***/ 24404:
/***/ ((module) => {
"use strict";
module.exports = require("tls");
/***/ }),
/***/ 76224:
/***/ ((module) => {
"use strict";
module.exports = require("tty");
/***/ }),
/***/ 57310:
/***/ ((module) => {
"use strict";
module.exports = require("url");
/***/ }),
/***/ 73837:
/***/ ((module) => {
"use strict";
module.exports = require("util");
/***/ }),
/***/ 29830:
/***/ ((module) => {
"use strict";
module.exports = require("util/types");
/***/ }),
/***/ 71267:
/***/ ((module) => {
"use strict";
module.exports = require("worker_threads");
/***/ }),
/***/ 59796:
/***/ ((module) => {
"use strict";
module.exports = require("zlib");
/***/ }),
/***/ 92960:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const WritableStream = (__nccwpck_require__(84492).Writable)
const inherits = (__nccwpck_require__(47261).inherits)
const StreamSearch = __nccwpck_require__(51142)
const PartStream = __nccwpck_require__(81620)
const HeaderParser = __nccwpck_require__(92032)
const DASH = 45
const B_ONEDASH = Buffer.from('-')
const B_CRLF = Buffer.from('\r\n')
const EMPTY_FN = function () {}
function Dicer (cfg) {
if (!(this instanceof Dicer)) { return new Dicer(cfg) }
WritableStream.call(this, cfg)
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
this._headerFirst = cfg.headerFirst
this._dashes = 0
this._parts = 0
this._finished = false
this._realFinish = false
this._isPreamble = true
this._justMatched = false
this._firstWrite = true
this._inHeader = true
this._part = undefined
this._cb = undefined
this._ignoreData = false
this._partOpts = { highWaterMark: cfg.partHwm }
this._pause = false
const self = this
this._hparser = new HeaderParser(cfg)
this._hparser.on('header', function (header) {
self._inHeader = false
self._part.emit('header', header)
})
}
inherits(Dicer, WritableStream)
Dicer.prototype.emit = function (ev) {
if (ev === 'finish' && !this._realFinish) {
if (!this._finished) {
const self = this
process.nextTick(function () {
self.emit('error', new Error('Unexpected end of multipart data'))
if (self._part && !self._ignoreData) {
const type = (self._isPreamble ? 'Preamble' : 'Part')
self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
self._part.push(null)
process.nextTick(function () {
self._realFinish = true
self.emit('finish')
self._realFinish = false
})
return
}
self._realFinish = true
self.emit('finish')
self._realFinish = false
})
}
} else { WritableStream.prototype.emit.apply(this, arguments) }
}
Dicer.prototype._write = function (data, encoding, cb) {
// ignore unexpected data (e.g. extra trailer data after finished)
if (!this._hparser && !this._bparser) { return cb() }
if (this._headerFirst && this._isPreamble) {
if (!this._part) {
this._part = new PartStream(this._partOpts)
if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }
}
const r = this._hparser.push(data)
if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
}
// allows for "easier" testing
if (this._firstWrite) {
this._bparser.push(B_CRLF)
this._firstWrite = false
}
this._bparser.push(data)
if (this._pause) { this._cb = cb } else { cb() }
}
Dicer.prototype.reset = function () {
this._part = undefined
this._bparser = undefined
this._hparser = undefined
}
Dicer.prototype.setBoundary = function (boundary) {
const self = this
this._bparser = new StreamSearch('\r\n--' + boundary)
this._bparser.on('info', function (isMatch, data, start, end) {
self._oninfo(isMatch, data, start, end)
})
}
Dicer.prototype._ignore = function () {
if (this._part && !this._ignoreData) {
this._ignoreData = true
this._part.on('error', EMPTY_FN)
// we must perform some kind of read on the stream even though we are
// ignoring the data, otherwise node's Readable stream will not emit 'end'
// after pushing null to the stream
this._part.resume()
}
}
Dicer.prototype._oninfo = function (isMatch, data, start, end) {
let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
if (!this._part && this._justMatched && data) {
while (this._dashes < 2 && (start + i) < end) {
if (data[start + i] === DASH) {
++i
++this._dashes
} else {
if (this._dashes) { buf = B_ONEDASH }
this._dashes = 0
break
}
}
if (this._dashes === 2) {
if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }
this.reset()
this._finished = true
// no more parts will be added
if (self._parts === 0) {
self._realFinish = true
self.emit('finish')
self._realFinish = false
}
}
if (this._dashes) { return }
}
if (this._justMatched) { this._justMatched = false }
if (!this._part) {
this._part = new PartStream(this._partOpts)
this._part._read = function (n) {
self._unpause()
}
if (this._isPreamble && this.listenerCount('preamble') !== 0) {
this.emit('preamble', this._part)
} else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
this.emit('part', this._part)
} else {
this._ignore()
}
if (!this._isPreamble) { this._inHeader = true }
}
if (data && start < end && !this._ignoreData) {
if (this._isPreamble || !this._inHeader) {
if (buf) { shouldWriteMore = this._part.push(buf) }
shouldWriteMore = this._part.push(data.slice(start, end))
if (!shouldWriteMore) { this._pause = true }
} else if (!this._isPreamble && this._inHeader) {
if (buf) { this._hparser.push(buf) }
r = this._hparser.push(data.slice(start, end))
if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
}
}
if (isMatch) {
this._hparser.reset()
if (this._isPreamble) { this._isPreamble = false } else {
if (start !== end) {
++this._parts
this._part.on('end', function () {
if (--self._parts === 0) {
if (self._finished) {
self._realFinish = true
self.emit('finish')
self._realFinish = false
} else {
self._unpause()
}
}
})
}
}
this._part.push(null)
this._part = undefined
this._ignoreData = false
this._justMatched = true
this._dashes = 0
}
}
Dicer.prototype._unpause = function () {
if (!this._pause) { return }
this._pause = false
if (this._cb) {
const cb = this._cb
this._cb = undefined
cb()
}
}
module.exports = Dicer
/***/ }),
/***/ 92032:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const EventEmitter = (__nccwpck_require__(15673).EventEmitter)
const inherits = (__nccwpck_require__(47261).inherits)
const getLimit = __nccwpck_require__(21467)
const StreamSearch = __nccwpck_require__(51142)
const B_DCRLF = Buffer.from('\r\n\r\n')
const RE_CRLF = /\r\n/g
const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
function HeaderParser (cfg) {
EventEmitter.call(this)
cfg = cfg || {}
const self = this
this.nread = 0
this.maxed = false
this.npairs = 0
this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
this.buffer = ''
this.header = {}
this.finished = false
this.ss = new StreamSearch(B_DCRLF)
this.ss.on('info', function (isMatch, data, start, end) {
if (data && !self.maxed) {
if (self.nread + end - start >= self.maxHeaderSize) {
end = self.maxHeaderSize - self.nread + start
self.nread = self.maxHeaderSize
self.maxed = true
} else { self.nread += (end - start) }
self.buffer += data.toString('binary', start, end)
}
if (isMatch) { self._finish() }
})
}
inherits(HeaderParser, EventEmitter)
HeaderParser.prototype.push = function (data) {
const r = this.ss.push(data)
if (this.finished) { return r }
}
HeaderParser.prototype.reset = function () {
this.finished = false
this.buffer = ''
this.header = {}
this.ss.reset()
}
HeaderParser.prototype._finish = function () {
if (this.buffer) { this._parseHeader() }
this.ss.matches = this.ss.maxMatches
const header = this.header
this.header = {}
this.buffer = ''
this.finished = true
this.nread = this.npairs = 0
this.maxed = false
this.emit('header', header)
}
HeaderParser.prototype._parseHeader = function () {
if (this.npairs === this.maxHeaderPairs) { return }
const lines = this.buffer.split(RE_CRLF)
const len = lines.length
let m, h
for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
if (lines[i].length === 0) { continue }
if (lines[i][0] === '\t' || lines[i][0] === ' ') {
// folded header content
// RFC2822 says to just remove the CRLF and not the whitespace following
// it, so we follow the RFC and include the leading whitespace ...
if (h) {
this.header[h][this.header[h].length - 1] += lines[i]
continue
}
}
const posColon = lines[i].indexOf(':')
if (
posColon === -1 ||
posColon === 0
) {
return
}
m = RE_HDR.exec(lines[i])
h = m[1].toLowerCase()
this.header[h] = this.header[h] || []
this.header[h].push((m[2] || ''))
if (++this.npairs === this.maxHeaderPairs) { break }
}
}
module.exports = HeaderParser
/***/ }),
/***/ 81620:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const inherits = (__nccwpck_require__(47261).inherits)
const ReadableStream = (__nccwpck_require__(84492).Readable)
function PartStream (opts) {
ReadableStream.call(this, opts)
}
inherits(PartStream, ReadableStream)
PartStream.prototype._read = function (n) {}
module.exports = PartStream
/***/ }),
/***/ 51142:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/**
* Copyright Brian White. All rights reserved.
*
* @see https://github.com/mscdex/streamsearch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
* by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
const EventEmitter = (__nccwpck_require__(15673).EventEmitter)
const inherits = (__nccwpck_require__(47261).inherits)
function SBMH (needle) {
if (typeof needle === 'string') {
needle = Buffer.from(needle)
}
if (!Buffer.isBuffer(needle)) {
throw new TypeError('The needle has to be a String or a Buffer.')
}
const needleLength = needle.length
if (needleLength === 0) {
throw new Error('The needle cannot be an empty String/Buffer.')
}
if (needleLength > 256) {
throw new Error('The needle cannot have a length bigger than 256.')
}
this.maxMatches = Infinity
this.matches = 0
this._occ = new Array(256)
.fill(needleLength) // Initialize occurrence table.
this._lookbehind_size = 0
this._needle = needle
this._bufpos = 0
this._lookbehind = Buffer.alloc(needleLength)
// Populate occurrence table with analysis of the needle,
// ignoring last letter.
for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
this._occ[needle[i]] = needleLength - 1 - i
}
}
inherits(SBMH, EventEmitter)
SBMH.prototype.reset = function () {
this._lookbehind_size = 0
this.matches = 0
this._bufpos = 0
}
SBMH.prototype.push = function (chunk, pos) {
if (!Buffer.isBuffer(chunk)) {
chunk = Buffer.from(chunk, 'binary')
}
const chlen = chunk.length
this._bufpos = pos || 0
let r
while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
return r
}
SBMH.prototype._sbmh_feed = function (data) {
const len = data.length
const needle = this._needle
const needleLength = needle.length
const lastNeedleChar = needle[needleLength - 1]
// Positive: points to a position in `data`
// pos == 3 points to data[3]
// Negative: points to a position in the lookbehind buffer
// pos == -2 points to lookbehind[lookbehind_size - 2]
let pos = -this._lookbehind_size
let ch
if (pos < 0) {
// Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
// search with character lookup code that considers both the
// lookbehind buffer and the current round's haystack data.
//
// Loop until
// there is a match.
// or until
// we've moved past the position that requires the
// lookbehind buffer. In this case we switch to the
// optimized loop.
// or until
// the character to look at lies outside the haystack.
while (pos < 0 && pos <= len - needleLength) {
ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
if (
ch === lastNeedleChar &&
this._sbmh_memcmp(data, pos, needleLength - 1)
) {
this._lookbehind_size = 0
++this.matches
this.emit('info', true)
return (this._bufpos = pos + needleLength)
}
pos += this._occ[ch]
}
// No match.
if (pos < 0) {
// There's too few data for Boyer-Moore-Horspool to run,
// so let's use a different algorithm to skip as much as
// we can.
// Forward pos until
// the trailing part of lookbehind + data
// looks like the beginning of the needle
// or until
// pos == 0
while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
if (pos >= 0) {
// Discard lookbehind buffer.
this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
this._lookbehind_size = 0
} else {
// Cut off part of the lookbehind buffer that has
// been processed and append the entire haystack
// into it.
const bytesToCutOff = this._lookbehind_size + pos
if (bytesToCutOff > 0) {
// The cut off data is guaranteed not to contain the needle.
this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
}
this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
this._lookbehind_size - bytesToCutOff)
this._lookbehind_size -= bytesToCutOff
data.copy(this._lookbehind, this._lookbehind_size)
this._lookbehind_size += len
this._bufpos = len
return len
}
}
pos += (pos >= 0) * this._bufpos
// Lookbehind buffer is now empty. We only need to check if the
// needle is in the haystack.
if (data.indexOf(needle, pos) !== -1) {
pos = data.indexOf(needle, pos)
++this.matches
if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
return (this._bufpos = pos + needleLength)
} else {
pos = len - needleLength
}
// There was no match. If there's trailing haystack data that we cannot
// match yet using the Boyer-Moore-Horspool algorithm (because the trailing
// data is less than the needle size) then match using a modified
// algorithm that starts matching from the beginning instead of the end.
// Whatever trailing data is left after running this algorithm is added to
// the lookbehind buffer.
while (
pos < len &&
(
data[pos] !== needle[0] ||
(
(Buffer.compare(
data.subarray(pos, pos + len - pos),
needle.subarray(0, len - pos)
) !== 0)
)
)
) {
++pos
}
if (pos < len) {
data.copy(this._lookbehind, 0, pos, pos + (len - pos))
this._lookbehind_size = len - pos
}
// Everything until pos is guaranteed not to contain needle data.
if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
this._bufpos = len
return len
}
SBMH.prototype._sbmh_lookup_char = function (data, pos) {
return (pos < 0)
? this._lookbehind[this._lookbehind_size + pos]
: data[pos]
}
SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
}
return true
}
module.exports = SBMH
/***/ }),
/***/ 50727:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const WritableStream = (__nccwpck_require__(84492).Writable)
const { inherits } = __nccwpck_require__(47261)
const Dicer = __nccwpck_require__(92960)
const MultipartParser = __nccwpck_require__(32183)
const UrlencodedParser = __nccwpck_require__(78306)
const parseParams = __nccwpck_require__(31854)
function Busboy (opts) {
if (!(this instanceof Busboy)) { return new Busboy(opts) }
if (typeof opts !== 'object') {
throw new TypeError('Busboy expected an options-Object.')
}
if (typeof opts.headers !== 'object') {
throw new TypeError('Busboy expected an options-Object with headers-attribute.')
}
if (typeof opts.headers['content-type'] !== 'string') {
throw new TypeError('Missing Content-Type-header.')
}
const {
headers,
...streamOptions
} = opts
this.opts = {
autoDestroy: false,
...streamOptions
}
WritableStream.call(this, this.opts)
this._done = false
this._parser = this.getParserByHeaders(headers)
this._finished = false
}
inherits(Busboy, WritableStream)
Busboy.prototype.emit = function (ev) {
if (ev === 'finish') {
if (!this._done) {
this._parser?.end()
return
} else if (this._finished) {
return
}
this._finished = true
}
WritableStream.prototype.emit.apply(this, arguments)
}
Busboy.prototype.getParserByHeaders = function (headers) {
const parsed = parseParams(headers['content-type'])
const cfg = {
defCharset: this.opts.defCharset,
fileHwm: this.opts.fileHwm,
headers,
highWaterMark: this.opts.highWaterMark,
isPartAFile: this.opts.isPartAFile,
limits: this.opts.limits,
parsedConType: parsed,
preservePath: this.opts.preservePath
}
if (MultipartParser.detect.test(parsed[0])) {
return new MultipartParser(this, cfg)
}
if (UrlencodedParser.detect.test(parsed[0])) {
return new UrlencodedParser(this, cfg)
}
throw new Error('Unsupported Content-Type.')
}
Busboy.prototype._write = function (chunk, encoding, cb) {
this._parser.write(chunk, cb)
}
module.exports = Busboy
module.exports["default"] = Busboy
module.exports.Busboy = Busboy
module.exports.Dicer = Dicer
/***/ }),
/***/ 32183:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// TODO:
// * support 1 nested multipart level
// (see second multipart example here:
// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
// * support limits.fieldNameSize
// -- this will require modifications to utils.parseParams
const { Readable } = __nccwpck_require__(84492)
const { inherits } = __nccwpck_require__(47261)
const Dicer = __nccwpck_require__(92960)
const parseParams = __nccwpck_require__(31854)
const decodeText = __nccwpck_require__(84619)
const basename = __nccwpck_require__(48647)
const getLimit = __nccwpck_require__(21467)
const RE_BOUNDARY = /^boundary$/i
const RE_FIELD = /^form-data$/i
const RE_CHARSET = /^charset$/i
const RE_FILENAME = /^filename$/i
const RE_NAME = /^name$/i
Multipart.detect = /^multipart\/form-data/i
function Multipart (boy, cfg) {
let i
let len
const self = this
let boundary
const limits = cfg.limits
const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
const parsedConType = cfg.parsedConType || []
const defCharset = cfg.defCharset || 'utf8'
const preservePath = cfg.preservePath
const fileOpts = { highWaterMark: cfg.fileHwm }
for (i = 0, len = parsedConType.length; i < len; ++i) {
if (Array.isArray(parsedConType[i]) &&
RE_BOUNDARY.test(parsedConType[i][0])) {
boundary = parsedConType[i][1]
break
}
}
function checkFinished () {
if (nends === 0 && finished && !boy._done) {
finished = false
self.end()
}
}
if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
const filesLimit = getLimit(limits, 'files', Infinity)
const fieldsLimit = getLimit(limits, 'fields', Infinity)
const partsLimit = getLimit(limits, 'parts', Infinity)
const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
let nfiles = 0
let nfields = 0
let nends = 0
let curFile
let curField
let finished = false
this._needDrain = false
this._pause = false
this._cb = undefined
this._nparts = 0
this._boy = boy
const parserCfg = {
boundary,
maxHeaderPairs: headerPairsLimit,
maxHeaderSize: headerSizeLimit,
partHwm: fileOpts.highWaterMark,
highWaterMark: cfg.highWaterMark
}
this.parser = new Dicer(parserCfg)
this.parser.on('drain', function () {
self._needDrain = false
if (self._cb && !self._pause) {
const cb = self._cb
self._cb = undefined
cb()
}
}).on('part', function onPart (part) {
if (++self._nparts > partsLimit) {
self.parser.removeListener('part', onPart)
self.parser.on('part', skipPart)
boy.hitPartsLimit = true
boy.emit('partsLimit')
return skipPart(part)
}
// hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
// us emit 'end' early since we know the part has ended if we are already
// seeing the next part
if (curField) {
const field = curField
field.emit('end')
field.removeAllListeners('end')
}
part.on('header', function (header) {
let contype
let fieldname
let parsed
let charset
let encoding
let filename
let nsize = 0
if (header['content-type']) {
parsed = parseParams(header['content-type'][0])
if (parsed[0]) {
contype = parsed[0].toLowerCase()
for (i = 0, len = parsed.length; i < len; ++i) {
if (RE_CHARSET.test(parsed[i][0])) {
charset = parsed[i][1].toLowerCase()
break
}
}
}
}
if (contype === undefined) { contype = 'text/plain' }
if (charset === undefined) { charset = defCharset }
if (header['content-disposition']) {
parsed = parseParams(header['content-disposition'][0])
if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
for (i = 0, len = parsed.length; i < len; ++i) {
if (RE_NAME.test(parsed[i][0])) {
fieldname = parsed[i][1]
} else if (RE_FILENAME.test(parsed[i][0])) {
filename = parsed[i][1]
if (!preservePath) { filename = basename(filename) }
}
}
} else { return skipPart(part) }
if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
let onData,
onEnd
if (isPartAFile(fieldname, contype, filename)) {
// file/binary field
if (nfiles === filesLimit) {
if (!boy.hitFilesLimit) {
boy.hitFilesLimit = true
boy.emit('filesLimit')
}
return skipPart(part)
}
++nfiles
if (boy.listenerCount('file') === 0) {
self.parser._ignore()
return
}
++nends
const file = new FileStream(fileOpts)
curFile = file
file.on('end', function () {
--nends
self._pause = false
checkFinished()
if (self._cb && !self._needDrain) {
const cb = self._cb
self._cb = undefined
cb()
}
})
file._read = function (n) {
if (!self._pause) { return }
self._pause = false
if (self._cb && !self._needDrain) {
const cb = self._cb
self._cb = undefined
cb()
}
}
boy.emit('file', fieldname, file, filename, encoding, contype)
onData = function (data) {
if ((nsize += data.length) > fileSizeLimit) {
const extralen = fileSizeLimit - nsize + data.length
if (extralen > 0) { file.push(data.slice(0, extralen)) }
file.truncated = true
file.bytesRead = fileSizeLimit
part.removeAllListeners('data')
file.emit('limit')
return
} else if (!file.push(data)) { self._pause = true }
file.bytesRead = nsize
}
onEnd = function () {
curFile = undefined
file.push(null)
}
} else {
// non-file field
if (nfields === fieldsLimit) {
if (!boy.hitFieldsLimit) {
boy.hitFieldsLimit = true
boy.emit('fieldsLimit')
}
return skipPart(part)
}
++nfields
++nends
let buffer = ''
let truncated = false
curField = part
onData = function (data) {
if ((nsize += data.length) > fieldSizeLimit) {
const extralen = (fieldSizeLimit - (nsize - data.length))
buffer += data.toString('binary', 0, extralen)
truncated = true
part.removeAllListeners('data')
} else { buffer += data.toString('binary') }
}
onEnd = function () {
curField = undefined
if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
--nends
checkFinished()
}
}
/* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
broken. Streams2/streams3 is a huge black box of confusion, but
somehow overriding the sync state seems to fix things again (and still
seems to work for previous node versions).
*/
part._readableState.sync = false
part.on('data', onData)
part.on('end', onEnd)
}).on('error', function (err) {
if (curFile) { curFile.emit('error', err) }
})
}).on('error', function (err) {
boy.emit('error', err)
}).on('finish', function () {
finished = true
checkFinished()
})
}
Multipart.prototype.write = function (chunk, cb) {
const r = this.parser.write(chunk)
if (r && !this._pause) {
cb()
} else {
this._needDrain = !r
this._cb = cb
}
}
Multipart.prototype.end = function () {
const self = this
if (self.parser.writable) {
self.parser.end()
} else if (!self._boy._done) {
process.nextTick(function () {
self._boy._done = true
self._boy.emit('finish')
})
}
}
function skipPart (part) {
part.resume()
}
function FileStream (opts) {
Readable.call(this, opts)
this.bytesRead = 0
this.truncated = false
}
inherits(FileStream, Readable)
FileStream.prototype._read = function (n) {}
module.exports = Multipart
/***/ }),
/***/ 78306:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Decoder = __nccwpck_require__(27100)
const decodeText = __nccwpck_require__(84619)
const getLimit = __nccwpck_require__(21467)
const RE_CHARSET = /^charset$/i
UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
function UrlEncoded (boy, cfg) {
const limits = cfg.limits
const parsedConType = cfg.parsedConType
this.boy = boy
this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
this.fieldsLimit = getLimit(limits, 'fields', Infinity)
let charset
for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
if (Array.isArray(parsedConType[i]) &&
RE_CHARSET.test(parsedConType[i][0])) {
charset = parsedConType[i][1].toLowerCase()
break
}
}
if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
this.decoder = new Decoder()
this.charset = charset
this._fields = 0
this._state = 'key'
this._checkingBytes = true
this._bytesKey = 0
this._bytesVal = 0
this._key = ''
this._val = ''
this._keyTrunc = false
this._valTrunc = false
this._hitLimit = false
}
UrlEncoded.prototype.write = function (data, cb) {
if (this._fields === this.fieldsLimit) {
if (!this.boy.hitFieldsLimit) {
this.boy.hitFieldsLimit = true
this.boy.emit('fieldsLimit')
}
return cb()
}
let idxeq; let idxamp; let i; let p = 0; const len = data.length
while (p < len) {
if (this._state === 'key') {
idxeq = idxamp = undefined
for (i = p; i < len; ++i) {
if (!this._checkingBytes) { ++p }
if (data[i] === 0x3D/* = */) {
idxeq = i
break
} else if (data[i] === 0x26/* & */) {
idxamp = i
break
}
if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
this._hitLimit = true
break
} else if (this._checkingBytes) { ++this._bytesKey }
}
if (idxeq !== undefined) {
// key with assignment
if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
this._state = 'val'
this._hitLimit = false
this._checkingBytes = true
this._val = ''
this._bytesVal = 0
this._valTrunc = false
this.decoder.reset()
p = idxeq + 1
} else if (idxamp !== undefined) {
// key with no assignment
++this._fields
let key; const keyTrunc = this._keyTrunc
if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
this._hitLimit = false
this._checkingBytes = true
this._key = ''
this._bytesKey = 0
this._keyTrunc = false
this.decoder.reset()
if (key.length) {
this.boy.emit('field', decodeText(key, 'binary', this.charset),
'',
keyTrunc,
false)
}
p = idxamp + 1
if (this._fields === this.fieldsLimit) { return cb() }
} else if (this._hitLimit) {
// we may not have hit the actual limit if there are encoded bytes...
if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
p = i
if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
// yep, we actually did hit the limit
this._checkingBytes = false
this._keyTrunc = true
}
} else {
if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
p = len
}
} else {
idxamp = undefined
for (i = p; i < len; ++i) {
if (!this._checkingBytes) { ++p }
if (data[i] === 0x26/* & */) {
idxamp = i
break
}
if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
this._hitLimit = true
break
} else if (this._checkingBytes) { ++this._bytesVal }
}
if (idxamp !== undefined) {
++this._fields
if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
decodeText(this._val, 'binary', this.charset),
this._keyTrunc,
this._valTrunc)
this._state = 'key'
this._hitLimit = false
this._checkingBytes = true
this._key = ''
this._bytesKey = 0
this._keyTrunc = false
this.decoder.reset()
p = idxamp + 1
if (this._fields === this.fieldsLimit) { return cb() }
} else if (this._hitLimit) {
// we may not have hit the actual limit if there are encoded bytes...
if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
p = i
if ((this._val === '' && this.fieldSizeLimit === 0) ||
(this._bytesVal = this._val.length) === this.fieldSizeLimit) {
// yep, we actually did hit the limit
this._checkingBytes = false
this._valTrunc = true
}
} else {
if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
p = len
}
}
}
cb()
}
UrlEncoded.prototype.end = function () {
if (this.boy._done) { return }
if (this._state === 'key' && this._key.length > 0) {
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
'',
this._keyTrunc,
false)
} else if (this._state === 'val') {
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
decodeText(this._val, 'binary', this.charset),
this._keyTrunc,
this._valTrunc)
}
this.boy._done = true
this.boy.emit('finish')
}
module.exports = UrlEncoded
/***/ }),
/***/ 27100:
/***/ ((module) => {
"use strict";
const RE_PLUS = /\+/g
const HEX = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]
function Decoder () {
this.buffer = undefined
}
Decoder.prototype.write = function (str) {
// Replace '+' with ' ' before decoding
str = str.replace(RE_PLUS, ' ')
let res = ''
let i = 0; let p = 0; const len = str.length
for (; i < len; ++i) {
if (this.buffer !== undefined) {
if (!HEX[str.charCodeAt(i)]) {
res += '%' + this.buffer
this.buffer = undefined
--i // retry character
} else {
this.buffer += str[i]
++p
if (this.buffer.length === 2) {
res += String.fromCharCode(parseInt(this.buffer, 16))
this.buffer = undefined
}
}
} else if (str[i] === '%') {
if (i > p) {
res += str.substring(p, i)
p = i
}
this.buffer = ''
++p
}
}
if (p < len && this.buffer === undefined) { res += str.substring(p) }
return res
}
Decoder.prototype.reset = function () {
this.buffer = undefined
}
module.exports = Decoder
/***/ }),
/***/ 48647:
/***/ ((module) => {
"use strict";
module.exports = function basename (path) {
if (typeof path !== 'string') { return '' }
for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
switch (path.charCodeAt(i)) {
case 0x2F: // '/'
case 0x5C: // '\'
path = path.slice(i + 1)
return (path === '..' || path === '.' ? '' : path)
}
}
return (path === '..' || path === '.' ? '' : path)
}
/***/ }),
/***/ 84619:
/***/ (function(module) {
"use strict";
// Node has always utf-8
const utf8Decoder = new TextDecoder('utf-8')
const textDecoders = new Map([
['utf-8', utf8Decoder],
['utf8', utf8Decoder]
])
function getDecoder (charset) {
let lc
while (true) {
switch (charset) {
case 'utf-8':
case 'utf8':
return decoders.utf8
case 'latin1':
case 'ascii': // TODO: Make these a separate, strict decoder?
case 'us-ascii':
case 'iso-8859-1':
case 'iso8859-1':
case 'iso88591':
case 'iso_8859-1':
case 'windows-1252':
case 'iso_8859-1:1987':
case 'cp1252':
case 'x-cp1252':
return decoders.latin1
case 'utf16le':
case 'utf-16le':
case 'ucs2':
case 'ucs-2':
return decoders.utf16le
case 'base64':
return decoders.base64
default:
if (lc === undefined) {
lc = true
charset = charset.toLowerCase()
continue
}
return decoders.other.bind(charset)
}
}
}
const decoders = {
utf8: (data, sourceEncoding) => {
if (data.length === 0) {
return ''
}
if (typeof data === 'string') {
data = Buffer.from(data, sourceEncoding)
}
return data.utf8Slice(0, data.length)
},
latin1: (data, sourceEncoding) => {
if (data.length === 0) {
return ''
}
if (typeof data === 'string') {
return data
}
return data.latin1Slice(0, data.length)
},
utf16le: (data, sourceEncoding) => {
if (data.length === 0) {
return ''
}
if (typeof data === 'string') {
data = Buffer.from(data, sourceEncoding)
}
return data.ucs2Slice(0, data.length)
},
base64: (data, sourceEncoding) => {
if (data.length === 0) {
return ''
}
if (typeof data === 'string') {
data = Buffer.from(data, sourceEncoding)
}
return data.base64Slice(0, data.length)
},
other: (data, sourceEncoding) => {
if (data.length === 0) {
return ''
}
if (typeof data === 'string') {
data = Buffer.from(data, sourceEncoding)
}
if (textDecoders.has(this.toString())) {
try {
return textDecoders.get(this).decode(data)
} catch {}
}
return typeof data === 'string'
? data
: data.toString()
}
}
function decodeText (text, sourceEncoding, destEncoding) {
if (text) {
return getDecoder(destEncoding)(text, sourceEncoding)
}
return text
}
module.exports = decodeText
/***/ }),
/***/ 21467:
/***/ ((module) => {
"use strict";
module.exports = function getLimit (limits, name, defaultLimit) {
if (
!limits ||
limits[name] === undefined ||
limits[name] === null
) { return defaultLimit }
if (
typeof limits[name] !== 'number' ||
isNaN(limits[name])
) { throw new TypeError('Limit ' + name + ' is not a valid number') }
return limits[name]
}
/***/ }),
/***/ 31854:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint-disable object-property-newline */
const decodeText = __nccwpck_require__(84619)
const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
const EncodedLookup = {
'%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
'%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
'%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
'%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
'%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
'%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
'%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
'%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
'%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
'%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
'%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
'%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
'%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
'%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
'%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
'%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
'%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
'%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
'%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
'%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
'%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
'%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
'%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
'%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
'%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
'%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
'%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
'%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
'%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
'%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
'%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
'%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
'%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
'%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
'%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
'%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
'%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
'%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
'%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
'%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
'%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
'%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
'%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
'%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
'%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
'%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
'%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
'%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
'%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
'%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
'%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
'%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
'%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
'%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
'%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
'%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
'%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
'%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
'%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
'%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
'%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
'%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
'%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
'%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
'%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
'%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
'%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
'%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
'%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
'%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
'%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
'%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
'%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
'%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
'%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
'%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
'%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
'%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
'%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
'%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
'%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
'%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
'%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
'%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
'%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
'%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
'%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
'%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
'%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
'%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
'%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
'%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
'%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
'%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
'%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
'%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
'%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
}
function encodedReplacer (match) {
return EncodedLookup[match]
}
const STATE_KEY = 0
const STATE_VALUE = 1
const STATE_CHARSET = 2
const STATE_LANG = 3
function parseParams (str) {
const res = []
let state = STATE_KEY
let charset = ''
let inquote = false
let escaping = false
let p = 0
let tmp = ''
const len = str.length
for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
const char = str[i]
if (char === '\\' && inquote) {
if (escaping) { escaping = false } else {
escaping = true
continue
}
} else if (char === '"') {
if (!escaping) {
if (inquote) {
inquote = false
state = STATE_KEY
} else { inquote = true }
continue
} else { escaping = false }
} else {
if (escaping && inquote) { tmp += '\\' }
escaping = false
if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
if (state === STATE_CHARSET) {
state = STATE_LANG
charset = tmp.substring(1)
} else { state = STATE_VALUE }
tmp = ''
continue
} else if (state === STATE_KEY &&
(char === '*' || char === '=') &&
res.length) {
state = char === '*'
? STATE_CHARSET
: STATE_VALUE
res[p] = [tmp, undefined]
tmp = ''
continue
} else if (!inquote && char === ';') {
state = STATE_KEY
if (charset) {
if (tmp.length) {
tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
'binary',
charset)
}
charset = ''
} else if (tmp.length) {
tmp = decodeText(tmp, 'binary', 'utf8')
}
if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
tmp = ''
++p
continue
} else if (!inquote && (char === ' ' || char === '\t')) { continue }
}
tmp += char
}
if (charset && tmp.length) {
tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
'binary',
charset)
} else if (tmp) {
tmp = decodeText(tmp, 'binary', 'utf8')
}
if (res[p] === undefined) {
if (tmp) { res[p] = tmp }
} else { res[p][1] = tmp }
return res
}
module.exports = parseParams
/***/ }),
/***/ 22259:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { format } = __nccwpck_require__(47261)
function toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
function createError (code, message, statusCode = 500, Base = Error) {
if (!code) throw new Error('Fastify error code must not be empty')
if (!message) throw new Error('Fastify error message must not be empty')
code = code.toUpperCase()
!statusCode && (statusCode = undefined)
function FastifyError (...args) {
if (!new.target) {
return new FastifyError(...args)
}
this.code = code
this.name = 'FastifyError'
this.statusCode = statusCode
const lastElement = args.length - 1
if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === 'object' && 'cause' in args[lastElement]) {
this.cause = args.pop().cause
}
this.message = format(message, ...args)
Error.stackTraceLimit !== 0 && Error.captureStackTrace(this, FastifyError)
}
FastifyError.prototype = Object.create(Base.prototype, {
constructor: {
value: FastifyError,
enumerable: false,
writable: true,
configurable: true
}
})
FastifyError.prototype[Symbol.toStringTag] = 'Error'
FastifyError.prototype.toString = toString
return FastifyError
}
module.exports = createError
module.exports["default"] = createError
module.exports.createError = createError
/***/ }),
/***/ 86389:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const deepEqual = __nccwpck_require__(28206)
const resolvers = __nccwpck_require__(99616)
const errors = __nccwpck_require__(55002)
const keywordsResolvers = {
$id: resolvers.skip,
type: resolvers.hybridArraysIntersection,
enum: resolvers.arraysIntersection,
minLength: resolvers.maxNumber,
maxLength: resolvers.minNumber,
minimum: resolvers.maxNumber,
maximum: resolvers.minNumber,
multipleOf: resolvers.commonMultiple,
exclusiveMinimum: resolvers.maxNumber,
exclusiveMaximum: resolvers.minNumber,
minItems: resolvers.maxNumber,
maxItems: resolvers.minNumber,
maxProperties: resolvers.minNumber,
minProperties: resolvers.maxNumber,
const: resolvers.allEqual,
default: resolvers.allEqual,
format: resolvers.allEqual,
required: resolvers.arraysUnion,
properties: mergeProperties,
patternProperties: mergeObjects,
additionalProperties: mergeSchemasResolver,
items: mergeItems,
additionalItems: mergeAdditionalItems,
definitions: mergeObjects,
$defs: mergeObjects,
nullable: resolvers.booleanAnd,
oneOf: mergeOneOf,
anyOf: mergeOneOf,
allOf: resolvers.arraysUnion,
not: mergeSchemasResolver,
if: mergeIfThenElseSchemas,
then: resolvers.skip,
else: resolvers.skip,
dependencies: mergeDependencies,
dependentRequired: mergeDependencies,
dependentSchemas: mergeObjects,
propertyNames: mergeSchemasResolver,
uniqueItems: resolvers.booleanOr,
contains: mergeSchemasResolver
}
function mergeSchemasResolver (keyword, values, mergedSchema, schemas, options) {
mergedSchema[keyword] = _mergeSchemas(values, options)
}
function cartesianProduct (arrays) {
let result = [[]]
for (const array of arrays) {
const temp = []
for (const x of result) {
for (const y of array) {
temp.push([...x, y])
}
}
result = temp
}
return result
}
function mergeOneOf (keyword, values, mergedSchema, schemas, options) {
if (values.length === 1) {
mergedSchema[keyword] = values[0]
return
}
const product = cartesianProduct(values)
const mergedOneOf = []
for (const combination of product) {
try {
const mergedSchema = _mergeSchemas(combination, options)
if (mergedSchema !== undefined) {
mergedOneOf.push(mergedSchema)
}
} catch (error) {
// If this combination is not valid, we can ignore it.
if (error instanceof errors.MergeError) continue
throw error
}
}
mergedSchema[keyword] = mergedOneOf
}
function getSchemaForItem (schema, index) {
const { items, additionalItems } = schema
if (Array.isArray(items)) {
if (index < items.length) {
return items[index]
}
return additionalItems
}
if (items !== undefined) {
return items
}
return additionalItems
}
function mergeItems (keyword, values, mergedSchema, schemas, options) {
let maxArrayItemsLength = 0
for (const itemsSchema of values) {
if (Array.isArray(itemsSchema)) {
maxArrayItemsLength = Math.max(maxArrayItemsLength, itemsSchema.length)
}
}
if (maxArrayItemsLength === 0) {
mergedSchema[keyword] = _mergeSchemas(values, options)
return
}
const mergedItemsSchemas = []
for (let i = 0; i < maxArrayItemsLength; i++) {
const indexItemSchemas = []
for (const schema of schemas) {
const itemSchema = getSchemaForItem(schema, i)
if (itemSchema !== undefined) {
indexItemSchemas.push(itemSchema)
}
}
mergedItemsSchemas[i] = _mergeSchemas(indexItemSchemas, options)
}
mergedSchema[keyword] = mergedItemsSchemas
}
function mergeAdditionalItems (keyword, values, mergedSchema, schemas, options) {
let hasArrayItems = false
for (const schema of schemas) {
if (Array.isArray(schema.items)) {
hasArrayItems = true
break
}
}
if (!hasArrayItems) {
mergedSchema[keyword] = _mergeSchemas(values, options)
return
}
const mergedAdditionalItemsSchemas = []
for (const schema of schemas) {
let additionalItemsSchema = schema.additionalItems
if (
additionalItemsSchema === undefined &&
!Array.isArray(schema.items)
) {
additionalItemsSchema = schema.items
}
if (additionalItemsSchema !== undefined) {
mergedAdditionalItemsSchemas.push(additionalItemsSchema)
}
}
mergedSchema[keyword] = _mergeSchemas(mergedAdditionalItemsSchemas, options)
}
function getSchemaForProperty (schema, propertyName) {
const { properties, patternProperties, additionalProperties } = schema
if (properties?.[propertyName] !== undefined) {
return properties[propertyName]
}
for (const pattern of Object.keys(patternProperties ?? {})) {
const regexp = new RegExp(pattern)
if (regexp.test(propertyName)) {
return patternProperties[pattern]
}
}
return additionalProperties
}
function mergeProperties (keyword, values, mergedSchema, schemas, options) {
const foundProperties = {}
for (const currentSchema of schemas) {
const properties = currentSchema.properties ?? {}
for (const propertyName of Object.keys(properties)) {
if (foundProperties[propertyName] !== undefined) continue
const propertySchema = properties[propertyName]
foundProperties[propertyName] = [propertySchema]
for (const anotherSchema of schemas) {
if (currentSchema === anotherSchema) continue
const propertySchema = getSchemaForProperty(anotherSchema, propertyName)
if (propertySchema !== undefined) {
foundProperties[propertyName].push(propertySchema)
}
}
}
}
const mergedProperties = {}
for (const property of Object.keys(foundProperties)) {
const propertySchemas = foundProperties[property]
mergedProperties[property] = _mergeSchemas(propertySchemas, options)
}
mergedSchema[keyword] = mergedProperties
}
function mergeObjects (keyword, values, mergedSchema, schemas, options) {
const objectsProperties = {}
for (const properties of values) {
for (const propertyName of Object.keys(properties)) {
if (objectsProperties[propertyName] === undefined) {
objectsProperties[propertyName] = []
}
objectsProperties[propertyName].push(properties[propertyName])
}
}
const mergedProperties = {}
for (const propertyName of Object.keys(objectsProperties)) {
const propertySchemas = objectsProperties[propertyName]
const mergedPropertySchema = _mergeSchemas(propertySchemas, options)
mergedProperties[propertyName] = mergedPropertySchema
}
mergedSchema[keyword] = mergedProperties
}
function mergeIfThenElseSchemas (keyword, values, mergedSchema, schemas, options) {
for (let i = 0; i < schemas.length; i++) {
const subSchema = {
if: schemas[i].if,
then: schemas[i].then,
else: schemas[i].else
}
if (subSchema.if === undefined) continue
if (mergedSchema.if === undefined) {
mergedSchema.if = subSchema.if
if (subSchema.then !== undefined) {
mergedSchema.then = subSchema.then
}
if (subSchema.else !== undefined) {
mergedSchema.else = subSchema.else
}
continue
}
if (mergedSchema.then !== undefined) {
mergedSchema.then = _mergeSchemas([mergedSchema.then, subSchema], options)
}
if (mergedSchema.else !== undefined) {
mergedSchema.else = _mergeSchemas([mergedSchema.else, subSchema], options)
}
}
}
function mergeDependencies (keyword, values, mergedSchema) {
const mergedDependencies = {}
for (const dependencies of values) {
for (const propertyName of Object.keys(dependencies)) {
if (mergedDependencies[propertyName] === undefined) {
mergedDependencies[propertyName] = []
}
const mergedPropertyDependencies = mergedDependencies[propertyName]
for (const propertyDependency of dependencies[propertyName]) {
if (!mergedPropertyDependencies.includes(propertyDependency)) {
mergedPropertyDependencies.push(propertyDependency)
}
}
}
}
mergedSchema[keyword] = mergedDependencies
}
function _mergeSchemas (schemas, options) {
if (schemas.length === 0) return {}
if (schemas.length === 1) return schemas[0]
const mergedSchema = {}
const keywords = {}
let allSchemasAreTrue = true
for (const schema of schemas) {
if (schema === false) return false
if (schema === true) continue
allSchemasAreTrue = false
for (const keyword of Object.keys(schema)) {
if (keywords[keyword] === undefined) {
keywords[keyword] = []
}
keywords[keyword].push(schema[keyword])
}
}
if (allSchemasAreTrue) return true
for (const keyword of Object.keys(keywords)) {
const keywordValues = keywords[keyword]
const resolver = options.resolvers[keyword] ?? options.defaultResolver
resolver(keyword, keywordValues, mergedSchema, schemas, options)
}
return mergedSchema
}
function defaultResolver (keyword, values, mergedSchema, schemas, options) {
const onConflict = options.onConflict ?? 'throw'
if (values.length === 1 || onConflict === 'first') {
mergedSchema[keyword] = values[0]
return
}
let allValuesEqual = true
for (let i = 1; i < values.length; i++) {
if (!deepEqual(values[i], values[0])) {
allValuesEqual = false
break
}
}
if (allValuesEqual) {
mergedSchema[keyword] = values[0]
return
}
if (onConflict === 'throw') {
throw new errors.ResolverNotFoundError(keyword, values)
}
if (onConflict === 'skip') {
return
}
throw new errors.InvalidOnConflictOptionError(onConflict)
}
function mergeSchemas (schemas, options = {}) {
if (options.defaultResolver === undefined) {
options.defaultResolver = defaultResolver
}
options.resolvers = { ...keywordsResolvers, ...options.resolvers }
const mergedSchema = _mergeSchemas(schemas, options)
return mergedSchema
}
module.exports = { mergeSchemas, keywordsResolvers, defaultResolver, ...errors }
/***/ }),
/***/ 55002:
/***/ ((module) => {
"use strict";
class MergeError extends Error {
constructor (keyword, schemas) {
super()
this.name = 'JsonSchemaMergeError'
this.code = 'JSON_SCHEMA_MERGE_ERROR'
this.message = `Failed to merge "${keyword}" keyword schemas.`
this.schemas = schemas
}
}
class ResolverNotFoundError extends Error {
constructor (keyword, schemas) {
super()
this.name = 'JsonSchemaMergeError'
this.code = 'JSON_SCHEMA_MERGE_ERROR'
this.message = `Resolver for "${keyword}" keyword not found.`
this.schemas = schemas
}
}
class InvalidOnConflictOptionError extends Error {
constructor (onConflict) {
super()
this.name = 'JsonSchemaMergeError'
this.code = 'JSON_SCHEMA_MERGE_ERROR'
this.message = `Invalid "onConflict" option: "${onConflict}".`
}
}
module.exports = {
MergeError,
ResolverNotFoundError,
InvalidOnConflictOptionError
}
/***/ }),
/***/ 99616:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const deepEqual = __nccwpck_require__(28206)
const { MergeError } = __nccwpck_require__(55002)
function _arraysIntersection (arrays) {
let intersection = arrays[0]
for (let i = 1; i < arrays.length; i++) {
intersection = intersection.filter(
value => arrays[i].includes(value)
)
}
return intersection
}
function arraysIntersection (keyword, values, mergedSchema) {
const intersection = _arraysIntersection(values)
if (intersection.length === 0) {
throw new MergeError(keyword, values)
}
mergedSchema[keyword] = intersection
}
function hybridArraysIntersection (keyword, values, mergedSchema) {
for (let i = 0; i < values.length; i++) {
if (!Array.isArray(values[i])) {
values[i] = [values[i]]
}
}
const intersection = _arraysIntersection(values)
if (intersection.length === 0) {
throw new MergeError(keyword, values)
}
if (intersection.length === 1) {
mergedSchema[keyword] = intersection[0]
} else {
mergedSchema[keyword] = intersection
}
}
function arraysUnion (keyword, values, mergedSchema) {
const union = []
for (const array of values) {
for (const value of array) {
if (!union.includes(value)) {
union.push(value)
}
}
}
mergedSchema[keyword] = union
}
function minNumber (keyword, values, mergedSchema) {
mergedSchema[keyword] = Math.min(...values)
}
function maxNumber (keyword, values, mergedSchema) {
mergedSchema[keyword] = Math.max(...values)
}
function commonMultiple (keyword, values, mergedSchema) {
const gcd = (a, b) => (!b ? a : gcd(b, a % b))
const lcm = (a, b) => (a * b) / gcd(a, b)
let scale = 1
for (const value of values) {
while (value * scale % 1 !== 0) {
scale *= 10
}
}
let multiple = values[0] * scale
for (const value of values) {
multiple = lcm(multiple, value * scale)
}
mergedSchema[keyword] = multiple / scale
}
function allEqual (keyword, values, mergedSchema) {
const firstValue = values[0]
for (let i = 1; i < values.length; i++) {
if (!deepEqual(values[i], firstValue)) {
throw new MergeError(keyword, values)
}
}
mergedSchema[keyword] = firstValue
}
function skip () {}
function booleanAnd (keyword, values, mergedSchema) {
for (const value of values) {
if (value === false) {
mergedSchema[keyword] = false
return
}
}
mergedSchema[keyword] = true
}
function booleanOr (keyword, values, mergedSchema) {
for (const value of values) {
if (value === true) {
mergedSchema[keyword] = true
return
}
}
mergedSchema[keyword] = false
}
module.exports = {
arraysIntersection,
hybridArraysIntersection,
arraysUnion,
minNumber,
maxNumber,
commonMultiple,
allEqual,
booleanAnd,
booleanOr,
skip
}
/***/ }),
/***/ 4488:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastq = __nccwpck_require__(7340)
const EE = (__nccwpck_require__(15673).EventEmitter)
const inherits = (__nccwpck_require__(47261).inherits)
const {
AVV_ERR_EXPOSE_ALREADY_DEFINED,
AVV_ERR_CALLBACK_NOT_FN,
AVV_ERR_ROOT_PLG_BOOTED,
AVV_ERR_READY_TIMEOUT,
AVV_ERR_ATTRIBUTE_ALREADY_DEFINED
} = __nccwpck_require__(64248)
const {
kAvvio,
kIsOnCloseHandler
} = __nccwpck_require__(74414)
const { TimeTree } = __nccwpck_require__(52218)
const { Plugin } = __nccwpck_require__(50244)
const { debug } = __nccwpck_require__(36472)
const { validatePlugin } = __nccwpck_require__(74382)
const { isBundledOrTypescriptPlugin } = __nccwpck_require__(84316)
const { isPromiseLike } = __nccwpck_require__(53186)
const { thenify } = __nccwpck_require__(23103)
const { executeWithThenable } = __nccwpck_require__(75971)
function Boot (server, opts, done) {
if (typeof server === 'function' && arguments.length === 1) {
done = server
opts = {}
server = null
}
if (typeof opts === 'function') {
done = opts
opts = {}
}
opts = opts || {}
opts.autostart = opts.autostart !== false
opts.timeout = Number(opts.timeout) || 0
opts.expose = opts.expose || {}
if (!new.target) {
return new Boot(server, opts, done)
}
this._server = server || this
this._opts = opts
if (server) {
this._expose()
}
/**
* @type {Array<Plugin>}
*/
this._current = []
this._error = null
this._lastUsed = null
this.setMaxListeners(0)
if (done) {
this.once('start', done)
}
this.started = false
this.booted = false
this.pluginTree = new TimeTree()
this._readyQ = fastq(this, callWithCbOrNextTick, 1)
this._readyQ.pause()
this._readyQ.drain = () => {
this.emit('start')
// nooping this, we want to emit start only once
this._readyQ.drain = noop
}
this._closeQ = fastq(this, closeWithCbOrNextTick, 1)
this._closeQ.pause()
this._closeQ.drain = () => {
this.emit('close')
// nooping this, we want to emit close only once
this._closeQ.drain = noop
}
this._doStart = null
const instance = this
this._root = new Plugin(fastq(this, this._loadPluginNextTick, 1), function root (server, opts, done) {
instance._doStart = done
opts.autostart && instance.start()
}, opts, false, 0)
this._trackPluginLoading(this._root)
this._loadPlugin(this._root, (err) => {
debug('root plugin ready')
try {
this.emit('preReady')
this._root = null
} catch (preReadyError) {
err = err || this._error || preReadyError
}
if (err) {
this._error = err
if (this._readyQ.length() === 0) {
throw err
}
} else {
this.booted = true
}
this._readyQ.resume()
})
}
inherits(Boot, EE)
Boot.prototype.start = function () {
this.started = true
// we need to wait any call to use() to happen
process.nextTick(this._doStart)
return this
}
// allows to override the instance of a server, given a plugin
Boot.prototype.override = function (server, func, opts) {
return server
}
Boot.prototype[kAvvio] = true
// load a plugin
Boot.prototype.use = function (plugin, opts) {
this._lastUsed = this._addPlugin(plugin, opts, false)
return this
}
Boot.prototype._loadRegistered = function () {
const plugin = this._current[0]
const weNeedToStart = !this.started && !this.booted
// if the root plugin is not loaded, let's resume that
// so one can use after() before calling ready
if (weNeedToStart) {
process.nextTick(() => this._root.queue.resume())
}
if (!plugin) {
return Promise.resolve()
}
return plugin.loadedSoFar()
}
Object.defineProperty(Boot.prototype, 'then', { get: thenify })
Boot.prototype._addPlugin = function (pluginFn, opts, isAfter) {
if (isBundledOrTypescriptPlugin(pluginFn)) {
pluginFn = pluginFn.default
}
validatePlugin(pluginFn)
opts = opts || {}
if (this.booted) {
throw new AVV_ERR_ROOT_PLG_BOOTED()
}
// we always add plugins to load at the current element
const current = this._current[0]
let timeout = this._opts.timeout
if (!current.loaded && current.timeout > 0) {
const delta = Date.now() - current.startTime
// We need to decrease it by 3ms to make sure the internal timeout
// is triggered earlier than the parent
timeout = current.timeout - (delta + 3)
}
const plugin = new Plugin(fastq(this, this._loadPluginNextTick, 1), pluginFn, opts, isAfter, timeout)
this._trackPluginLoading(plugin)
if (current.loaded) {
throw new Error(plugin.name, current.name)
}
// we add the plugin to be loaded at the end of the current queue
current.enqueue(plugin, (err) => { err && (this._error = err) })
return plugin
}
Boot.prototype._expose = function _expose () {
const instance = this
const server = instance._server
const {
use: useKey = 'use',
after: afterKey = 'after',
ready: readyKey = 'ready',
onClose: onCloseKey = 'onClose',
close: closeKey = 'close'
} = this._opts.expose
if (server[useKey]) {
throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(useKey, 'use')
}
server[useKey] = function (fn, opts) {
instance.use(fn, opts)
return this
}
if (server[afterKey]) {
throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(afterKey, 'after')
}
server[afterKey] = function (func) {
if (typeof func !== 'function') {
return instance._loadRegistered()
}
instance.after(encapsulateThreeParam(func, this))
return this
}
if (server[readyKey]) {
throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(readyKey, 'ready')
}
server[readyKey] = function (func) {
if (func && typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN(readyKey, typeof func)
}
return instance.ready(func ? encapsulateThreeParam(func, this) : undefined)
}
if (server[onCloseKey]) {
throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(onCloseKey, 'onClose')
}
server[onCloseKey] = function (func) {
if (typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN(onCloseKey, typeof func)
}
instance.onClose(encapsulateTwoParam(func, this))
return this
}
if (server[closeKey]) {
throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(closeKey, 'close')
}
server[closeKey] = function (func) {
if (func && typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN(closeKey, typeof func)
}
if (func) {
instance.close(encapsulateThreeParam(func, this))
return this
}
// this is a Promise
return instance.close()
}
if (server.then) {
throw new AVV_ERR_ATTRIBUTE_ALREADY_DEFINED('then')
}
Object.defineProperty(server, 'then', { get: thenify.bind(instance) })
server[kAvvio] = true
}
Boot.prototype.after = function (func) {
if (!func) {
return this._loadRegistered()
}
this._addPlugin(_after.bind(this), {}, true)
function _after (s, opts, done) {
callWithCbOrNextTick.call(this, func, done)
}
return this
}
Boot.prototype.onClose = function (func) {
// this is used to distinguish between onClose and close handlers
// because they share the same queue but must be called with different signatures
if (typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN('onClose', typeof func)
}
func[kIsOnCloseHandler] = true
this._closeQ.unshift(func, (err) => { err && (this._error = err) })
return this
}
Boot.prototype.close = function (func) {
let promise
if (func) {
if (typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN('close', typeof func)
}
} else {
promise = new Promise(function (resolve, reject) {
func = function (err) {
if (err) {
return reject(err)
}
resolve()
}
})
}
this.ready(() => {
this._error = null
this._closeQ.push(func)
process.nextTick(this._closeQ.resume.bind(this._closeQ))
})
return promise
}
Boot.prototype.ready = function (func) {
if (func) {
if (typeof func !== 'function') {
throw new AVV_ERR_CALLBACK_NOT_FN('ready', typeof func)
}
this._readyQ.push(func)
queueMicrotask(this.start.bind(this))
return
}
return new Promise((resolve, reject) => {
this._readyQ.push(readyPromiseCB)
this.start()
/**
* The `encapsulateThreeParam` let callback function
* bind to the right server instance.
* In promises we need to track the last server
* instance loaded, the first one in the _current queue.
*/
const relativeContext = this._current[0].server
function readyPromiseCB (err, context, done) {
// the context is always binded to the root server
if (err) {
reject(err)
} else {
resolve(relativeContext)
}
process.nextTick(done)
}
})
}
/**
* @param {Plugin} plugin
* @returns {void}
*/
Boot.prototype._trackPluginLoading = function (plugin) {
const parentName = this._current[0]?.name || null
plugin.once('start', (serverName, funcName, time) => {
const nodeId = this.pluginTree.start(parentName || null, funcName, time)
plugin.once('loaded', (serverName, funcName, time) => {
this.pluginTree.stop(nodeId, time)
})
})
}
Boot.prototype.prettyPrint = function () {
return this.pluginTree.prettyPrint()
}
Boot.prototype.toJSON = function () {
return this.pluginTree.toJSON()
}
/**
* @callback LoadPluginCallback
* @param {Error} [err]
*/
/**
* Load a plugin
*
* @param {Plugin} plugin
* @param {LoadPluginCallback} callback
*/
Boot.prototype._loadPlugin = function (plugin, callback) {
const instance = this
if (isPromiseLike(plugin.func)) {
plugin.func.then((fn) => {
if (typeof fn.default === 'function') {
fn = fn.default
}
plugin.func = fn
this._loadPlugin(plugin, callback)
}, callback)
return
}
const last = instance._current[0]
// place the plugin at the top of _current
instance._current.unshift(plugin)
if (instance._error && !plugin.isAfter) {
debug('skipping loading of plugin as instance errored and it is not an after', plugin.name)
process.nextTick(execCallback)
return
}
let server = (last && last.server) || instance._server
if (!plugin.isAfter) {
// Skip override for after
try {
server = instance.override(server, plugin.func, plugin.options)
} catch (overrideErr) {
debug('override errored', plugin.name)
return execCallback(overrideErr)
}
}
plugin.exec(server, execCallback)
function execCallback (err) {
plugin.finish(err, (err) => {
instance._current.shift()
callback(err)
})
}
}
/**
* Delays plugin loading until the next tick to ensure any bound `_after` callbacks have a chance
* to run prior to executing the next plugin
*/
Boot.prototype._loadPluginNextTick = function (plugin, callback) {
process.nextTick(this._loadPlugin.bind(this), plugin, callback)
}
function noop () { }
function callWithCbOrNextTick (func, cb) {
const context = this._server
const err = this._error
// with this the error will appear just in the next after/ready callback
this._error = null
if (func.length === 0) {
this._error = err
executeWithThenable(func, [], cb)
} else if (func.length === 1) {
executeWithThenable(func, [err], cb)
} else {
if (this._opts.timeout === 0) {
const wrapCb = (err) => {
this._error = err
cb(this._error)
}
if (func.length === 2) {
func(err, wrapCb)
} else {
func(err, context, wrapCb)
}
} else {
timeoutCall.call(this, func, err, context, cb)
}
}
}
function timeoutCall (func, rootErr, context, cb) {
const name = func.name
debug('setting up ready timeout', name, this._opts.timeout)
let timer = setTimeout(() => {
debug('timed out', name)
timer = null
const toutErr = new AVV_ERR_READY_TIMEOUT(name)
toutErr.fn = func
this._error = toutErr
cb(toutErr)
}, this._opts.timeout)
if (func.length === 2) {
func(rootErr, timeoutCb.bind(this))
} else {
func(rootErr, context, timeoutCb.bind(this))
}
function timeoutCb (err) {
if (timer) {
clearTimeout(timer)
this._error = err
cb(this._error)
} else {
// timeout has been triggered
// can not call cb twice
}
}
}
function closeWithCbOrNextTick (func, cb) {
const context = this._server
const isOnCloseHandler = func[kIsOnCloseHandler]
if (func.length === 0 || func.length === 1) {
let promise
if (isOnCloseHandler) {
promise = func(context)
} else {
promise = func(this._error)
}
if (promise && typeof promise.then === 'function') {
debug('resolving close/onClose promise')
promise.then(
() => process.nextTick(cb),
(e) => process.nextTick(cb, e))
} else {
process.nextTick(cb)
}
} else if (func.length === 2) {
if (isOnCloseHandler) {
func(context, cb)
} else {
func(this._error, cb)
}
} else {
if (isOnCloseHandler) {
func(context, cb)
} else {
func(this._error, context, cb)
}
}
}
function encapsulateTwoParam (func, that) {
return _encapsulateTwoParam.bind(that)
function _encapsulateTwoParam (context, cb) {
let res
if (func.length === 0) {
res = func()
if (res && res.then) {
res.then(function () {
process.nextTick(cb)
}, cb)
} else {
process.nextTick(cb)
}
} else if (func.length === 1) {
res = func(this)
if (res && res.then) {
res.then(function () {
process.nextTick(cb)
}, cb)
} else {
process.nextTick(cb)
}
} else {
func(this, cb)
}
}
}
function encapsulateThreeParam (func, that) {
return _encapsulateThreeParam.bind(that)
function _encapsulateThreeParam (err, cb) {
let res
if (!func) {
process.nextTick(cb)
} else if (func.length === 0) {
res = func()
if (res && res.then) {
res.then(function () {
process.nextTick(cb, err)
}, cb)
} else {
process.nextTick(cb, err)
}
} else if (func.length === 1) {
res = func(err)
if (res && res.then) {
res.then(function () {
process.nextTick(cb)
}, cb)
} else {
process.nextTick(cb)
}
} else if (func.length === 2) {
func(err, cb)
} else {
func(err, this, cb)
}
}
}
module.exports = Boot
module.exports.express = function (app) {
return Boot(app, {
expose: {
use: 'load'
}
})
}
/***/ }),
/***/ 22757:
/***/ ((module) => {
"use strict";
/**
* @callback PromiseResolve
* @param {any|PromiseLike<any>} value
* @returns {void}
*/
/**
* @callback PromiseReject
* @param {any} reason
* @returns {void}
*/
/**
* @typedef PromiseObject
* @property {Promise} promise
* @property {PromiseResolve} resolve
* @property {PromiseReject} reject
*/
/**
* @returns {PromiseObject}
*/
function createPromise () {
/**
* @type {PromiseObject}
*/
const obj = {
resolve: null,
reject: null,
promise: null
}
obj.promise = new Promise((resolve, reject) => {
obj.resolve = resolve
obj.reject = reject
})
return obj
}
module.exports = {
createPromise
}
/***/ }),
/***/ 36472:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { debuglog } = __nccwpck_require__(47261)
/**
* @callback DebugLogger
* @param {string} msg
* @param {...unknown} param
* @returns {void}
*/
/**
* @type {DebugLogger}
*/
const debug = debuglog('avvio')
module.exports = {
debug
}
/***/ }),
/***/ 64248:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { createError } = __nccwpck_require__(22259)
module.exports = {
AVV_ERR_EXPOSE_ALREADY_DEFINED: createError(
'AVV_ERR_EXPOSE_ALREADY_DEFINED',
"'%s' is already defined, specify an expose option for '%s'"
),
AVV_ERR_ATTRIBUTE_ALREADY_DEFINED: createError(
'AVV_ERR_ATTRIBUTE_ALREADY_DEFINED',
"'%s' is already defined"
),
AVV_ERR_CALLBACK_NOT_FN: createError(
'AVV_ERR_CALLBACK_NOT_FN',
"Callback for '%s' hook is not a function. Received: '%s'"
),
AVV_ERR_PLUGIN_NOT_VALID: createError(
'AVV_ERR_PLUGIN_NOT_VALID',
"Plugin must be a function or a promise. Received: '%s'"
),
AVV_ERR_ROOT_PLG_BOOTED: createError(
'AVV_ERR_ROOT_PLG_BOOTED',
'Root plugin has already booted'
),
AVV_ERR_PARENT_PLG_LOADED: createError(
'AVV_ERR_PARENT_PLG_LOADED',
"Impossible to load '%s' plugin because the parent '%s' was already loaded"
),
AVV_ERR_READY_TIMEOUT: createError(
'AVV_ERR_READY_TIMEOUT',
"Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise"
),
AVV_ERR_PLUGIN_EXEC_TIMEOUT: createError(
'AVV_ERR_PLUGIN_EXEC_TIMEOUT',
"Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise"
)
}
/***/ }),
/***/ 75971:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { isPromiseLike } = __nccwpck_require__(53186)
const { kAvvio } = __nccwpck_require__(74414)
/**
* @callback ExecuteWithThenableCallback
* @param {Error} error
* @returns {void}
*/
/**
* @param {Function} func
* @param {Array<any>} args
* @param {ExecuteWithThenableCallback} [callback]
*/
function executeWithThenable (func, args, callback) {
const result = func.apply(func, args)
if (isPromiseLike(result) && !result[kAvvio]) {
// process promise but not avvio mock thenable
result.then(() => process.nextTick(callback), (error) => process.nextTick(callback, error))
} else if (callback) {
process.nextTick(callback)
}
}
module.exports = {
executeWithThenable
}
/***/ }),
/***/ 74436:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// this symbol is assigned by fastify-plugin
const { kPluginMeta } = __nccwpck_require__(74414)
/**
* @param {function} plugin
* @param {object} [options]
* @param {string} [options.name]
* @returns {string}
*/
function getPluginName (plugin, options) {
// use explicit function metadata if set
if (plugin[kPluginMeta] && plugin[kPluginMeta].name) {
return plugin[kPluginMeta].name
}
// use explicit name option if set
if (options && options.name) {
return options.name
}
// determine from the function
if (plugin.name) {
return plugin.name
} else {
// takes the first two lines of the function if nothing else works
return plugin.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ')
}
}
module.exports = {
getPluginName
}
/***/ }),
/***/ 84316:
/***/ ((module) => {
"use strict";
/**
* bundled or typescript plugin
* @typedef {object} BundledOrTypescriptPlugin
* @property {function} default
*/
/**
* @param {any} maybeBundledOrTypescriptPlugin
* @returns {plugin is BundledOrTypescriptPlugin}
*/
function isBundledOrTypescriptPlugin (maybeBundledOrTypescriptPlugin) {
return (
maybeBundledOrTypescriptPlugin !== null &&
typeof maybeBundledOrTypescriptPlugin === 'object' &&
typeof maybeBundledOrTypescriptPlugin.default === 'function'
)
}
module.exports = {
isBundledOrTypescriptPlugin
}
/***/ }),
/***/ 53186:
/***/ ((module) => {
"use strict";
/**
* @param {any} maybePromiseLike
* @returns {maybePromiseLike is PromiseLike}
*/
function isPromiseLike (maybePromiseLike) {
return (
maybePromiseLike !== null &&
typeof maybePromiseLike === 'object' &&
typeof maybePromiseLike.then === 'function'
)
}
module.exports = {
isPromiseLike
}
/***/ }),
/***/ 50244:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { EventEmitter } = __nccwpck_require__(15673)
const { inherits } = __nccwpck_require__(47261)
const { debug } = __nccwpck_require__(36472)
const { createPromise } = __nccwpck_require__(22757)
const { AVV_ERR_PLUGIN_EXEC_TIMEOUT } = __nccwpck_require__(64248)
const { getPluginName } = __nccwpck_require__(74436)
const { isPromiseLike } = __nccwpck_require__(53186)
/**
* @param {*} queue
* @param {*} func
* @param {*} options
* @param {boolean} isAfter
* @param {number} [timeout]
*/
function Plugin (queue, func, options, isAfter, timeout) {
this.queue = queue
this.func = func
this.options = options
/**
* @type {boolean}
*/
this.isAfter = isAfter
/**
* @type {number}
*/
this.timeout = timeout
/**
* @type {boolean}
*/
this.started = false
/**
* @type {string}
*/
this.name = getPluginName(func, options)
this.queue.pause()
/**
* @type {Error|null}
*/
this._error = null
/**
* @type {boolean}
*/
this.loaded = false
this._promise = null
this.startTime = null
}
inherits(Plugin, EventEmitter)
/**
* @callback ExecCallback
* @param {Error|null} execErr
* @returns
*/
/**
*
* @param {*} server
* @param {ExecCallback} callback
* @returns
*/
Plugin.prototype.exec = function (server, callback) {
debug('exec', this.name)
this.server = server
const func = this.func
const name = this.name
let completed = false
this.options = typeof this.options === 'function' ? this.options(this.server) : this.options
let timer = null
/**
* @param {Error} [execErr]
*/
const done = (execErr) => {
if (completed) {
debug('loading complete', name)
return
}
this._error = execErr
if (execErr) {
debug('exec errored', name)
} else {
debug('exec completed', name)
}
completed = true
if (timer) {
clearTimeout(timer)
}
callback(execErr)
}
if (this.timeout > 0) {
debug('setting up timeout', name, this.timeout)
timer = setTimeout(function () {
debug('timed out', name)
timer = null
const readyTimeoutErr = new AVV_ERR_PLUGIN_EXEC_TIMEOUT(name)
// TODO Remove reference to function
readyTimeoutErr.fn = func
done(readyTimeoutErr)
}, this.timeout)
}
this.started = true
this.startTime = Date.now()
this.emit('start', this.server ? this.server.name : null, this.name, Date.now())
const maybePromiseLike = func(this.server, this.options, done)
if (isPromiseLike(maybePromiseLike)) {
debug('exec: resolving promise', name)
maybePromiseLike.then(
() => process.nextTick(done),
(e) => process.nextTick(done, e))
}
}
/**
* @returns {Promise}
*/
Plugin.prototype.loadedSoFar = function () {
debug('loadedSoFar', this.name)
if (this.loaded) {
return Promise.resolve()
}
const setup = () => {
this.server.after((afterErr, callback) => {
this._error = afterErr
this.queue.pause()
if (this._promise) {
if (afterErr) {
debug('rejecting promise', this.name, afterErr)
this._promise.reject(afterErr)
} else {
debug('resolving promise', this.name)
this._promise.resolve()
}
this._promise = null
}
process.nextTick(callback, afterErr)
})
this.queue.resume()
}
let res
if (!this._promise) {
this._promise = createPromise()
res = this._promise.promise
if (!this.server) {
this.on('start', setup)
} else {
setup()
}
} else {
res = Promise.resolve()
}
return res
}
/**
* @callback EnqueueCallback
* @param {Error|null} enqueueErr
* @param {Plugin} result
*/
/**
*
* @param {Plugin} plugin
* @param {EnqueueCallback} callback
*/
Plugin.prototype.enqueue = function (plugin, callback) {
debug('enqueue', this.name, plugin.name)
this.emit('enqueue', this.server ? this.server.name : null, this.name, Date.now())
this.queue.push(plugin, callback)
}
/**
* @callback FinishCallback
* @param {Error|null} finishErr
* @returns
*/
/**
*
* @param {Error|null} err
* @param {FinishCallback} callback
* @returns
*/
Plugin.prototype.finish = function (err, callback) {
debug('finish', this.name, err)
const done = () => {
if (this.loaded) {
return
}
debug('loaded', this.name)
this.emit('loaded', this.server ? this.server.name : null, this.name, Date.now())
this.loaded = true
callback(err)
}
if (err) {
if (this._promise) {
this._promise.reject(err)
this._promise = null
}
done()
return
}
const check = () => {
debug('check', this.name, this.queue.length(), this.queue.running(), this._promise)
if (this.queue.length() === 0 && this.queue.running() === 0) {
if (this._promise) {
const wrap = () => {
debug('wrap')
queueMicrotask(check)
}
this._promise.resolve()
this._promise.promise.then(wrap, wrap)
this._promise = null
} else {
done()
}
} else {
debug('delayed', this.name)
// finish when the queue of nested plugins to load is empty
this.queue.drain = () => {
debug('drain', this.name)
this.queue.drain = noop
// we defer the check, as a safety net for things
// that might be scheduled in the loading callback
queueMicrotask(check)
}
}
}
queueMicrotask(check)
// we start loading the dependents plugins only once
// the current level is finished
this.queue.resume()
}
function noop () {}
module.exports = {
Plugin
}
/***/ }),
/***/ 74414:
/***/ ((module) => {
"use strict";
// Internal Symbols
const kAvvio = Symbol('avvio.Boot')
const kIsOnCloseHandler = Symbol('isOnCloseHandler')
const kThenifyDoNotWrap = Symbol('avvio.ThenifyDoNotWrap')
const kUntrackNode = Symbol('avvio.TimeTree.untrackNode')
const kTrackNode = Symbol('avvio.TimeTree.trackNode')
const kGetParent = Symbol('avvio.TimeTree.getParent')
const kGetNode = Symbol('avvio.TimeTree.getNode')
const kAddNode = Symbol('avvio.TimeTree.addNode')
// Public Symbols
const kPluginMeta = Symbol.for('plugin-meta')
module.exports = {
kAvvio,
kIsOnCloseHandler,
kThenifyDoNotWrap,
kUntrackNode,
kTrackNode,
kGetParent,
kGetNode,
kAddNode,
kPluginMeta
}
/***/ }),
/***/ 23103:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { debug } = __nccwpck_require__(36472)
const { kThenifyDoNotWrap } = __nccwpck_require__(74414)
/**
* @callback PromiseConstructorLikeResolve
* @param {any} value
* @returns {void}
*/
/**
* @callback PromiseConstructorLikeReject
* @param {reason} error
* @returns {void}
*/
/**
* @callback PromiseConstructorLike
* @param {PromiseConstructorLikeResolve} resolve
* @param {PromiseConstructorLikeReject} reject
* @returns {void}
*/
/**
* @returns {PromiseConstructorLike}
*/
function thenify () {
// If the instance is ready, then there is
// nothing to await. This is true during
// await server.ready() as ready() resolves
// with the server, end we will end up here
// because of automatic promise chaining.
if (this.booted) {
debug('thenify returning undefined because we are already booted')
return
}
// Calling resolve(this._server) would fetch the then
// property on the server, which will lead it here.
// If we do not break the recursion, we will loop
// forever.
if (this[kThenifyDoNotWrap]) {
this[kThenifyDoNotWrap] = false
return
}
debug('thenify')
return (resolve, reject) => {
const p = this._loadRegistered()
return p.then(() => {
this[kThenifyDoNotWrap] = true
return resolve(this._server)
}, reject)
}
}
module.exports = {
thenify
}
/***/ }),
/***/ 52218:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kUntrackNode,
kTrackNode,
kGetParent,
kGetNode,
kAddNode
} = __nccwpck_require__(74414)
/**
* Node of the TimeTree
* @typedef {object} TimeTreeNode
* @property {string} id
* @property {string|null} parent
* @property {string} label
* @property {Array<TimeTreeNode>} nodes
* @property {number} start
* @property {number|undefined} stop
* @property {number|undefined} diff
*/
class TimeTree {
constructor () {
/**
* @type {TimeTreeNode|null} root
* @public
*/
this.root = null
/**
* @type {Map<string, TimeTreeNode>} tableId
* @public
*/
this.tableId = new Map()
/**
* @type {Map<string, Array<TimeTreeNode>>} tableLabel
* @public
*/
this.tableLabel = new Map()
}
/**
* @param {TimeTreeNode} node
*/
[kTrackNode] (node) {
this.tableId.set(node.id, node)
if (this.tableLabel.has(node.label)) {
this.tableLabel.get(node.label).push(node)
} else {
this.tableLabel.set(node.label, [node])
}
}
/**
* @param {TimeTreeNode} node
*/
[kUntrackNode] (node) {
this.tableId.delete(node.id)
const labelNode = this.tableLabel.get(node.label)
labelNode.pop()
if (labelNode.length === 0) {
this.tableLabel.delete(node.label)
}
}
/**
* @param {string} parent
* @returns {TimeTreeNode}
*/
[kGetParent] (parent) {
if (parent === null) {
return null
} else if (this.tableLabel.has(parent)) {
const parentNode = this.tableLabel.get(parent)
return parentNode[parentNode.length - 1]
} else {
return null
}
}
/**
*
* @param {string} nodeId
* @returns {TimeTreeNode}
*/
[kGetNode] (nodeId) {
return this.tableId.get(nodeId)
}
/**
* @param {string} parent
* @param {string} label
* @param {number} start
* @returns {TimeTreeNode["id"]}
*/
[kAddNode] (parent, label, start) {
const parentNode = this[kGetParent](parent)
const isRoot = parentNode === null
if (isRoot) {
this.root = {
parent: null,
id: 'root',
label,
nodes: [],
start,
stop: null,
diff: -1
}
this[kTrackNode](this.root)
return this.root.id
}
const nodeId = `${label}-${Math.random()}`
/**
* @type {TimeTreeNode}
*/
const childNode = {
parent,
id: nodeId,
label,
nodes: [],
start,
stop: null,
diff: -1
}
parentNode.nodes.push(childNode)
this[kTrackNode](childNode)
return nodeId
}
/**
* @param {string} parent
* @param {string} label
* @param {number|undefined} start
* @returns {TimeTreeNode["id"]}
*/
start (parent, label, start = Date.now()) {
return this[kAddNode](parent, label, start)
}
/**
* @param {string} nodeId
* @param {number|undefined} stop
*/
stop (nodeId, stop = Date.now()) {
const node = this[kGetNode](nodeId)
if (node) {
node.stop = stop
node.diff = (node.stop - node.start) || 0
this[kUntrackNode](node)
}
}
/**
* @returns {TimeTreeNode}
*/
toJSON () {
return Object.assign({}, this.root)
}
/**
* @returns {string}
*/
prettyPrint () {
return prettyPrintTimeTree(this.toJSON())
}
}
/**
* @param {TimeTreeNode} obj
* @param {string|undefined} prefix
* @returns {string}
*/
function prettyPrintTimeTree (obj, prefix = '') {
let result = prefix
const nodesCount = obj.nodes.length
const lastIndex = nodesCount - 1
result += `${obj.label} ${obj.diff} ms\n`
for (let i = 0; i < nodesCount; ++i) {
const node = obj.nodes[i]
const prefix_ = prefix + (i === lastIndex ? ' ' : '│ ')
result += prefix
result += (i === lastIndex ? '└─' : '├─')
result += (node.nodes.length === 0 ? '─ ' : '┬ ')
result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2)
}
return result
}
module.exports = {
TimeTree
}
/***/ }),
/***/ 74382:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { AVV_ERR_PLUGIN_NOT_VALID } = __nccwpck_require__(64248)
/**
* @param {any} maybePlugin
* @throws {AVV_ERR_PLUGIN_NOT_VALID}
*
* @returns {asserts plugin is Function|PromiseLike}
*/
function validatePlugin (maybePlugin) {
// validate if plugin is a function or Promise
if (!(maybePlugin && (typeof maybePlugin === 'function' || typeof maybePlugin.then === 'function'))) {
if (Array.isArray(maybePlugin)) {
throw new AVV_ERR_PLUGIN_NOT_VALID('array')
} else if (maybePlugin === null) {
throw new AVV_ERR_PLUGIN_NOT_VALID('null')
} else {
throw new AVV_ERR_PLUGIN_NOT_VALID(typeof maybePlugin)
}
}
}
module.exports = {
validatePlugin
}
/***/ }),
/***/ 2793:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const { RefResolver } = __nccwpck_require__(24060)
const Serializer = __nccwpck_require__(52234)
const Validator = __nccwpck_require__(87737)
const Location = __nccwpck_require__(70731)
const validate = __nccwpck_require__(80898)
const mergeSchemas = __nccwpck_require__(13438)
const SINGLE_TICK = /'/g
let largeArraySize = 2e4
let largeArrayMechanism = 'default'
const validRoundingMethods = [
'floor',
'ceil',
'round',
'trunc'
]
const validLargeArrayMechanisms = [
'default',
'json-stringify'
]
let schemaIdCounter = 0
function isValidSchema (schema, name) {
if (!validate(schema)) {
if (name) {
name = `"${name}" `
} else {
name = ''
}
const first = validate.errors[0]
const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`)
err.errors = isValidSchema.errors
throw err
}
}
function resolveRef (context, location) {
const ref = location.schema.$ref
let hashIndex = ref.indexOf('#')
if (hashIndex === -1) {
hashIndex = ref.length
}
const schemaId = ref.slice(0, hashIndex) || location.schemaId
const jsonPointer = ref.slice(hashIndex) || '#'
const schema = context.refResolver.getSchema(schemaId, jsonPointer)
if (schema === null) {
throw new Error(`Cannot find reference "${ref}"`)
}
const newLocation = new Location(schema, schemaId, jsonPointer)
if (schema.$ref !== undefined) {
return resolveRef(context, newLocation)
}
return newLocation
}
function getMergedLocation (context, mergedSchemaId) {
const mergedSchema = context.refResolver.getSchema(mergedSchemaId, '#')
return new Location(mergedSchema, mergedSchemaId, '#')
}
function getSchemaId (schema, rootSchemaId) {
if (schema.$id && schema.$id.charAt(0) !== '#') {
return schema.$id
}
return rootSchemaId
}
function build (schema, options) {
isValidSchema(schema)
options = options || {}
const context = {
functions: [],
functionsCounter: 0,
functionsNamesBySchema: new Map(),
options,
refResolver: new RefResolver(),
rootSchemaId: schema.$id || `__fjs_root_${schemaIdCounter++}`,
validatorSchemasIds: new Set(),
mergedSchemasIds: new Map()
}
const schemaId = getSchemaId(schema, context.rootSchemaId)
if (!context.refResolver.hasSchema(schemaId)) {
context.refResolver.addSchema(schema, context.rootSchemaId)
}
if (options.schema) {
for (const key in options.schema) {
const schema = options.schema[key]
const schemaId = getSchemaId(schema, key)
if (!context.refResolver.hasSchema(schemaId)) {
isValidSchema(schema, key)
context.refResolver.addSchema(schema, key)
}
}
}
if (options.rounding) {
if (!validRoundingMethods.includes(options.rounding)) {
throw new Error(`Unsupported integer rounding method ${options.rounding}`)
}
}
if (options.largeArrayMechanism) {
if (validLargeArrayMechanisms.includes(options.largeArrayMechanism)) {
largeArrayMechanism = options.largeArrayMechanism
} else {
throw new Error(`Unsupported large array mechanism ${options.largeArrayMechanism}`)
}
}
if (options.largeArraySize) {
if (typeof options.largeArraySize === 'string' && Number.isFinite(Number.parseInt(options.largeArraySize, 10))) {
largeArraySize = Number.parseInt(options.largeArraySize, 10)
} else if (typeof options.largeArraySize === 'number' && Number.isInteger(options.largeArraySize)) {
largeArraySize = options.largeArraySize
} else if (typeof options.largeArraySize === 'bigint') {
largeArraySize = Number(options.largeArraySize)
} else {
throw new Error(`Unsupported large array size. Expected integer-like, got ${typeof options.largeArraySize} with value ${options.largeArraySize}`)
}
}
const location = new Location(schema, context.rootSchemaId)
const code = buildValue(context, location, 'input')
let contextFunctionCode = `
const JSON_STR_BEGIN_OBJECT = '{'
const JSON_STR_END_OBJECT = '}'
const JSON_STR_BEGIN_ARRAY = '['
const JSON_STR_END_ARRAY = ']'
const JSON_STR_COMMA = ','
const JSON_STR_COLONS = ':'
const JSON_STR_QUOTE = '"'
const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT
const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY
const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE
const JSON_STR_NULL = 'null'
`
// If we have only the invocation of the 'anonymous0' function, we would
// basically just wrap the 'anonymous0' function in the 'main' function and
// and the overhead of the intermediate variable 'json'. We can avoid the
// wrapping and the unnecessary memory allocation by aliasing 'anonymous0' to
// 'main'
if (code === 'json += anonymous0(input)') {
contextFunctionCode += `
${context.functions.join('\n')}
const main = anonymous0
return main
`
} else {
contextFunctionCode += `
function main (input) {
let json = ''
${code}
return json
}
${context.functions.join('\n')}
return main
`
}
const serializer = new Serializer(options)
const validator = new Validator(options.ajv)
for (const schemaId of context.validatorSchemasIds) {
const schema = context.refResolver.getSchema(schemaId)
validator.addSchema(schema, schemaId)
const dependencies = context.refResolver.getSchemaDependencies(schemaId)
for (const [schemaId, schema] of Object.entries(dependencies)) {
validator.addSchema(schema, schemaId)
}
}
if (options.debugMode) {
options.mode = 'debug'
}
if (options.mode === 'debug') {
return {
validator,
serializer,
code: `validator\nserializer\n${contextFunctionCode}`,
ajv: validator.ajv
}
}
/* eslint no-new-func: "off" */
const contextFunc = new Function('validator', 'serializer', contextFunctionCode)
if (options.mode === 'standalone') {
const buildStandaloneCode = __nccwpck_require__(23591)
return buildStandaloneCode(contextFunc, context, serializer, validator)
}
return contextFunc(validator, serializer)
}
const objectKeywords = [
'properties',
'required',
'additionalProperties',
'patternProperties',
'maxProperties',
'minProperties',
'dependencies'
]
const arrayKeywords = [
'items',
'additionalItems',
'maxItems',
'minItems',
'uniqueItems',
'contains'
]
const stringKeywords = [
'maxLength',
'minLength',
'pattern'
]
const numberKeywords = [
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum'
]
/**
* Infer type based on keyword in order to generate optimized code
* https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6
*/
function inferTypeByKeyword (schema) {
// eslint-disable-next-line
for (var keyword of objectKeywords) {
if (keyword in schema) return 'object'
}
// eslint-disable-next-line
for (var keyword of arrayKeywords) {
if (keyword in schema) return 'array'
}
// eslint-disable-next-line
for (var keyword of stringKeywords) {
if (keyword in schema) return 'string'
}
// eslint-disable-next-line
for (var keyword of numberKeywords) {
if (keyword in schema) return 'number'
}
return schema.type
}
function buildExtraObjectPropertiesSerializer (context, location, addComma) {
const schema = location.schema
const propertiesKeys = Object.keys(schema.properties || {})
let code = `
const propertiesKeys = ${JSON.stringify(propertiesKeys)}
for (const [key, value] of Object.entries(obj)) {
if (
propertiesKeys.includes(key) ||
value === undefined ||
typeof value === 'function' ||
typeof value === 'symbol'
) continue
`
const patternPropertiesLocation = location.getPropertyLocation('patternProperties')
const patternPropertiesSchema = patternPropertiesLocation.schema
if (patternPropertiesSchema !== undefined) {
for (const propertyKey in patternPropertiesSchema) {
const propertyLocation = patternPropertiesLocation.getPropertyLocation(propertyKey)
code += `
if (/${propertyKey.replace(/\\*\//g, '\\/')}/.test(key)) {
${addComma}
json += serializer.asString(key) + JSON_STR_COLONS
${buildValue(context, propertyLocation, 'value')}
continue
}
`
}
}
const additionalPropertiesLocation = location.getPropertyLocation('additionalProperties')
const additionalPropertiesSchema = additionalPropertiesLocation.schema
if (additionalPropertiesSchema !== undefined) {
if (additionalPropertiesSchema === true) {
code += `
${addComma}
json += serializer.asString(key) + JSON_STR_COLONS + JSON.stringify(value)
`
} else {
const propertyLocation = location.getPropertyLocation('additionalProperties')
code += `
${addComma}
json += serializer.asString(key) + JSON_STR_COLONS
${buildValue(context, propertyLocation, 'value')}
`
}
}
code += `
}
`
return code
}
function buildInnerObject (context, location) {
const schema = location.schema
const propertiesLocation = location.getPropertyLocation('properties')
const requiredProperties = schema.required || []
// Should serialize required properties first
const propertiesKeys = Object.keys(schema.properties || {}).sort(
(key1, key2) => {
const required1 = requiredProperties.includes(key1)
const required2 = requiredProperties.includes(key2)
return required1 === required2 ? 0 : required1 ? -1 : 1
}
)
const hasRequiredProperties = requiredProperties.includes(propertiesKeys[0])
let code = 'let value\n'
for (const key of requiredProperties) {
if (!propertiesKeys.includes(key)) {
const sanitizedKey = JSON.stringify(key)
code += `if (obj[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n`
}
}
code += 'let json = JSON_STR_BEGIN_OBJECT\n'
let addComma = ''
if (!hasRequiredProperties) {
code += 'let addComma = false\n'
addComma = '!addComma && (addComma = true) || (json += JSON_STR_COMMA)'
}
for (const key of propertiesKeys) {
let propertyLocation = propertiesLocation.getPropertyLocation(key)
if (propertyLocation.schema.$ref) {
propertyLocation = resolveRef(context, propertyLocation)
}
const sanitizedKey = JSON.stringify(key)
const defaultValue = propertyLocation.schema.default
const isRequired = requiredProperties.includes(key)
code += `
value = obj[${sanitizedKey}]
if (value !== undefined) {
${addComma}
json += ${JSON.stringify(sanitizedKey + ':')}
${buildValue(context, propertyLocation, 'value')}
}`
if (defaultValue !== undefined) {
code += ` else {
${addComma}
json += ${JSON.stringify(sanitizedKey + ':' + JSON.stringify(defaultValue))}
}
`
} else if (isRequired) {
code += ` else {
throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')
}
`
} else {
code += '\n'
}
if (hasRequiredProperties) {
addComma = 'json += \',\''
}
}
if (schema.patternProperties || schema.additionalProperties) {
code += buildExtraObjectPropertiesSerializer(context, location, addComma)
}
code += `
return json + JSON_STR_END_OBJECT
`
return code
}
function mergeLocations (context, mergedSchemaId, mergedLocations) {
for (let i = 0; i < mergedLocations.length; i++) {
const location = mergedLocations[i]
const schema = location.schema
if (schema.$ref) {
mergedLocations[i] = resolveRef(context, location)
}
}
const mergedSchemas = []
for (const location of mergedLocations) {
const schema = cloneOriginSchema(context, location.schema, location.schemaId)
delete schema.$id
mergedSchemas.push(schema)
}
const mergedSchema = mergeSchemas(mergedSchemas)
const mergedLocation = new Location(mergedSchema, mergedSchemaId)
context.refResolver.addSchema(mergedSchema, mergedSchemaId)
return mergedLocation
}
function cloneOriginSchema (context, schema, schemaId) {
const clonedSchema = Array.isArray(schema) ? [] : {}
if (
schema.$id !== undefined &&
schema.$id.charAt(0) !== '#'
) {
schemaId = schema.$id
}
const mergedSchemaRef = context.mergedSchemasIds.get(schema)
if (mergedSchemaRef) {
context.mergedSchemasIds.set(clonedSchema, mergedSchemaRef)
}
for (const key in schema) {
let value = schema[key]
if (key === '$ref' && typeof value === 'string' && value.charAt(0) === '#') {
value = schemaId + value
}
if (typeof value === 'object' && value !== null) {
value = cloneOriginSchema(context, value, schemaId)
}
clonedSchema[key] = value
}
return clonedSchema
}
function toJSON (variableName) {
return `(${variableName} && typeof ${variableName}.toJSON === 'function')
? ${variableName}.toJSON()
: ${variableName}
`
}
function buildObject (context, location) {
const schema = location.schema
if (context.functionsNamesBySchema.has(schema)) {
return context.functionsNamesBySchema.get(schema)
}
const functionName = generateFuncName(context)
context.functionsNamesBySchema.set(schema, functionName)
let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}
let functionCode = `
`
const nullable = schema.nullable === true
functionCode += `
// ${schemaRef}
function ${functionName} (input) {
const obj = ${toJSON('input')}
${!nullable ? 'if (obj === null) return JSON_STR_EMPTY_OBJECT' : ''}
${buildInnerObject(context, location)}
}
`
context.functions.push(functionCode)
return functionName
}
function buildArray (context, location) {
const schema = location.schema
let itemsLocation = location.getPropertyLocation('items')
itemsLocation.schema = itemsLocation.schema || {}
if (itemsLocation.schema.$ref) {
itemsLocation = resolveRef(context, itemsLocation)
}
const itemsSchema = itemsLocation.schema
if (context.functionsNamesBySchema.has(schema)) {
return context.functionsNamesBySchema.get(schema)
}
const functionName = generateFuncName(context)
context.functionsNamesBySchema.set(schema, functionName)
let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}
let functionCode = `
function ${functionName} (obj) {
// ${schemaRef}
`
const nullable = schema.nullable === true
functionCode += `
${!nullable ? 'if (obj === null) return JSON_STR_EMPTY_ARRAY' : ''}
if (!Array.isArray(obj)) {
throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
}
const arrayLength = obj.length
`
if (!schema.additionalItems && Array.isArray(itemsSchema)) {
functionCode += `
if (arrayLength > ${itemsSchema.length}) {
throw new Error(\`Item at ${itemsSchema.length} does not match schema definition.\`)
}
`
}
if (largeArrayMechanism === 'json-stringify') {
functionCode += `if (arrayLength >= ${largeArraySize}) return JSON.stringify(obj)\n`
}
functionCode += `
const arrayEnd = arrayLength - 1
let value
let json = ''
`
if (Array.isArray(itemsSchema)) {
for (let i = 0; i < itemsSchema.length; i++) {
const item = itemsSchema[i]
functionCode += `value = obj[${i}]`
const tmpRes = buildValue(context, itemsLocation.getPropertyLocation(i), 'value')
functionCode += `
if (${i} < arrayLength) {
if (${buildArrayTypeCondition(item.type, `[${i}]`)}) {
${tmpRes}
if (${i} < arrayEnd) {
json += JSON_STR_COMMA
}
} else {
throw new Error(\`Item at ${i} does not match schema definition.\`)
}
}
`
}
if (schema.additionalItems) {
functionCode += `
for (let i = ${itemsSchema.length}; i < arrayLength; i++) {
json += JSON.stringify(obj[i])
if (i < arrayEnd) {
json += JSON_STR_COMMA
}
}`
}
} else {
const code = buildValue(context, itemsLocation, 'obj[i]')
functionCode += `
for (let i = 0; i < arrayLength; i++) {
${code}
if (i < arrayEnd) {
json += JSON_STR_COMMA
}
}`
}
functionCode += `
return JSON_STR_BEGIN_ARRAY + json + JSON_STR_END_ARRAY
}`
context.functions.push(functionCode)
return functionName
}
function buildArrayTypeCondition (type, accessor) {
let condition
switch (type) {
case 'null':
condition = 'value === null'
break
case 'string':
condition = `typeof value === 'string' ||
value === null ||
value instanceof Date ||
value instanceof RegExp ||
(
typeof value === "object" &&
typeof value.toString === "function" &&
value.toString !== Object.prototype.toString
)`
break
case 'integer':
condition = 'Number.isInteger(value)'
break
case 'number':
condition = 'Number.isFinite(value)'
break
case 'boolean':
condition = 'typeof value === \'boolean\''
break
case 'object':
condition = 'value && typeof value === \'object\' && value.constructor === Object'
break
case 'array':
condition = 'Array.isArray(value)'
break
default:
if (Array.isArray(type)) {
const conditions = type.map((subType) => {
return buildArrayTypeCondition(subType, accessor)
})
condition = `(${conditions.join(' || ')})`
}
}
return condition
}
function generateFuncName (context) {
return 'anonymous' + context.functionsCounter++
}
function buildMultiTypeSerializer (context, location, input) {
const schema = location.schema
const types = schema.type.sort(t1 => t1 === 'null' ? -1 : 1)
let code = ''
types.forEach((type, index) => {
location.schema = { ...location.schema, type }
const nestedResult = buildSingleTypeSerializer(context, location, input)
const statement = index === 0 ? 'if' : 'else if'
switch (type) {
case 'null':
code += `
${statement} (${input} === null)
${nestedResult}
`
break
case 'string': {
code += `
${statement}(
typeof ${input} === "string" ||
${input} === null ||
${input} instanceof Date ||
${input} instanceof RegExp ||
(
typeof ${input} === "object" &&
typeof ${input}.toString === "function" &&
${input}.toString !== Object.prototype.toString
)
)
${nestedResult}
`
break
}
case 'array': {
code += `
${statement}(Array.isArray(${input}))
${nestedResult}
`
break
}
case 'integer': {
code += `
${statement}(Number.isInteger(${input}) || ${input} === null)
${nestedResult}
`
break
}
default: {
code += `
${statement}(typeof ${input} === "${type}" || ${input} === null)
${nestedResult}
`
break
}
}
})
let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}
code += `
else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
`
return code
}
function buildSingleTypeSerializer (context, location, input) {
const schema = location.schema
switch (schema.type) {
case 'null':
return 'json += JSON_STR_NULL'
case 'string': {
if (schema.format === 'date-time') {
return `json += serializer.asDateTime(${input})`
} else if (schema.format === 'date') {
return `json += serializer.asDate(${input})`
} else if (schema.format === 'time') {
return `json += serializer.asTime(${input})`
} else if (schema.format === 'unsafe') {
return `json += serializer.asUnsafeString(${input})`
} else {
return `
if (typeof ${input} !== 'string') {
if (${input} === null) {
json += JSON_STR_EMPTY_STRING
} else if (${input} instanceof Date) {
json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE
} else if (${input} instanceof RegExp) {
json += serializer.asString(${input}.source)
} else {
json += serializer.asString(${input}.toString())
}
} else {
json += serializer.asString(${input})
}
`
}
}
case 'integer':
return `json += serializer.asInteger(${input})`
case 'number':
return `json += serializer.asNumber(${input})`
case 'boolean':
return `json += serializer.asBoolean(${input})`
case 'object': {
const funcName = buildObject(context, location)
return `json += ${funcName}(${input})`
}
case 'array': {
const funcName = buildArray(context, location)
return `json += ${funcName}(${input})`
}
case undefined:
return `json += JSON.stringify(${input})`
default:
throw new Error(`${schema.type} unsupported`)
}
}
function buildConstSerializer (location, input) {
const schema = location.schema
const type = schema.type
const hasNullType = Array.isArray(type) && type.includes('null')
let code = ''
if (hasNullType) {
code += `
if (${input} === null) {
json += JSON_STR_NULL
} else {
`
}
code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'`
if (hasNullType) {
code += `
}
`
}
return code
}
function buildAllOf (context, location, input) {
const schema = location.schema
let mergedSchemaId = context.mergedSchemasIds.get(schema)
if (mergedSchemaId) {
const mergedLocation = getMergedLocation(context, mergedSchemaId)
return buildValue(context, mergedLocation, input)
}
mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`
context.mergedSchemasIds.set(schema, mergedSchemaId)
const { allOf, ...schemaWithoutAllOf } = location.schema
const locations = [
new Location(
schemaWithoutAllOf,
location.schemaId,
location.jsonPointer
)
]
const allOfsLocation = location.getPropertyLocation('allOf')
for (let i = 0; i < allOf.length; i++) {
locations.push(allOfsLocation.getPropertyLocation(i))
}
const mergedLocation = mergeLocations(context, mergedSchemaId, locations)
return buildValue(context, mergedLocation, input)
}
function buildOneOf (context, location, input) {
context.validatorSchemasIds.add(location.schemaId)
const schema = location.schema
const type = schema.anyOf ? 'anyOf' : 'oneOf'
const { [type]: oneOfs, ...schemaWithoutAnyOf } = location.schema
const locationWithoutOneOf = new Location(
schemaWithoutAnyOf,
location.schemaId,
location.jsonPointer
)
const oneOfsLocation = location.getPropertyLocation(type)
let code = ''
for (let index = 0; index < oneOfs.length; index++) {
const optionLocation = oneOfsLocation.getPropertyLocation(index)
const optionSchema = optionLocation.schema
let mergedSchemaId = context.mergedSchemasIds.get(optionSchema)
let mergedLocation = null
if (mergedSchemaId) {
mergedLocation = getMergedLocation(context, mergedSchemaId)
} else {
mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`
context.mergedSchemasIds.set(optionSchema, mergedSchemaId)
mergedLocation = mergeLocations(context, mergedSchemaId, [
locationWithoutOneOf,
optionLocation
])
}
const nestedResult = buildValue(context, mergedLocation, input)
const schemaRef = optionLocation.getSchemaRef()
code += `
${index === 0 ? 'if' : 'else if'}(validator.validate("${schemaRef}", ${input}))
${nestedResult}
`
}
let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}
code += `
else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
`
return code
}
function buildIfThenElse (context, location, input) {
context.validatorSchemasIds.add(location.schemaId)
const {
if: ifSchema,
then: thenSchema,
else: elseSchema,
...schemaWithoutIfThenElse
} = location.schema
const rootLocation = new Location(
schemaWithoutIfThenElse,
location.schemaId,
location.jsonPointer
)
const ifLocation = location.getPropertyLocation('if')
const ifSchemaRef = ifLocation.getSchemaRef()
const thenLocation = location.getPropertyLocation('then')
let thenMergedSchemaId = context.mergedSchemasIds.get(thenSchema)
let thenMergedLocation = null
if (thenMergedSchemaId) {
thenMergedLocation = getMergedLocation(context, thenMergedSchemaId)
} else {
thenMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`
context.mergedSchemasIds.set(thenSchema, thenMergedSchemaId)
thenMergedLocation = mergeLocations(context, thenMergedSchemaId, [
rootLocation,
thenLocation
])
}
if (!elseSchema) {
return `
if (validator.validate("${ifSchemaRef}", ${input})) {
${buildValue(context, thenMergedLocation, input)}
} else {
${buildValue(context, rootLocation, input)}
}
`
}
const elseLocation = location.getPropertyLocation('else')
let elseMergedSchemaId = context.mergedSchemasIds.get(elseSchema)
let elseMergedLocation = null
if (elseMergedSchemaId) {
elseMergedLocation = getMergedLocation(context, elseMergedSchemaId)
} else {
elseMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`
context.mergedSchemasIds.set(elseSchema, elseMergedSchemaId)
elseMergedLocation = mergeLocations(context, elseMergedSchemaId, [
rootLocation,
elseLocation
])
}
return `
if (validator.validate("${ifSchemaRef}", ${input})) {
${buildValue(context, thenMergedLocation, input)}
} else {
${buildValue(context, elseMergedLocation, input)}
}
`
}
function buildValue (context, location, input) {
let schema = location.schema
if (typeof schema === 'boolean') {
return `json += JSON.stringify(${input})`
}
if (schema.$ref) {
location = resolveRef(context, location)
schema = location.schema
}
if (schema.allOf) {
return buildAllOf(context, location, input)
}
if (schema.anyOf || schema.oneOf) {
return buildOneOf(context, location, input)
}
if (schema.if && schema.then) {
return buildIfThenElse(context, location, input)
}
if (schema.type === undefined) {
const inferredType = inferTypeByKeyword(schema)
if (inferredType) {
schema.type = inferredType
}
}
let code = ''
const type = schema.type
const nullable = schema.nullable === true
if (nullable) {
code += `
if (${input} === null) {
json += JSON_STR_NULL
} else {
`
}
if (schema.const !== undefined) {
code += buildConstSerializer(location, input)
} else if (Array.isArray(type)) {
code += buildMultiTypeSerializer(context, location, input)
} else {
code += buildSingleTypeSerializer(context, location, input)
}
if (nullable) {
code += `
}
`
}
return code
}
module.exports = build
module.exports["default"] = build
module.exports.build = build
module.exports.validLargeArrayMechanisms = validLargeArrayMechanisms
module.exports.restore = function ({ code, validator, serializer }) {
// eslint-disable-next-line
return (Function.apply(null, ['validator', 'serializer', code])
.apply(null, [validator, serializer]))
}
/***/ }),
/***/ 70731:
/***/ ((module) => {
"use strict";
class Location {
constructor (schema, schemaId, jsonPointer = '#') {
this.schema = schema
this.schemaId = schemaId
this.jsonPointer = jsonPointer
}
getPropertyLocation (propertyName) {
const propertyLocation = new Location(
this.schema[propertyName],
this.schemaId,
this.jsonPointer + '/' + propertyName
)
return propertyLocation
}
getSchemaRef () {
return this.schemaId + this.jsonPointer
}
}
module.exports = Location
/***/ }),
/***/ 13438:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { mergeSchemas: _mergeSchemas } = __nccwpck_require__(86389)
function mergeSchemas (schemas) {
return _mergeSchemas(schemas, { onConflict: 'skip' })
}
module.exports = mergeSchemas
/***/ }),
/***/ 80898:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* CODE GENERATED BY 'build-schema-validator.js' DO NOT EDIT! */
module.exports = validate10;
module.exports["default"] = validate10;
const schema11 = {"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true};
const schema12 = {"type":"integer","minimum":0};
const schema18 = {"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]};
const schema20 = {"enum":["array","boolean","integer","null","number","object","string"]};
const formats0 = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
const formats2 = (__nccwpck_require__(66124).fullFormats.uri);
const formats6 = (__nccwpck_require__(66124).fullFormats.regex);
const schema13 = {"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]};
function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
let vErrors = null;
let errors = 0;
const _errs1 = errors;
if(!(((typeof data == "number") && (!(data % 1) && !isNaN(data))) && (isFinite(data)))){
validate11.errors = [{instancePath,schemaPath:"#/definitions/nonNegativeInteger/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
if(errors === _errs1){
if((typeof data == "number") && (isFinite(data))){
if(data < 0 || isNaN(data)){
validate11.errors = [{instancePath,schemaPath:"#/definitions/nonNegativeInteger/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];
return false;
}
}
}
validate11.errors = vErrors;
return errors === 0;
}
const schema15 = {"type":"array","minItems":1,"items":{"$ref":"#"}};
const root1 = {validate: validate10};
function validate13(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
let vErrors = null;
let errors = 0;
if(errors === 0){
if(Array.isArray(data)){
if(data.length < 1){
validate13.errors = [{instancePath,schemaPath:"#/minItems",keyword:"minItems",params:{limit: 1},message:"must NOT have fewer than 1 items"}];
return false;
}
else {
var valid0 = true;
const len0 = data.length;
for(let i0=0; i0<len0; i0++){
const _errs1 = errors;
if(!(root1.validate(data[i0], {instancePath:instancePath+"/" + i0,parentData:data,parentDataProperty:i0,rootData}))){
vErrors = vErrors === null ? root1.validate.errors : vErrors.concat(root1.validate.errors);
errors = vErrors.length;
}
var valid0 = _errs1 === errors;
if(!valid0){
break;
}
}
}
}
else {
validate13.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "array"},message:"must be array"}];
return false;
}
}
validate13.errors = vErrors;
return errors === 0;
}
const func0 = (__nccwpck_require__(73938)["default"]);
function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
/*# sourceURL="http://json-schema.org/draft-07/schema#" */;
let vErrors = null;
let errors = 0;
if((!(data && typeof data == "object" && !Array.isArray(data))) && (typeof data !== "boolean")){
validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: schema11.type},message:"must be object,boolean"}];
return false;
}
if(errors === 0){
if(data && typeof data == "object" && !Array.isArray(data)){
if(data.$id !== undefined){
let data0 = data.$id;
const _errs1 = errors;
if(errors === _errs1){
if(errors === _errs1){
if(typeof data0 === "string"){
if(!(formats0.test(data0))){
validate10.errors = [{instancePath:instancePath+"/$id",schemaPath:"#/properties/%24id/format",keyword:"format",params:{format: "uri-reference"},message:"must match format \""+"uri-reference"+"\""}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/$id",schemaPath:"#/properties/%24id/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
}
var valid0 = _errs1 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.$schema !== undefined){
let data1 = data.$schema;
const _errs3 = errors;
if(errors === _errs3){
if(errors === _errs3){
if(typeof data1 === "string"){
if(!(formats2(data1))){
validate10.errors = [{instancePath:instancePath+"/$schema",schemaPath:"#/properties/%24schema/format",keyword:"format",params:{format: "uri"},message:"must match format \""+"uri"+"\""}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/$schema",schemaPath:"#/properties/%24schema/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
}
var valid0 = _errs3 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.$ref !== undefined){
let data2 = data.$ref;
const _errs5 = errors;
if(errors === _errs5){
if(errors === _errs5){
if(typeof data2 === "string"){
if(!(formats0.test(data2))){
validate10.errors = [{instancePath:instancePath+"/$ref",schemaPath:"#/properties/%24ref/format",keyword:"format",params:{format: "uri-reference"},message:"must match format \""+"uri-reference"+"\""}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
}
var valid0 = _errs5 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.$comment !== undefined){
const _errs7 = errors;
if(typeof data.$comment !== "string"){
validate10.errors = [{instancePath:instancePath+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs7 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.title !== undefined){
const _errs9 = errors;
if(typeof data.title !== "string"){
validate10.errors = [{instancePath:instancePath+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs9 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.description !== undefined){
const _errs11 = errors;
if(typeof data.description !== "string"){
validate10.errors = [{instancePath:instancePath+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs11 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.readOnly !== undefined){
const _errs13 = errors;
if(typeof data.readOnly !== "boolean"){
validate10.errors = [{instancePath:instancePath+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
var valid0 = _errs13 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.examples !== undefined){
const _errs15 = errors;
if(errors === _errs15){
if(!(Array.isArray(data.examples))){
validate10.errors = [{instancePath:instancePath+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type: "array"},message:"must be array"}];
return false;
}
}
var valid0 = _errs15 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.multipleOf !== undefined){
let data8 = data.multipleOf;
const _errs17 = errors;
if(errors === _errs17){
if((typeof data8 == "number") && (isFinite(data8))){
if(data8 <= 0 || isNaN(data8)){
validate10.errors = [{instancePath:instancePath+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison: ">", limit: 0},message:"must be > 0"}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type: "number"},message:"must be number"}];
return false;
}
}
var valid0 = _errs17 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.maximum !== undefined){
let data9 = data.maximum;
const _errs19 = errors;
if(!((typeof data9 == "number") && (isFinite(data9)))){
validate10.errors = [{instancePath:instancePath+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type: "number"},message:"must be number"}];
return false;
}
var valid0 = _errs19 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.exclusiveMaximum !== undefined){
let data10 = data.exclusiveMaximum;
const _errs21 = errors;
if(!((typeof data10 == "number") && (isFinite(data10)))){
validate10.errors = [{instancePath:instancePath+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type: "number"},message:"must be number"}];
return false;
}
var valid0 = _errs21 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.minimum !== undefined){
let data11 = data.minimum;
const _errs23 = errors;
if(!((typeof data11 == "number") && (isFinite(data11)))){
validate10.errors = [{instancePath:instancePath+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type: "number"},message:"must be number"}];
return false;
}
var valid0 = _errs23 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.exclusiveMinimum !== undefined){
let data12 = data.exclusiveMinimum;
const _errs25 = errors;
if(!((typeof data12 == "number") && (isFinite(data12)))){
validate10.errors = [{instancePath:instancePath+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type: "number"},message:"must be number"}];
return false;
}
var valid0 = _errs25 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.maxLength !== undefined){
let data13 = data.maxLength;
const _errs27 = errors;
const _errs28 = errors;
if(!(((typeof data13 == "number") && (!(data13 % 1) && !isNaN(data13))) && (isFinite(data13)))){
validate10.errors = [{instancePath:instancePath+"/maxLength",schemaPath:"#/definitions/nonNegativeInteger/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
if(errors === _errs28){
if((typeof data13 == "number") && (isFinite(data13))){
if(data13 < 0 || isNaN(data13)){
validate10.errors = [{instancePath:instancePath+"/maxLength",schemaPath:"#/definitions/nonNegativeInteger/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];
return false;
}
}
}
var valid0 = _errs27 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.minLength !== undefined){
const _errs30 = errors;
if(!(validate11(data.minLength, {instancePath:instancePath+"/minLength",parentData:data,parentDataProperty:"minLength",rootData}))){
vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors);
errors = vErrors.length;
}
var valid0 = _errs30 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.pattern !== undefined){
let data15 = data.pattern;
const _errs31 = errors;
if(errors === _errs31){
if(errors === _errs31){
if(typeof data15 === "string"){
if(!(formats6(data15))){
validate10.errors = [{instancePath:instancePath+"/pattern",schemaPath:"#/properties/pattern/format",keyword:"format",params:{format: "regex"},message:"must match format \""+"regex"+"\""}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/pattern",schemaPath:"#/properties/pattern/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
}
var valid0 = _errs31 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.additionalItems !== undefined){
const _errs33 = errors;
if(!(validate10(data.additionalItems, {instancePath:instancePath+"/additionalItems",parentData:data,parentDataProperty:"additionalItems",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs33 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.items !== undefined){
let data17 = data.items;
const _errs34 = errors;
const _errs35 = errors;
let valid2 = false;
const _errs36 = errors;
if(!(validate10(data17, {instancePath:instancePath+"/items",parentData:data,parentDataProperty:"items",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var _valid0 = _errs36 === errors;
valid2 = valid2 || _valid0;
if(!valid2){
const _errs37 = errors;
if(!(validate13(data17, {instancePath:instancePath+"/items",parentData:data,parentDataProperty:"items",rootData}))){
vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors);
errors = vErrors.length;
}
var _valid0 = _errs37 === errors;
valid2 = valid2 || _valid0;
}
if(!valid2){
const err0 = {instancePath:instancePath+"/items",schemaPath:"#/properties/items/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err0];
}
else {
vErrors.push(err0);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs35;
if(vErrors !== null){
if(_errs35){
vErrors.length = _errs35;
}
else {
vErrors = null;
}
}
}
var valid0 = _errs34 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.maxItems !== undefined){
let data18 = data.maxItems;
const _errs38 = errors;
const _errs39 = errors;
if(!(((typeof data18 == "number") && (!(data18 % 1) && !isNaN(data18))) && (isFinite(data18)))){
validate10.errors = [{instancePath:instancePath+"/maxItems",schemaPath:"#/definitions/nonNegativeInteger/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
if(errors === _errs39){
if((typeof data18 == "number") && (isFinite(data18))){
if(data18 < 0 || isNaN(data18)){
validate10.errors = [{instancePath:instancePath+"/maxItems",schemaPath:"#/definitions/nonNegativeInteger/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];
return false;
}
}
}
var valid0 = _errs38 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.minItems !== undefined){
const _errs41 = errors;
if(!(validate11(data.minItems, {instancePath:instancePath+"/minItems",parentData:data,parentDataProperty:"minItems",rootData}))){
vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors);
errors = vErrors.length;
}
var valid0 = _errs41 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.uniqueItems !== undefined){
const _errs42 = errors;
if(typeof data.uniqueItems !== "boolean"){
validate10.errors = [{instancePath:instancePath+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
var valid0 = _errs42 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.contains !== undefined){
const _errs44 = errors;
if(!(validate10(data.contains, {instancePath:instancePath+"/contains",parentData:data,parentDataProperty:"contains",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs44 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.maxProperties !== undefined){
let data22 = data.maxProperties;
const _errs45 = errors;
const _errs46 = errors;
if(!(((typeof data22 == "number") && (!(data22 % 1) && !isNaN(data22))) && (isFinite(data22)))){
validate10.errors = [{instancePath:instancePath+"/maxProperties",schemaPath:"#/definitions/nonNegativeInteger/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
if(errors === _errs46){
if((typeof data22 == "number") && (isFinite(data22))){
if(data22 < 0 || isNaN(data22)){
validate10.errors = [{instancePath:instancePath+"/maxProperties",schemaPath:"#/definitions/nonNegativeInteger/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];
return false;
}
}
}
var valid0 = _errs45 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.minProperties !== undefined){
const _errs48 = errors;
if(!(validate11(data.minProperties, {instancePath:instancePath+"/minProperties",parentData:data,parentDataProperty:"minProperties",rootData}))){
vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors);
errors = vErrors.length;
}
var valid0 = _errs48 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.required !== undefined){
let data24 = data.required;
const _errs49 = errors;
const _errs50 = errors;
if(errors === _errs50){
if(Array.isArray(data24)){
var valid6 = true;
const len0 = data24.length;
for(let i0=0; i0<len0; i0++){
const _errs52 = errors;
if(typeof data24[i0] !== "string"){
validate10.errors = [{instancePath:instancePath+"/required/" + i0,schemaPath:"#/definitions/stringArray/items/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid6 = _errs52 === errors;
if(!valid6){
break;
}
}
if(valid6){
let i1 = data24.length;
let j0;
if(i1 > 1){
const indices0 = {};
for(;i1--;){
let item0 = data24[i1];
if(typeof item0 !== "string"){
continue;
}
if(typeof indices0[item0] == "number"){
j0 = indices0[item0];
validate10.errors = [{instancePath:instancePath+"/required",schemaPath:"#/definitions/stringArray/uniqueItems",keyword:"uniqueItems",params:{i: i1, j: j0},message:"must NOT have duplicate items (items ## "+j0+" and "+i1+" are identical)"}];
return false;
break;
}
indices0[item0] = i1;
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/required",schemaPath:"#/definitions/stringArray/type",keyword:"type",params:{type: "array"},message:"must be array"}];
return false;
}
}
var valid0 = _errs49 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.additionalProperties !== undefined){
const _errs54 = errors;
if(!(validate10(data.additionalProperties, {instancePath:instancePath+"/additionalProperties",parentData:data,parentDataProperty:"additionalProperties",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs54 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.definitions !== undefined){
let data27 = data.definitions;
const _errs55 = errors;
if(errors === _errs55){
if(data27 && typeof data27 == "object" && !Array.isArray(data27)){
for(const key0 in data27){
const _errs58 = errors;
if(!(validate10(data27[key0], {instancePath:instancePath+"/definitions/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data27,parentDataProperty:key0,rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid8 = _errs58 === errors;
if(!valid8){
break;
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/definitions",schemaPath:"#/properties/definitions/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs55 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.properties !== undefined){
let data29 = data.properties;
const _errs59 = errors;
if(errors === _errs59){
if(data29 && typeof data29 == "object" && !Array.isArray(data29)){
for(const key1 in data29){
const _errs62 = errors;
if(!(validate10(data29[key1], {instancePath:instancePath+"/properties/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data29,parentDataProperty:key1,rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid9 = _errs62 === errors;
if(!valid9){
break;
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/properties",schemaPath:"#/properties/properties/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs59 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.patternProperties !== undefined){
let data31 = data.patternProperties;
const _errs63 = errors;
if(errors === _errs63){
if(data31 && typeof data31 == "object" && !Array.isArray(data31)){
for(const key2 in data31){
const _errs65 = errors;
if(errors === _errs65){
if(typeof key2 === "string"){
if(!(formats6(key2))){
const err1 = {instancePath:instancePath+"/patternProperties",schemaPath:"#/properties/patternProperties/propertyNames/format",keyword:"format",params:{format: "regex"},message:"must match format \""+"regex"+"\"",propertyName:key2};
if(vErrors === null){
vErrors = [err1];
}
else {
vErrors.push(err1);
}
errors++;
}
}
}
var valid10 = _errs65 === errors;
if(!valid10){
const err2 = {instancePath:instancePath+"/patternProperties",schemaPath:"#/properties/patternProperties/propertyNames",keyword:"propertyNames",params:{propertyName: key2},message:"property name must be valid"};
if(vErrors === null){
vErrors = [err2];
}
else {
vErrors.push(err2);
}
errors++;
validate10.errors = vErrors;
return false;
break;
}
}
if(valid10){
for(const key3 in data31){
const _errs67 = errors;
if(!(validate10(data31[key3], {instancePath:instancePath+"/patternProperties/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data31,parentDataProperty:key3,rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid11 = _errs67 === errors;
if(!valid11){
break;
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/patternProperties",schemaPath:"#/properties/patternProperties/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs63 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.dependencies !== undefined){
let data33 = data.dependencies;
const _errs68 = errors;
if(errors === _errs68){
if(data33 && typeof data33 == "object" && !Array.isArray(data33)){
for(const key4 in data33){
let data34 = data33[key4];
const _errs71 = errors;
const _errs72 = errors;
let valid13 = false;
const _errs73 = errors;
if(!(validate10(data34, {instancePath:instancePath+"/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data33,parentDataProperty:key4,rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var _valid1 = _errs73 === errors;
valid13 = valid13 || _valid1;
if(!valid13){
const _errs74 = errors;
const _errs75 = errors;
if(errors === _errs75){
if(Array.isArray(data34)){
var valid15 = true;
const len1 = data34.length;
for(let i2=0; i2<len1; i2++){
const _errs77 = errors;
if(typeof data34[i2] !== "string"){
const err3 = {instancePath:instancePath+"/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1")+"/" + i2,schemaPath:"#/definitions/stringArray/items/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err3];
}
else {
vErrors.push(err3);
}
errors++;
}
var valid15 = _errs77 === errors;
if(!valid15){
break;
}
}
if(valid15){
let i3 = data34.length;
let j1;
if(i3 > 1){
const indices1 = {};
for(;i3--;){
let item1 = data34[i3];
if(typeof item1 !== "string"){
continue;
}
if(typeof indices1[item1] == "number"){
j1 = indices1[item1];
const err4 = {instancePath:instancePath+"/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"),schemaPath:"#/definitions/stringArray/uniqueItems",keyword:"uniqueItems",params:{i: i3, j: j1},message:"must NOT have duplicate items (items ## "+j1+" and "+i3+" are identical)"};
if(vErrors === null){
vErrors = [err4];
}
else {
vErrors.push(err4);
}
errors++;
break;
}
indices1[item1] = i3;
}
}
}
}
else {
const err5 = {instancePath:instancePath+"/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"),schemaPath:"#/definitions/stringArray/type",keyword:"type",params:{type: "array"},message:"must be array"};
if(vErrors === null){
vErrors = [err5];
}
else {
vErrors.push(err5);
}
errors++;
}
}
var _valid1 = _errs74 === errors;
valid13 = valid13 || _valid1;
}
if(!valid13){
const err6 = {instancePath:instancePath+"/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"),schemaPath:"#/properties/dependencies/additionalProperties/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err6];
}
else {
vErrors.push(err6);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs72;
if(vErrors !== null){
if(_errs72){
vErrors.length = _errs72;
}
else {
vErrors = null;
}
}
}
var valid12 = _errs71 === errors;
if(!valid12){
break;
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/dependencies",schemaPath:"#/properties/dependencies/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs68 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.propertyNames !== undefined){
const _errs79 = errors;
if(!(validate10(data.propertyNames, {instancePath:instancePath+"/propertyNames",parentData:data,parentDataProperty:"propertyNames",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs79 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.enum !== undefined){
let data37 = data.enum;
const _errs80 = errors;
if(errors === _errs80){
if(Array.isArray(data37)){
if(data37.length < 1){
validate10.errors = [{instancePath:instancePath+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit: 1},message:"must NOT have fewer than 1 items"}];
return false;
}
else {
let i4 = data37.length;
let j2;
if(i4 > 1){
outer0:
for(;i4--;){
for(j2 = i4; j2--;){
if(func0(data37[i4], data37[j2])){
validate10.errors = [{instancePath:instancePath+"/enum",schemaPath:"#/properties/enum/uniqueItems",keyword:"uniqueItems",params:{i: i4, j: j2},message:"must NOT have duplicate items (items ## "+j2+" and "+i4+" are identical)"}];
return false;
break outer0;
}
}
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type: "array"},message:"must be array"}];
return false;
}
}
var valid0 = _errs80 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.type !== undefined){
let data38 = data.type;
const _errs82 = errors;
const _errs83 = errors;
let valid18 = false;
const _errs84 = errors;
if(!(((((((data38 === "array") || (data38 === "boolean")) || (data38 === "integer")) || (data38 === "null")) || (data38 === "number")) || (data38 === "object")) || (data38 === "string"))){
const err7 = {instancePath:instancePath+"/type",schemaPath:"#/definitions/simpleTypes/enum",keyword:"enum",params:{allowedValues: schema20.enum},message:"must be equal to one of the allowed values"};
if(vErrors === null){
vErrors = [err7];
}
else {
vErrors.push(err7);
}
errors++;
}
var _valid2 = _errs84 === errors;
valid18 = valid18 || _valid2;
if(!valid18){
const _errs86 = errors;
if(errors === _errs86){
if(Array.isArray(data38)){
if(data38.length < 1){
const err8 = {instancePath:instancePath+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit: 1},message:"must NOT have fewer than 1 items"};
if(vErrors === null){
vErrors = [err8];
}
else {
vErrors.push(err8);
}
errors++;
}
else {
var valid20 = true;
const len2 = data38.length;
for(let i5=0; i5<len2; i5++){
let data39 = data38[i5];
const _errs88 = errors;
if(!(((((((data39 === "array") || (data39 === "boolean")) || (data39 === "integer")) || (data39 === "null")) || (data39 === "number")) || (data39 === "object")) || (data39 === "string"))){
const err9 = {instancePath:instancePath+"/type/" + i5,schemaPath:"#/definitions/simpleTypes/enum",keyword:"enum",params:{allowedValues: schema20.enum},message:"must be equal to one of the allowed values"};
if(vErrors === null){
vErrors = [err9];
}
else {
vErrors.push(err9);
}
errors++;
}
var valid20 = _errs88 === errors;
if(!valid20){
break;
}
}
if(valid20){
let i6 = data38.length;
let j3;
if(i6 > 1){
outer1:
for(;i6--;){
for(j3 = i6; j3--;){
if(func0(data38[i6], data38[j3])){
const err10 = {instancePath:instancePath+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i: i6, j: j3},message:"must NOT have duplicate items (items ## "+j3+" and "+i6+" are identical)"};
if(vErrors === null){
vErrors = [err10];
}
else {
vErrors.push(err10);
}
errors++;
break outer1;
}
}
}
}
}
}
}
else {
const err11 = {instancePath:instancePath+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type: "array"},message:"must be array"};
if(vErrors === null){
vErrors = [err11];
}
else {
vErrors.push(err11);
}
errors++;
}
}
var _valid2 = _errs86 === errors;
valid18 = valid18 || _valid2;
}
if(!valid18){
const err12 = {instancePath:instancePath+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err12];
}
else {
vErrors.push(err12);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs83;
if(vErrors !== null){
if(_errs83){
vErrors.length = _errs83;
}
else {
vErrors = null;
}
}
}
var valid0 = _errs82 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.format !== undefined){
const _errs90 = errors;
if(typeof data.format !== "string"){
validate10.errors = [{instancePath:instancePath+"/format",schemaPath:"#/properties/format/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs90 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.contentMediaType !== undefined){
const _errs92 = errors;
if(typeof data.contentMediaType !== "string"){
validate10.errors = [{instancePath:instancePath+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs92 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.contentEncoding !== undefined){
const _errs94 = errors;
if(typeof data.contentEncoding !== "string"){
validate10.errors = [{instancePath:instancePath+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
var valid0 = _errs94 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.if !== undefined){
const _errs96 = errors;
if(!(validate10(data.if, {instancePath:instancePath+"/if",parentData:data,parentDataProperty:"if",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs96 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.then !== undefined){
const _errs97 = errors;
if(!(validate10(data.then, {instancePath:instancePath+"/then",parentData:data,parentDataProperty:"then",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs97 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.else !== undefined){
const _errs98 = errors;
if(!(validate10(data.else, {instancePath:instancePath+"/else",parentData:data,parentDataProperty:"else",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs98 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.allOf !== undefined){
const _errs99 = errors;
if(!(validate13(data.allOf, {instancePath:instancePath+"/allOf",parentData:data,parentDataProperty:"allOf",rootData}))){
vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors);
errors = vErrors.length;
}
var valid0 = _errs99 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.anyOf !== undefined){
const _errs100 = errors;
if(!(validate13(data.anyOf, {instancePath:instancePath+"/anyOf",parentData:data,parentDataProperty:"anyOf",rootData}))){
vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors);
errors = vErrors.length;
}
var valid0 = _errs100 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.oneOf !== undefined){
const _errs101 = errors;
if(!(validate13(data.oneOf, {instancePath:instancePath+"/oneOf",parentData:data,parentDataProperty:"oneOf",rootData}))){
vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors);
errors = vErrors.length;
}
var valid0 = _errs101 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.not !== undefined){
const _errs102 = errors;
if(!(validate10(data.not, {instancePath:instancePath+"/not",parentData:data,parentDataProperty:"not",rootData}))){
vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors);
errors = vErrors.length;
}
var valid0 = _errs102 === errors;
}
else {
var valid0 = true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
validate10.errors = vErrors;
return errors === 0;
}
/***/ }),
/***/ 52234:
/***/ ((module) => {
"use strict";
// eslint-disable-next-line
const STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/
module.exports = class Serializer {
constructor (options) {
switch (options && options.rounding) {
case 'floor':
this.parseInteger = Math.floor
break
case 'ceil':
this.parseInteger = Math.ceil
break
case 'round':
this.parseInteger = Math.round
break
case 'trunc':
default:
this.parseInteger = Math.trunc
break
}
this._options = options
}
asInteger (i) {
if (Number.isInteger(i)) {
return '' + i
} else if (typeof i === 'bigint') {
return i.toString()
}
/* eslint no-undef: "off" */
const integer = this.parseInteger(i)
// check if number is Infinity or NaN
// eslint-disable-next-line no-self-compare
if (integer === Infinity || integer === -Infinity || integer !== integer) {
throw new Error(`The value "${i}" cannot be converted to an integer.`)
}
return '' + integer
}
asNumber (i) {
// fast cast to number
const num = +i
// check if number is NaN
// eslint-disable-next-line no-self-compare
if (num !== num) {
throw new Error(`The value "${i}" cannot be converted to a number.`)
} else if (num === Infinity || num === -Infinity) {
return 'null'
} else {
return '' + num
}
}
asBoolean (bool) {
return bool && 'true' || 'false' // eslint-disable-line
}
asDateTime (date) {
if (date === null) return '""'
if (date instanceof Date) {
return '"' + date.toISOString() + '"'
}
if (typeof date === 'string') {
return '"' + date + '"'
}
throw new Error(`The value "${date}" cannot be converted to a date-time.`)
}
asDate (date) {
if (date === null) return '""'
if (date instanceof Date) {
return '"' + new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().slice(0, 10) + '"'
}
if (typeof date === 'string') {
return '"' + date + '"'
}
throw new Error(`The value "${date}" cannot be converted to a date.`)
}
asTime (date) {
if (date === null) return '""'
if (date instanceof Date) {
return '"' + new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().slice(11, 19) + '"'
}
if (typeof date === 'string') {
return '"' + date + '"'
}
throw new Error(`The value "${date}" cannot be converted to a time.`)
}
asString (str) {
const len = str.length
if (len < 42) {
// magically escape strings for json
// relying on their charCodeAt
// everything below 32 needs JSON.stringify()
// every string that contain surrogate needs JSON.stringify()
// 34 and 92 happens all the time, so we
// have a fast case for them
let result = ''
let last = -1
let point = 255
// eslint-disable-next-line
for (var i = 0; i < len; i++) {
point = str.charCodeAt(i)
if (
point === 0x22 || // '"'
point === 0x5c // '\'
) {
last === -1 && (last = 0)
result += str.slice(last, i) + '\\'
last = i
} else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
// The current character is non-printable characters or a surrogate.
return JSON.stringify(str)
}
}
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
} else if (len < 5000 && STR_ESCAPE.test(str) === false) {
// Only use the regular expression for shorter input. The overhead is otherwise too much.
return '"' + str + '"'
} else {
return JSON.stringify(str)
}
}
asUnsafeString (str) {
return '"' + str + '"'
}
getState () {
return this._options
}
static restoreFromState (state) {
return new Serializer(state)
}
}
/***/ }),
/***/ 23591:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
function buildStandaloneCode (contextFunc, context, serializer, validator) {
let ajvDependencyCode = ''
if (context.validatorSchemasIds.size > 0) {
ajvDependencyCode += 'const Validator = require(\'fast-json-stringify/lib/validator\')\n'
ajvDependencyCode += `const validatorState = ${JSON.stringify(validator.getState())}\n`
ajvDependencyCode += 'const validator = Validator.restoreFromState(validatorState)\n'
} else {
ajvDependencyCode += 'const validator = null\n'
}
// Don't need to keep external schemas once compiled
// validatorState will hold external schemas if it needs them
const { schema, ...serializerState } = serializer.getState()
return `
'use strict'
const Serializer = require('fast-json-stringify/lib/serializer')
const serializerState = ${JSON.stringify(serializerState)}
const serializer = Serializer.restoreFromState(serializerState)
${ajvDependencyCode}
module.exports = ${contextFunc.toString()}(validator, serializer)`
}
module.exports = buildStandaloneCode
module.exports.dependencies = {
Serializer: __nccwpck_require__(52234),
Validator: __nccwpck_require__(87737)
}
/***/ }),
/***/ 87737:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const Ajv = __nccwpck_require__(41848)
const fastUri = __nccwpck_require__(49688)
const ajvFormats = __nccwpck_require__(40281)
const clone = __nccwpck_require__(11868)({ proto: true })
class Validator {
constructor (ajvOptions) {
this.ajv = new Ajv({
...ajvOptions,
strictSchema: false,
validateSchema: false,
allowUnionTypes: true,
uriResolver: fastUri
})
ajvFormats(this.ajv)
this.ajv.addKeyword({
keyword: 'fjs_type',
type: 'object',
errors: false,
validate: (type, date) => {
return date instanceof Date
}
})
this._ajvSchemas = {}
this._ajvOptions = ajvOptions || {}
}
addSchema (schema, schemaName) {
let schemaKey = schema.$id || schemaName
if (schema.$id !== undefined && schema.$id[0] === '#') {
schemaKey = schemaName + schema.$id // relative URI
}
if (
this.ajv.refs[schemaKey] === undefined &&
this.ajv.schemas[schemaKey] === undefined
) {
const ajvSchema = clone(schema)
this.convertSchemaToAjvFormat(ajvSchema)
this.ajv.addSchema(ajvSchema, schemaKey)
this._ajvSchemas[schemaKey] = schema
}
}
validate (schemaRef, data) {
return this.ajv.validate(schemaRef, data)
}
// Ajv does not support js date format. In order to properly validate objects containing a date,
// it needs to replace all occurrences of the string date format with a custom keyword fjs_type.
// (see https://github.com/fastify/fast-json-stringify/pull/441)
convertSchemaToAjvFormat (schema) {
if (schema === null) return
if (schema.type === 'string') {
schema.fjs_type = 'string'
schema.type = ['string', 'object']
} else if (
Array.isArray(schema.type) &&
schema.type.includes('string') &&
!schema.type.includes('object')
) {
schema.fjs_type = 'string'
schema.type.push('object')
}
for (const property in schema) {
if (typeof schema[property] === 'object') {
this.convertSchemaToAjvFormat(schema[property])
}
}
}
getState () {
return {
ajvOptions: this._ajvOptions,
ajvSchemas: this._ajvSchemas
}
}
static restoreFromState (state) {
const validator = new Validator(state.ajvOptions)
for (const [id, ajvSchema] of Object.entries(state.ajvSchemas)) {
validator.ajv.addSchema(ajvSchema, id)
}
return validator
}
}
module.exports = Validator
/***/ }),
/***/ 49688:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = __nccwpck_require__(96743)
const SCHEMES = __nccwpck_require__(4923)
function normalize (uri, options) {
if (typeof uri === 'string') {
uri = serialize(parse(uri, options), options)
} else if (typeof uri === 'object') {
uri = parse(serialize(uri, options), options)
}
return uri
}
function resolve (baseURI, relativeURI, options) {
const schemelessOptions = Object.assign({ scheme: 'null' }, options)
const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)
return serialize(resolved, { ...schemelessOptions, skipEscape: true })
}
function resolveComponents (base, relative, options, skipNormalization) {
const target = {}
if (!skipNormalization) {
base = parse(serialize(base, options), options) // normalize base components
relative = parse(serialize(relative, options), options) // normalize relative components
}
options = options || {}
if (!options.tolerant && relative.scheme) {
target.scheme = relative.scheme
// target.authority = relative.authority;
target.userinfo = relative.userinfo
target.host = relative.host
target.port = relative.port
target.path = removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
// target.authority = relative.authority;
target.userinfo = relative.userinfo
target.host = relative.host
target.port = relative.port
target.path = removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (!relative.path) {
target.path = base.path
if (relative.query !== undefined) {
target.query = relative.query
} else {
target.query = base.query
}
} else {
if (relative.path.charAt(0) === '/') {
target.path = removeDotSegments(relative.path)
} else {
if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
target.path = '/' + relative.path
} else if (!base.path) {
target.path = relative.path
} else {
target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
}
target.path = removeDotSegments(target.path)
}
target.query = relative.query
}
// target.authority = base.authority;
target.userinfo = base.userinfo
target.host = base.host
target.port = base.port
}
target.scheme = base.scheme
}
target.fragment = relative.fragment
return target
}
function equal (uriA, uriB, options) {
if (typeof uriA === 'string') {
uriA = unescape(uriA)
uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })
} else if (typeof uriA === 'object') {
uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })
}
if (typeof uriB === 'string') {
uriB = unescape(uriB)
uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })
} else if (typeof uriB === 'object') {
uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })
}
return uriA.toLowerCase() === uriB.toLowerCase()
}
function serialize (cmpts, opts) {
const components = {
host: cmpts.host,
scheme: cmpts.scheme,
userinfo: cmpts.userinfo,
port: cmpts.port,
path: cmpts.path,
query: cmpts.query,
nid: cmpts.nid,
nss: cmpts.nss,
uuid: cmpts.uuid,
fragment: cmpts.fragment,
reference: cmpts.reference,
resourceName: cmpts.resourceName,
secure: cmpts.secure,
error: ''
}
const options = Object.assign({}, opts)
const uriTokens = []
// find scheme handler
const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()]
// perform scheme specific serialization
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options)
if (components.path !== undefined) {
if (!options.skipEscape) {
components.path = escape(components.path)
if (components.scheme !== undefined) {
components.path = components.path.split('%3A').join(':')
}
} else {
components.path = unescape(components.path)
}
}
if (options.reference !== 'suffix' && components.scheme) {
uriTokens.push(components.scheme)
uriTokens.push(':')
}
const authority = recomposeAuthority(components, options)
if (authority !== undefined) {
if (options.reference !== 'suffix') {
uriTokens.push('//')
}
uriTokens.push(authority)
if (components.path && components.path.charAt(0) !== '/') {
uriTokens.push('/')
}
}
if (components.path !== undefined) {
let s = components.path
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
s = removeDotSegments(s)
}
if (authority === undefined) {
s = s.replace(/^\/\//u, '/%2F') // don't allow the path to start with "//"
}
uriTokens.push(s)
}
if (components.query !== undefined) {
uriTokens.push('?')
uriTokens.push(components.query)
}
if (components.fragment !== undefined) {
uriTokens.push('#')
uriTokens.push(components.fragment)
}
return uriTokens.join('')
}
const hexLookUp = Array.from({ length: 127 }, (v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)))
function nonSimpleDomain (value) {
let code = 0
for (let i = 0, len = value.length; i < len; ++i) {
code = value.charCodeAt(i)
if (code > 126 || hexLookUp[code]) {
return true
}
}
return false
}
const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
function parse (uri, opts) {
const options = Object.assign({}, opts)
const parsed = {
scheme: undefined,
userinfo: undefined,
host: '',
port: undefined,
path: '',
query: undefined,
fragment: undefined
}
const gotEncoding = uri.indexOf('%') !== -1
if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri
const matches = uri.match(URI_PARSE)
if (matches) {
// store each component
parsed.scheme = matches[1]
parsed.userinfo = matches[3]
parsed.host = matches[4]
parsed.port = parseInt(matches[5], 10)
parsed.path = matches[6] || ''
parsed.query = matches[7]
parsed.fragment = matches[8]
// fix port number
if (isNaN(parsed.port)) {
parsed.port = matches[5]
}
if (parsed.host) {
const ipv4result = normalizeIPv4(parsed.host)
if (ipv4result.isIPV4 === false) {
parsed.host = normalizeIPv6(ipv4result.host, { isIPV4: false }).host.toLowerCase()
} else {
parsed.host = ipv4result.host
}
}
if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && !parsed.path && parsed.query === undefined) {
parsed.reference = 'same-document'
} else if (parsed.scheme === undefined) {
parsed.reference = 'relative'
} else if (parsed.fragment === undefined) {
parsed.reference = 'absolute'
} else {
parsed.reference = 'uri'
}
// check for reference errors
if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
}
// find scheme handler
const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()]
// check if scheme can't handle IRIs
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
// if host component is a domain name
if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && nonSimpleDomain(parsed.host)) {
// convert Unicode IDN -> ASCII IDN
try {
parsed.host = URL.domainToASCII(parsed.host.toLowerCase())
} catch (e) {
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
}
}
// convert IRI -> URI
}
if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
if (gotEncoding && parsed.scheme !== undefined) {
parsed.scheme = unescape(parsed.scheme)
}
if (gotEncoding && parsed.userinfo !== undefined) {
parsed.userinfo = unescape(parsed.userinfo)
}
if (gotEncoding && parsed.host !== undefined) {
parsed.host = unescape(parsed.host)
}
if (parsed.path !== undefined && parsed.path.length) {
parsed.path = escape(unescape(parsed.path))
}
if (parsed.fragment !== undefined && parsed.fragment.length) {
parsed.fragment = encodeURI(decodeURI(parsed.fragment))
}
}
// perform scheme specific parsing
if (schemeHandler && schemeHandler.parse) {
schemeHandler.parse(parsed, options)
}
} else {
parsed.error = parsed.error || 'URI can not be parsed.'
}
return parsed
}
const fastUri = {
normalize,
resolve,
resolveComponents,
equal,
serialize,
parse
}
module.exports = fastUri
module.exports["default"] = fastUri
module.exports.fastUri = fastUri
/***/ }),
/***/ 4923:
/***/ ((module) => {
"use strict";
const UUID_REG = /^[\da-f]{8}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{12}$/iu
const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu
function isSecure (wsComponents) {
return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === 'wss'
}
function httpParse (components) {
if (!components.host) {
components.error = components.error || 'HTTP URIs must have a host.'
}
return components
}
function httpSerialize (components) {
const secure = String(components.scheme).toLowerCase() === 'https'
// normalize the default port
if (components.port === (secure ? 443 : 80) || components.port === '') {
components.port = undefined
}
// normalize the empty path
if (!components.path) {
components.path = '/'
}
// NOTE: We do not parse query strings for HTTP URIs
// as WWW Form Url Encoded query strings are part of the HTML4+ spec,
// and not the HTTP spec.
return components
}
function wsParse (wsComponents) {
// indicate if the secure flag is set
wsComponents.secure = isSecure(wsComponents)
// construct resouce name
wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '')
wsComponents.path = undefined
wsComponents.query = undefined
return wsComponents
}
function wsSerialize (wsComponents) {
// normalize the default port
if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === '') {
wsComponents.port = undefined
}
// ensure scheme matches secure flag
if (typeof wsComponents.secure === 'boolean') {
wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws')
wsComponents.secure = undefined
}
// reconstruct path from resource name
if (wsComponents.resourceName) {
const [path, query] = wsComponents.resourceName.split('?')
wsComponents.path = (path && path !== '/' ? path : undefined)
wsComponents.query = query
wsComponents.resourceName = undefined
}
// forbid fragment component
wsComponents.fragment = undefined
return wsComponents
}
function urnParse (urnComponents, options) {
if (!urnComponents.path) {
urnComponents.error = 'URN can not be parsed'
return urnComponents
}
const matches = urnComponents.path.match(URN_REG)
if (matches) {
const scheme = options.scheme || urnComponents.scheme || 'urn'
urnComponents.nid = matches[1].toLowerCase()
urnComponents.nss = matches[2]
const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`
const schemeHandler = SCHEMES[urnScheme]
urnComponents.path = undefined
if (schemeHandler) {
urnComponents = schemeHandler.parse(urnComponents, options)
}
} else {
urnComponents.error = urnComponents.error || 'URN can not be parsed.'
}
return urnComponents
}
function urnSerialize (urnComponents, options) {
const scheme = options.scheme || urnComponents.scheme || 'urn'
const nid = urnComponents.nid.toLowerCase()
const urnScheme = `${scheme}:${options.nid || nid}`
const schemeHandler = SCHEMES[urnScheme]
if (schemeHandler) {
urnComponents = schemeHandler.serialize(urnComponents, options)
}
const uriComponents = urnComponents
const nss = urnComponents.nss
uriComponents.path = `${nid || options.nid}:${nss}`
options.skipEscape = true
return uriComponents
}
function urnuuidParse (urnComponents, options) {
const uuidComponents = urnComponents
uuidComponents.uuid = uuidComponents.nss
uuidComponents.nss = undefined
if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) {
uuidComponents.error = uuidComponents.error || 'UUID is not valid.'
}
return uuidComponents
}
function urnuuidSerialize (uuidComponents) {
const urnComponents = uuidComponents
// normalize UUID
urnComponents.nss = (uuidComponents.uuid || '').toLowerCase()
return urnComponents
}
const http = {
scheme: 'http',
domainHost: true,
parse: httpParse,
serialize: httpSerialize
}
const https = {
scheme: 'https',
domainHost: http.domainHost,
parse: httpParse,
serialize: httpSerialize
}
const ws = {
scheme: 'ws',
domainHost: true,
parse: wsParse,
serialize: wsSerialize
}
const wss = {
scheme: 'wss',
domainHost: ws.domainHost,
parse: ws.parse,
serialize: ws.serialize
}
const urn = {
scheme: 'urn',
parse: urnParse,
serialize: urnSerialize,
skipNormalize: true
}
const urnuuid = {
scheme: 'urn:uuid',
parse: urnuuidParse,
serialize: urnuuidSerialize,
skipNormalize: true
}
const SCHEMES = {
http,
https,
ws,
wss,
urn,
'urn:uuid': urnuuid
}
module.exports = SCHEMES
/***/ }),
/***/ 83157:
/***/ ((module) => {
"use strict";
const HEX = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
a: 10,
A: 10,
b: 11,
B: 11,
c: 12,
C: 12,
d: 13,
D: 13,
e: 14,
E: 14,
f: 15,
F: 15
}
module.exports = {
HEX
}
/***/ }),
/***/ 96743:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { HEX } = __nccwpck_require__(83157)
function normalizeIPv4 (host) {
if (findToken(host, '.') < 3) { return { host, isIPV4: false } }
const matches = host.match(/^(\b[01]?\d{1,2}|\b2[0-4]\d|\b25[0-5])(\.([01]?\d{1,2}|2[0-4]\d|25[0-5])){3}$/u) || []
const [address] = matches
if (address) {
return { host: stripLeadingZeros(address, '.'), isIPV4: true }
} else {
return { host, isIPV4: false }
}
}
function stringToHexStripped (input) {
let acc = ''
let strip = true
for (const c of input) {
if (c !== '0' && strip === true) strip = false
if (HEX[c] === undefined) return undefined
if (!strip) acc += c
}
return acc
}
function getIPV6 (input) {
let tokenCount = 0
const output = { error: false, address: '', zone: '' }
const address = []
const buffer = []
let isZone = false
let endipv6Encountered = false
let endIpv6 = false
function consume () {
if (buffer.length) {
if (isZone === false) {
const hex = stringToHexStripped(buffer.join(''))
if (hex !== undefined) {
address.push(hex)
} else {
output.error = true
return false
}
}
buffer.length = 0
}
return true
}
for (let i = 0; i < input.length; i++) {
const cursor = input[i]
if (cursor === '[' || cursor === ']') { continue }
if (cursor === ':') {
if (endipv6Encountered === true) {
endIpv6 = true
}
if (!consume()) { break }
tokenCount++
address.push(':')
if (tokenCount > 7) {
// not valid
output.error = true
break
}
if (i - 1 >= 0 && input[i - 1] === ':') {
endipv6Encountered = true
}
continue
} else if (cursor === '%') {
if (!consume()) { break }
// switch to zone detection
isZone = true
} else {
buffer.push(cursor)
continue
}
}
if (buffer.length) {
if (isZone) {
output.zone = buffer.join('')
} else if (endIpv6) {
address.push(buffer.join(''))
} else {
address.push(stringToHexStripped(buffer.join('')))
}
}
output.address = address.join('')
return output
}
function normalizeIPv6 (host, opts = {}) {
if (findToken(host, ':') < 2) { return { host, isIPV6: false } }
const ipv6 = getIPV6(host)
if (!ipv6.error) {
let newHost = ipv6.address
let escapedHost = ipv6.address
if (ipv6.zone) {
newHost += '%' + ipv6.zone
escapedHost += '%25' + ipv6.zone
}
return { host: newHost, escapedHost, isIPV6: true }
} else {
return { host, isIPV6: false }
}
}
function stripLeadingZeros (str, token) {
let out = ''
let skip = true
const l = str.length
for (let i = 0; i < l; i++) {
const c = str[i]
if (c === '0' && skip) {
if ((i + 1 <= l && str[i + 1] === token) || i + 1 === l) {
out += c
skip = false
}
} else {
if (c === token) {
skip = true
} else {
skip = false
}
out += c
}
}
return out
}
function findToken (str, token) {
let ind = 0
for (let i = 0; i < str.length; i++) {
if (str[i] === token) ind++
}
return ind
}
const RDS1 = /^\.\.?\//u
const RDS2 = /^\/\.(?:\/|$)/u
const RDS3 = /^\/\.\.(?:\/|$)/u
const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u
function removeDotSegments (input) {
const output = []
while (input.length) {
if (input.match(RDS1)) {
input = input.replace(RDS1, '')
} else if (input.match(RDS2)) {
input = input.replace(RDS2, '/')
} else if (input.match(RDS3)) {
input = input.replace(RDS3, '/')
output.pop()
} else if (input === '.' || input === '..') {
input = ''
} else {
const im = input.match(RDS5)
if (im) {
const s = im[0]
input = input.slice(s.length)
output.push(s)
} else {
throw new Error('Unexpected dot segment condition')
}
}
}
return output.join('')
}
function normalizeComponentEncoding (components, esc) {
const func = esc !== true ? escape : unescape
if (components.scheme !== undefined) {
components.scheme = func(components.scheme)
}
if (components.userinfo !== undefined) {
components.userinfo = func(components.userinfo)
}
if (components.host !== undefined) {
components.host = func(components.host)
}
if (components.path !== undefined) {
components.path = func(components.path)
}
if (components.query !== undefined) {
components.query = func(components.query)
}
if (components.fragment !== undefined) {
components.fragment = func(components.fragment)
}
return components
}
function recomposeAuthority (components, options) {
const uriTokens = []
if (components.userinfo !== undefined) {
uriTokens.push(components.userinfo)
uriTokens.push('@')
}
if (components.host !== undefined) {
let host = unescape(components.host)
const ipV4res = normalizeIPv4(host)
if (ipV4res.isIPV4) {
host = ipV4res.host
} else {
const ipV6res = normalizeIPv6(ipV4res.host, { isIPV4: false })
if (ipV6res.isIPV6 === true) {
host = `[${ipV6res.escapedHost}]`
} else {
host = components.host
}
}
uriTokens.push(host)
}
if (typeof components.port === 'number' || typeof components.port === 'string') {
uriTokens.push(':')
uriTokens.push(String(components.port))
}
return uriTokens.length ? uriTokens.join('') : undefined
};
module.exports = {
recomposeAuthority,
normalizeComponentEncoding,
removeDotSegments,
normalizeIPv4,
normalizeIPv6,
stringToHexStripped
}
/***/ }),
/***/ 67834:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const VERSION = '4.27.0'
const Avvio = __nccwpck_require__(4488)
const http = __nccwpck_require__(88849)
let lightMyRequest
const {
kAvvioBoot,
kChildren,
kServerBindings,
kBodyLimit,
kRoutePrefix,
kLogLevel,
kLogSerializers,
kHooks,
kSchemaController,
kRequestAcceptVersion,
kReplySerializerDefault,
kContentTypeParser,
kReply,
kRequest,
kFourOhFour,
kState,
kOptions,
kPluginNameChain,
kSchemaErrorFormatter,
kErrorHandler,
kKeepAliveConnections,
kChildLoggerFactory,
kGenReqId
} = __nccwpck_require__(28622)
const { createServer, compileValidateHTTPVersion } = __nccwpck_require__(60410)
const Reply = __nccwpck_require__(55479)
const Request = __nccwpck_require__(11696)
const Context = __nccwpck_require__(76676)
const { supportedMethods } = __nccwpck_require__(8340)
const decorator = __nccwpck_require__(7629)
const ContentTypeParser = __nccwpck_require__(76696)
const SchemaController = __nccwpck_require__(92310)
const { Hooks, hookRunnerApplication, supportedHooks } = __nccwpck_require__(26133)
const { createLogger, createChildLogger, defaultChildLoggerFactory } = __nccwpck_require__(8102)
const pluginUtils = __nccwpck_require__(41057)
const { getGenReqId, reqIdGenFactory } = __nccwpck_require__(74729)
const { buildRouting, validateBodyLimitOption } = __nccwpck_require__(61237)
const build404 = __nccwpck_require__(48660)
const getSecuredInitialConfig = __nccwpck_require__(39643)
const override = __nccwpck_require__(28243)
const { FSTDEP009 } = __nccwpck_require__(59283)
const noopSet = __nccwpck_require__(4679)
const {
appendStackTrace,
AVVIO_ERRORS_MAP,
...errorCodes
} = __nccwpck_require__(89005)
const { defaultInitOptions } = getSecuredInitialConfig
const {
FST_ERR_ASYNC_CONSTRAINT,
FST_ERR_BAD_URL,
FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE,
FST_ERR_OPTIONS_NOT_OBJ,
FST_ERR_QSP_NOT_FN,
FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN,
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ,
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR,
FST_ERR_VERSION_CONSTRAINT_NOT_STR,
FST_ERR_INSTANCE_ALREADY_LISTENING,
FST_ERR_REOPENED_CLOSE_SERVER,
FST_ERR_ROUTE_REWRITE_NOT_STR,
FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN,
FST_ERR_ERROR_HANDLER_NOT_FN
} = errorCodes
const { buildErrorHandler } = __nccwpck_require__(58755)
function defaultBuildPrettyMeta (route) {
// return a shallow copy of route's sanitized context
const cleanKeys = {}
const allowedProps = ['errorHandler', 'logLevel', 'logSerializers']
allowedProps.concat(supportedHooks).forEach(k => {
cleanKeys[k] = route.store[k]
})
return Object.assign({}, cleanKeys)
}
/**
* @param {import('./fastify.js').FastifyServerOptions} options
*/
function fastify (options) {
// Options validations
options = options || {}
if (typeof options !== 'object') {
throw new FST_ERR_OPTIONS_NOT_OBJ()
}
if (options.querystringParser && typeof options.querystringParser !== 'function') {
throw new FST_ERR_QSP_NOT_FN(typeof options.querystringParser)
}
if (options.schemaController && options.schemaController.bucket && typeof options.schemaController.bucket !== 'function') {
throw new FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN(typeof options.schemaController.bucket)
}
validateBodyLimitOption(options.bodyLimit)
const requestIdHeader = (options.requestIdHeader === false) ? false : (options.requestIdHeader || defaultInitOptions.requestIdHeader).toLowerCase()
const genReqId = reqIdGenFactory(requestIdHeader, options.genReqId)
const requestIdLogLabel = options.requestIdLogLabel || 'reqId'
const bodyLimit = options.bodyLimit || defaultInitOptions.bodyLimit
const disableRequestLogging = options.disableRequestLogging || false
const ajvOptions = Object.assign({
customOptions: {},
plugins: []
}, options.ajv)
const frameworkErrors = options.frameworkErrors
// Ajv options
if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ(typeof ajvOptions.customOptions)
}
if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins)
}
// Instance Fastify components
const { logger, hasLogger } = createLogger(options)
// Update the options with the fixed values
options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout
options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout
options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket
options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout
options.logger = logger
options.requestIdHeader = requestIdHeader
options.requestIdLogLabel = requestIdLogLabel
options.disableRequestLogging = disableRequestLogging
options.ajv = ajvOptions
options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler
const initialConfig = getSecuredInitialConfig(options)
// exposeHeadRoutes have its default set from the validator
options.exposeHeadRoutes = initialConfig.exposeHeadRoutes
let constraints = options.constraints
if (options.versioning) {
FSTDEP009()
constraints = {
...constraints,
version: {
name: 'version',
mustMatchWhenDerived: true,
storage: options.versioning.storage,
deriveConstraint: options.versioning.deriveVersion,
validate (value) {
if (typeof value !== 'string') {
throw new FST_ERR_VERSION_CONSTRAINT_NOT_STR()
}
}
}
}
}
// Default router
const router = buildRouting({
config: {
defaultRoute,
onBadUrl,
constraints,
ignoreTrailingSlash: options.ignoreTrailingSlash || defaultInitOptions.ignoreTrailingSlash,
ignoreDuplicateSlashes: options.ignoreDuplicateSlashes || defaultInitOptions.ignoreDuplicateSlashes,
maxParamLength: options.maxParamLength || defaultInitOptions.maxParamLength,
caseSensitive: options.caseSensitive,
allowUnsafeRegex: options.allowUnsafeRegex || defaultInitOptions.allowUnsafeRegex,
buildPrettyMeta: defaultBuildPrettyMeta,
querystringParser: options.querystringParser,
useSemicolonDelimiter: options.useSemicolonDelimiter ?? defaultInitOptions.useSemicolonDelimiter
}
})
// 404 router, used for handling encapsulated 404 handlers
const fourOhFour = build404(options)
// HTTP server and its handler
const httpHandler = wrapRouting(router, options)
// we need to set this before calling createServer
options.http2SessionTimeout = initialConfig.http2SessionTimeout
const { server, listen } = createServer(options, httpHandler)
const serverHasCloseAllConnections = typeof server.closeAllConnections === 'function'
const serverHasCloseIdleConnections = typeof server.closeIdleConnections === 'function'
let forceCloseConnections = options.forceCloseConnections
if (forceCloseConnections === 'idle' && !serverHasCloseIdleConnections) {
throw new FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE()
} else if (typeof forceCloseConnections !== 'boolean') {
/* istanbul ignore next: only one branch can be valid in a given Node.js version */
forceCloseConnections = serverHasCloseIdleConnections ? 'idle' : false
}
const keepAliveConnections = !serverHasCloseAllConnections && forceCloseConnections === true ? new Set() : noopSet()
const setupResponseListeners = Reply.setupResponseListeners
const schemaController = SchemaController.buildSchemaController(null, options.schemaController)
// Public API
const fastify = {
// Fastify internals
[kState]: {
listening: false,
closing: false,
started: false,
ready: false,
booting: false,
readyPromise: null
},
[kKeepAliveConnections]: keepAliveConnections,
[kOptions]: options,
[kChildren]: [],
[kServerBindings]: [],
[kBodyLimit]: bodyLimit,
[kRoutePrefix]: '',
[kLogLevel]: '',
[kLogSerializers]: null,
[kHooks]: new Hooks(),
[kSchemaController]: schemaController,
[kSchemaErrorFormatter]: null,
[kErrorHandler]: buildErrorHandler(),
[kChildLoggerFactory]: defaultChildLoggerFactory,
[kReplySerializerDefault]: null,
[kContentTypeParser]: new ContentTypeParser(
bodyLimit,
(options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning),
(options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning)
),
[kReply]: Reply.buildReply(Reply),
[kRequest]: Request.buildRequest(Request, options.trustProxy),
[kFourOhFour]: fourOhFour,
[pluginUtils.kRegisteredPlugins]: [],
[kPluginNameChain]: ['fastify'],
[kAvvioBoot]: null,
[kGenReqId]: genReqId,
// routing method
routing: httpHandler,
getDefaultRoute: router.getDefaultRoute.bind(router),
setDefaultRoute: router.setDefaultRoute.bind(router),
// routes shorthand methods
delete: function _delete (url, options, handler) {
return router.prepareRoute.call(this, { method: 'DELETE', url, options, handler })
},
get: function _get (url, options, handler) {
return router.prepareRoute.call(this, { method: 'GET', url, options, handler })
},
head: function _head (url, options, handler) {
return router.prepareRoute.call(this, { method: 'HEAD', url, options, handler })
},
patch: function _patch (url, options, handler) {
return router.prepareRoute.call(this, { method: 'PATCH', url, options, handler })
},
post: function _post (url, options, handler) {
return router.prepareRoute.call(this, { method: 'POST', url, options, handler })
},
put: function _put (url, options, handler) {
return router.prepareRoute.call(this, { method: 'PUT', url, options, handler })
},
options: function _options (url, options, handler) {
return router.prepareRoute.call(this, { method: 'OPTIONS', url, options, handler })
},
all: function _all (url, options, handler) {
return router.prepareRoute.call(this, { method: supportedMethods, url, options, handler })
},
// extended route
route: function _route (options) {
// we need the fastify object that we are producing so we apply a lazy loading of the function,
// otherwise we should bind it after the declaration
return router.route.call(this, { options })
},
hasRoute: function _route (options) {
return router.hasRoute.call(this, { options })
},
findRoute: function _findRoute (options) {
return router.findRoute(options)
},
// expose logger instance
log: logger,
// type provider
withTypeProvider,
// hooks
addHook,
// schemas
addSchema,
getSchema: schemaController.getSchema.bind(schemaController),
getSchemas: schemaController.getSchemas.bind(schemaController),
setValidatorCompiler,
setSerializerCompiler,
setSchemaController,
setReplySerializer,
setSchemaErrorFormatter,
// set generated request id
setGenReqId,
// custom parsers
addContentTypeParser: ContentTypeParser.helpers.addContentTypeParser,
hasContentTypeParser: ContentTypeParser.helpers.hasContentTypeParser,
getDefaultJsonParser: ContentTypeParser.defaultParsers.getDefaultJsonParser,
defaultTextParser: ContentTypeParser.defaultParsers.defaultTextParser,
removeContentTypeParser: ContentTypeParser.helpers.removeContentTypeParser,
removeAllContentTypeParsers: ContentTypeParser.helpers.removeAllContentTypeParsers,
// Fastify architecture methods (initialized by Avvio)
register: null,
after: null,
ready: null,
onClose: null,
close: null,
printPlugins: null,
hasPlugin: function (name) {
return this[pluginUtils.kRegisteredPlugins].includes(name) || this[kPluginNameChain].includes(name)
},
// http server
listen,
server,
addresses: function () {
/* istanbul ignore next */
const binded = this[kServerBindings].map(b => b.address())
binded.push(this.server.address())
return binded.filter(adr => adr)
},
// extend fastify objects
decorate: decorator.add,
hasDecorator: decorator.exist,
decorateReply: decorator.decorateReply,
decorateRequest: decorator.decorateRequest,
hasRequestDecorator: decorator.existRequest,
hasReplyDecorator: decorator.existReply,
// fake http injection
inject,
// pretty print of the registered routes
printRoutes,
// custom error handling
setNotFoundHandler,
setErrorHandler,
// child logger
setChildLoggerFactory,
// Set fastify initial configuration options read-only object
initialConfig,
// constraint strategies
addConstraintStrategy: router.addConstraintStrategy.bind(router),
hasConstraintStrategy: router.hasConstraintStrategy.bind(router)
}
Object.defineProperties(fastify, {
listeningOrigin: {
get () {
const address = this.addresses().slice(-1).pop()
/* ignore if windows: unix socket is not testable on Windows platform */
/* c8 ignore next 3 */
if (typeof address === 'string') {
return address
}
const host = address.family === 'IPv6' ? `[${address.address}]` : address.address
return `${this[kOptions].https ? 'https' : 'http'}://${host}:${address.port}`
}
},
pluginName: {
configurable: true,
get () {
if (this[kPluginNameChain].length > 1) {
return this[kPluginNameChain].join(' -> ')
}
return this[kPluginNameChain][0]
}
},
prefix: {
configurable: true,
get () { return this[kRoutePrefix] }
},
validatorCompiler: {
configurable: true,
get () { return this[kSchemaController].getValidatorCompiler() }
},
serializerCompiler: {
configurable: true,
get () { return this[kSchemaController].getSerializerCompiler() }
},
childLoggerFactory: {
configurable: true,
get () { return this[kChildLoggerFactory] }
},
version: {
configurable: true,
get () { return VERSION }
},
errorHandler: {
configurable: true,
get () {
return this[kErrorHandler].func
}
},
genReqId: {
configurable: true,
get () { return this[kGenReqId] }
}
})
if (options.schemaErrorFormatter) {
validateSchemaErrorFormatter(options.schemaErrorFormatter)
fastify[kSchemaErrorFormatter] = options.schemaErrorFormatter.bind(fastify)
}
// Install and configure Avvio
// Avvio will update the following Fastify methods:
// - register
// - after
// - ready
// - onClose
// - close
const avvioPluginTimeout = Number(options.pluginTimeout)
const avvio = Avvio(fastify, {
autostart: false,
timeout: isNaN(avvioPluginTimeout) === false ? avvioPluginTimeout : defaultInitOptions.pluginTimeout,
expose: {
use: 'register'
}
})
// Override to allow the plugin encapsulation
avvio.override = override
avvio.on('start', () => (fastify[kState].started = true))
fastify[kAvvioBoot] = fastify.ready // the avvio ready function
fastify.ready = ready // overwrite the avvio ready function
fastify.printPlugins = avvio.prettyPrint.bind(avvio)
// cache the closing value, since we are checking it in an hot path
avvio.once('preReady', () => {
fastify.onClose((instance, done) => {
fastify[kState].closing = true
router.closeRoutes()
hookRunnerApplication('preClose', fastify[kAvvioBoot], fastify, function () {
if (fastify[kState].listening) {
/* istanbul ignore next: Cannot test this without Node.js core support */
if (forceCloseConnections === 'idle') {
// Not needed in Node 19
instance.server.closeIdleConnections()
/* istanbul ignore next: Cannot test this without Node.js core support */
} else if (serverHasCloseAllConnections && forceCloseConnections) {
instance.server.closeAllConnections()
} else if (forceCloseConnections === true) {
for (const conn of fastify[kKeepAliveConnections]) {
// We must invoke the destroy method instead of merely unreffing
// the sockets. If we only unref, then the callback passed to
// `fastify.close` will never be invoked; nor will any of the
// registered `onClose` hooks.
conn.destroy()
fastify[kKeepAliveConnections].delete(conn)
}
}
}
// No new TCP connections are accepted.
// We must call close on the server even if we are not listening
// otherwise memory will be leaked.
// https://github.com/nodejs/node/issues/48604
if (!options.serverFactory || fastify[kState].listening) {
instance.server.close(function (err) {
/* c8 ignore next 6 */
if (err && err.code !== 'ERR_SERVER_NOT_RUNNING') {
done(null)
} else {
done()
}
})
} else {
process.nextTick(done, null)
}
})
})
})
// Create bad URL context
const onBadUrlContext = new Context({
server: fastify,
config: {}
})
// Set the default 404 handler
fastify.setNotFoundHandler()
fourOhFour.arrange404(fastify)
router.setup(options, {
avvio,
fourOhFour,
logger,
hasLogger,
setupResponseListeners,
throwIfAlreadyStarted,
validateHTTPVersion: compileValidateHTTPVersion(options),
keepAliveConnections
})
// Delay configuring clientError handler so that it can access fastify state.
server.on('clientError', options.clientErrorHandler.bind(fastify))
try {
const dc = __nccwpck_require__(65714)
const initChannel = dc.channel('fastify.initialization')
if (initChannel.hasSubscribers) {
initChannel.publish({ fastify })
}
} catch (e) {
// This only happens if `diagnostics_channel` isn't available, i.e. earlier
// versions of Node.js. In that event, we don't care, so ignore the error.
}
// Older nodejs versions may not have asyncDispose
if ('asyncDispose' in Symbol) {
fastify[Symbol.asyncDispose] = function dispose () {
return fastify.close()
}
}
return fastify
function throwIfAlreadyStarted (msg) {
if (fastify[kState].started) throw new FST_ERR_INSTANCE_ALREADY_LISTENING(msg)
}
// HTTP injection handling
// If the server is not ready yet, this
// utility will automatically force it.
function inject (opts, cb) {
// lightMyRequest is dynamically loaded as it seems very expensive
// because of Ajv
if (lightMyRequest === undefined) {
lightMyRequest = __nccwpck_require__(62438)
}
if (fastify[kState].started) {
if (fastify[kState].closing) {
// Force to return an error
const error = new FST_ERR_REOPENED_CLOSE_SERVER()
if (cb) {
cb(error)
return
} else {
return Promise.reject(error)
}
}
return lightMyRequest(httpHandler, opts, cb)
}
if (cb) {
this.ready(err => {
if (err) cb(err, null)
else lightMyRequest(httpHandler, opts, cb)
})
} else {
return lightMyRequest((req, res) => {
this.ready(function (err) {
if (err) {
res.emit('error', err)
return
}
httpHandler(req, res)
})
}, opts)
}
}
function ready (cb) {
if (this[kState].readyPromise !== null) {
if (cb != null) {
this[kState].readyPromise.then(() => cb(null, fastify), cb)
return
}
return this[kState].readyPromise
}
let resolveReady
let rejectReady
// run the hooks after returning the promise
process.nextTick(runHooks)
// Create a promise no matter what
// It will work as a barrier for all the .ready() calls (ensuring single hook execution)
// as well as a flow control mechanism to chain cbs and further
// promises
this[kState].readyPromise = new Promise(function (resolve, reject) {
resolveReady = resolve
rejectReady = reject
})
if (!cb) {
return this[kState].readyPromise
} else {
this[kState].readyPromise.then(() => cb(null, fastify), cb)
}
function runHooks () {
// start loading
fastify[kAvvioBoot]((err, done) => {
if (err || fastify[kState].started || fastify[kState].ready || fastify[kState].booting) {
manageErr(err)
} else {
fastify[kState].booting = true
hookRunnerApplication('onReady', fastify[kAvvioBoot], fastify, manageErr)
}
done()
})
}
function manageErr (err) {
// If the error comes out of Avvio's Error codes
// We create a make and preserve the previous error
// as cause
err = err != null && AVVIO_ERRORS_MAP[err.code] != null
? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message))
: err
if (err) {
return rejectReady(err)
}
resolveReady(fastify)
fastify[kState].booting = false
fastify[kState].ready = true
fastify[kState].promise = null
}
}
// Used exclusively in TypeScript contexts to enable auto type inference from JSON schema.
function withTypeProvider () {
return this
}
// wrapper that we expose to the user for hooks handling
function addHook (name, fn) {
throwIfAlreadyStarted('Cannot call "addHook"!')
if (fn == null) {
throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn)
}
if (name === 'onSend' || name === 'preSerialization' || name === 'onError' || name === 'preParsing') {
if (fn.constructor.name === 'AsyncFunction' && fn.length === 4) {
throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
} else if (name === 'onReady' || name === 'onListen') {
if (fn.constructor.name === 'AsyncFunction' && fn.length !== 0) {
throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
} else if (name === 'onRequestAbort') {
if (fn.constructor.name === 'AsyncFunction' && fn.length !== 1) {
throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
} else {
if (fn.constructor.name === 'AsyncFunction' && fn.length === 3) {
throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
}
if (name === 'onClose') {
this.onClose(fn)
} else if (name === 'onReady' || name === 'onListen' || name === 'onRoute') {
this[kHooks].add(name, fn)
} else {
this.after((err, done) => {
_addHook.call(this, name, fn)
done(err)
})
}
return this
function _addHook (name, fn) {
this[kHooks].add(name, fn)
this[kChildren].forEach(child => _addHook.call(child, name, fn))
}
}
// wrapper that we expose to the user for schemas handling
function addSchema (schema) {
throwIfAlreadyStarted('Cannot call "addSchema"!')
this[kSchemaController].add(schema)
this[kChildren].forEach(child => child.addSchema(schema))
return this
}
function defaultClientErrorHandler (err, socket) {
// In case of a connection reset, the socket has been destroyed and there is nothing that needs to be done.
// https://nodejs.org/api/http.html#http_event_clienterror
if (err.code === 'ECONNRESET' || socket.destroyed) {
return
}
let body, errorCode, errorStatus, errorLabel
if (err.code === 'ERR_HTTP_REQUEST_TIMEOUT') {
errorCode = '408'
errorStatus = http.STATUS_CODES[errorCode]
body = `{"error":"${errorStatus}","message":"Client Timeout","statusCode":408}`
errorLabel = 'timeout'
} else if (err.code === 'HPE_HEADER_OVERFLOW') {
errorCode = '431'
errorStatus = http.STATUS_CODES[errorCode]
body = `{"error":"${errorStatus}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`
errorLabel = 'header_overflow'
} else {
errorCode = '400'
errorStatus = http.STATUS_CODES[errorCode]
body = `{"error":"${errorStatus}","message":"Client Error","statusCode":400}`
errorLabel = 'error'
}
// Most devs do not know what to do with this error.
// In the vast majority of cases, it's a network error and/or some
// config issue on the load balancer side.
this.log.trace({ err }, `client ${errorLabel}`)
// Copying standard node behavior
// https://github.com/nodejs/node/blob/6ca23d7846cb47e84fd344543e394e50938540be/lib/_http_server.js#L666
// If the socket is not writable, there is no reason to try to send data.
if (socket.writable) {
socket.write(`HTTP/1.1 ${errorCode} ${errorStatus}\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
}
socket.destroy(err)
}
// If the router does not match any route, every request will land here
// req and res are Node.js core objects
function defaultRoute (req, res) {
if (req.headers['accept-version'] !== undefined) {
// we remove the accept-version header for performance result
// because we do not want to go through the constraint checking
// the usage of symbol here to prevent any collision on custom header name
req.headers[kRequestAcceptVersion] = req.headers['accept-version']
req.headers['accept-version'] = undefined
}
fourOhFour.router.lookup(req, res)
}
function onBadUrl (path, req, res) {
if (frameworkErrors) {
const id = getGenReqId(onBadUrlContext.server, req)
const childLogger = createChildLogger(onBadUrlContext, logger, req, id)
const request = new Request(id, null, req, null, childLogger, onBadUrlContext)
const reply = new Reply(res, request, childLogger)
if (disableRequestLogging === false) {
childLogger.info({ req: request }, 'incoming request')
}
return frameworkErrors(new FST_ERR_BAD_URL(path), request, reply)
}
const body = `{"error":"Bad Request","code":"FST_ERR_BAD_URL","message":"'${path}' is not a valid url component","statusCode":400}`
res.writeHead(400, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}
function buildAsyncConstraintCallback (isAsync, req, res) {
if (isAsync === false) return undefined
return function onAsyncConstraintError (err) {
if (err) {
if (frameworkErrors) {
const id = getGenReqId(onBadUrlContext.server, req)
const childLogger = createChildLogger(onBadUrlContext, logger, req, id)
const request = new Request(id, null, req, null, childLogger, onBadUrlContext)
const reply = new Reply(res, request, childLogger)
if (disableRequestLogging === false) {
childLogger.info({ req: request }, 'incoming request')
}
return frameworkErrors(new FST_ERR_ASYNC_CONSTRAINT(), request, reply)
}
const body = '{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}'
res.writeHead(500, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}
}
}
function setNotFoundHandler (opts, handler) {
throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!')
fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler)
return this
}
function setValidatorCompiler (validatorCompiler) {
throwIfAlreadyStarted('Cannot call "setValidatorCompiler"!')
this[kSchemaController].setValidatorCompiler(validatorCompiler)
return this
}
function setSchemaErrorFormatter (errorFormatter) {
throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter"!')
validateSchemaErrorFormatter(errorFormatter)
this[kSchemaErrorFormatter] = errorFormatter.bind(this)
return this
}
function setSerializerCompiler (serializerCompiler) {
throwIfAlreadyStarted('Cannot call "setSerializerCompiler"!')
this[kSchemaController].setSerializerCompiler(serializerCompiler)
return this
}
function setSchemaController (schemaControllerOpts) {
throwIfAlreadyStarted('Cannot call "setSchemaController"!')
const old = this[kSchemaController]
const schemaController = SchemaController.buildSchemaController(old, Object.assign({}, old.opts, schemaControllerOpts))
this[kSchemaController] = schemaController
this.getSchema = schemaController.getSchema.bind(schemaController)
this.getSchemas = schemaController.getSchemas.bind(schemaController)
return this
}
function setReplySerializer (replySerializer) {
throwIfAlreadyStarted('Cannot call "setReplySerializer"!')
this[kReplySerializerDefault] = replySerializer
return this
}
// wrapper that we expose to the user for configure the custom error handler
function setErrorHandler (func) {
throwIfAlreadyStarted('Cannot call "setErrorHandler"!')
if (typeof func !== 'function') {
throw new FST_ERR_ERROR_HANDLER_NOT_FN()
}
this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this))
return this
}
function setChildLoggerFactory (factory) {
throwIfAlreadyStarted('Cannot call "setChildLoggerFactory"!')
this[kChildLoggerFactory] = factory
return this
}
function printRoutes (opts = {}) {
// includeHooks:true - shortcut to include all supported hooks exported by fastify.Hooks
opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta
return router.printRoutes(opts)
}
function wrapRouting (router, { rewriteUrl, logger }) {
let isAsync
return function preRouting (req, res) {
// only call isAsyncConstraint once
if (isAsync === undefined) isAsync = router.isAsyncConstraint()
if (rewriteUrl) {
req.originalUrl = req.url
const url = rewriteUrl.call(fastify, req)
if (typeof url === 'string') {
req.url = url
} else {
const err = new FST_ERR_ROUTE_REWRITE_NOT_STR(req.url, typeof url)
req.destroy(err)
}
}
router.routing(req, res, buildAsyncConstraintCallback(isAsync, req, res))
}
}
function setGenReqId (func) {
throwIfAlreadyStarted('Cannot call "setGenReqId"!')
this[kGenReqId] = reqIdGenFactory(this[kOptions].requestIdHeader, func)
return this
}
}
function validateSchemaErrorFormatter (schemaErrorFormatter) {
if (typeof schemaErrorFormatter !== 'function') {
throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN(typeof schemaErrorFormatter)
} else if (schemaErrorFormatter.constructor.name === 'AsyncFunction') {
throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN('AsyncFunction')
}
}
/**
* These export configurations enable JS and TS developers
* to consumer fastify in whatever way best suits their needs.
* Some examples of supported import syntax includes:
* - `const fastify = require('fastify')`
* - `const { fastify } = require('fastify')`
* - `import * as Fastify from 'fastify'`
* - `import { fastify, TSC_definition } from 'fastify'`
* - `import fastify from 'fastify'`
* - `import fastify, { TSC_definition } from 'fastify'`
*/
module.exports = fastify
module.exports.errorCodes = errorCodes
module.exports.fastify = fastify
module.exports["default"] = fastify
/***/ }),
/***/ 51612:
/***/ ((module) => {
"use strict";
// This file is autogenerated by build/build-validation.js, do not edit
/* istanbul ignore file */
module.exports = validate10;
module.exports["default"] = validate10;
const schema11 = {"type":"object","additionalProperties":false,"properties":{"connectionTimeout":{"type":"integer","default":0},"keepAliveTimeout":{"type":"integer","default":72000},"forceCloseConnections":{"oneOf":[{"type":"string","pattern":"idle"},{"type":"boolean"}]},"maxRequestsPerSocket":{"type":"integer","default":0,"nullable":true},"requestTimeout":{"type":"integer","default":0},"bodyLimit":{"type":"integer","default":1048576},"caseSensitive":{"type":"boolean","default":true},"allowUnsafeRegex":{"type":"boolean","default":false},"http2":{"type":"boolean"},"https":{"if":{"not":{"oneOf":[{"type":"boolean"},{"type":"null"},{"type":"object","additionalProperties":false,"required":["allowHTTP1"],"properties":{"allowHTTP1":{"type":"boolean"}}}]}},"then":{"setDefaultValue":true}},"ignoreTrailingSlash":{"type":"boolean","default":false},"ignoreDuplicateSlashes":{"type":"boolean","default":false},"disableRequestLogging":{"type":"boolean","default":false},"jsonShorthand":{"type":"boolean","default":true},"maxParamLength":{"type":"integer","default":100},"onProtoPoisoning":{"type":"string","default":"error"},"onConstructorPoisoning":{"type":"string","default":"error"},"pluginTimeout":{"type":"integer","default":10000},"requestIdHeader":{"anyOf":[{"enum":[false]},{"type":"string"}],"default":"request-id"},"requestIdLogLabel":{"type":"string","default":"reqId"},"http2SessionTimeout":{"type":"integer","default":72000},"exposeHeadRoutes":{"type":"boolean","default":true},"useSemicolonDelimiter":{"type":"boolean","default":true},"versioning":{"type":"object","additionalProperties":true,"required":["storage","deriveVersion"],"properties":{"storage":{},"deriveVersion":{}}},"constraints":{"type":"object","additionalProperties":{"type":"object","required":["name","storage","validate","deriveConstraint"],"additionalProperties":true,"properties":{"name":{"type":"string"},"storage":{},"validate":{},"deriveConstraint":{}}}}}};
const func2 = Object.prototype.hasOwnProperty;
const pattern0 = new RegExp("idle", "u");
function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
let vErrors = null;
let errors = 0;
if(errors === 0){
if(data && typeof data == "object" && !Array.isArray(data)){
if(data.connectionTimeout === undefined){
data.connectionTimeout = 0;
}
if(data.keepAliveTimeout === undefined){
data.keepAliveTimeout = 72000;
}
if(data.maxRequestsPerSocket === undefined){
data.maxRequestsPerSocket = 0;
}
if(data.requestTimeout === undefined){
data.requestTimeout = 0;
}
if(data.bodyLimit === undefined){
data.bodyLimit = 1048576;
}
if(data.caseSensitive === undefined){
data.caseSensitive = true;
}
if(data.allowUnsafeRegex === undefined){
data.allowUnsafeRegex = false;
}
if(data.ignoreTrailingSlash === undefined){
data.ignoreTrailingSlash = false;
}
if(data.ignoreDuplicateSlashes === undefined){
data.ignoreDuplicateSlashes = false;
}
if(data.disableRequestLogging === undefined){
data.disableRequestLogging = false;
}
if(data.jsonShorthand === undefined){
data.jsonShorthand = true;
}
if(data.maxParamLength === undefined){
data.maxParamLength = 100;
}
if(data.onProtoPoisoning === undefined){
data.onProtoPoisoning = "error";
}
if(data.onConstructorPoisoning === undefined){
data.onConstructorPoisoning = "error";
}
if(data.pluginTimeout === undefined){
data.pluginTimeout = 10000;
}
if(data.requestIdHeader === undefined){
data.requestIdHeader = "request-id";
}
if(data.requestIdLogLabel === undefined){
data.requestIdLogLabel = "reqId";
}
if(data.http2SessionTimeout === undefined){
data.http2SessionTimeout = 72000;
}
if(data.exposeHeadRoutes === undefined){
data.exposeHeadRoutes = true;
}
if(data.useSemicolonDelimiter === undefined){
data.useSemicolonDelimiter = true;
}
const _errs1 = errors;
for(const key0 in data){
if(!(func2.call(schema11.properties, key0))){
delete data[key0];
}
}
if(_errs1 === errors){
let data0 = data.connectionTimeout;
const _errs2 = errors;
if(!(((typeof data0 == "number") && (!(data0 % 1) && !isNaN(data0))) && (isFinite(data0)))){
let dataType0 = typeof data0;
let coerced0 = undefined;
if(!(coerced0 !== undefined)){
if(dataType0 === "boolean" || data0 === null
|| (dataType0 === "string" && data0 && data0 == +data0 && !(data0 % 1))){
coerced0 = +data0;
}
else {
validate10.errors = [{instancePath:instancePath+"/connectionTimeout",schemaPath:"#/properties/connectionTimeout/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced0 !== undefined){
data0 = coerced0;
if(data !== undefined){
data["connectionTimeout"] = coerced0;
}
}
}
var valid0 = _errs2 === errors;
if(valid0){
let data1 = data.keepAliveTimeout;
const _errs4 = errors;
if(!(((typeof data1 == "number") && (!(data1 % 1) && !isNaN(data1))) && (isFinite(data1)))){
let dataType1 = typeof data1;
let coerced1 = undefined;
if(!(coerced1 !== undefined)){
if(dataType1 === "boolean" || data1 === null
|| (dataType1 === "string" && data1 && data1 == +data1 && !(data1 % 1))){
coerced1 = +data1;
}
else {
validate10.errors = [{instancePath:instancePath+"/keepAliveTimeout",schemaPath:"#/properties/keepAliveTimeout/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced1 !== undefined){
data1 = coerced1;
if(data !== undefined){
data["keepAliveTimeout"] = coerced1;
}
}
}
var valid0 = _errs4 === errors;
if(valid0){
if(data.forceCloseConnections !== undefined){
let data2 = data.forceCloseConnections;
const _errs6 = errors;
const _errs7 = errors;
let valid1 = false;
let passing0 = null;
const _errs8 = errors;
if(typeof data2 !== "string"){
let dataType2 = typeof data2;
let coerced2 = undefined;
if(!(coerced2 !== undefined)){
if(dataType2 == "number" || dataType2 == "boolean"){
coerced2 = "" + data2;
}
else if(data2 === null){
coerced2 = "";
}
else {
const err0 = {instancePath:instancePath+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err0];
}
else {
vErrors.push(err0);
}
errors++;
}
}
if(coerced2 !== undefined){
data2 = coerced2;
if(data !== undefined){
data["forceCloseConnections"] = coerced2;
}
}
}
if(errors === _errs8){
if(typeof data2 === "string"){
if(!pattern0.test(data2)){
const err1 = {instancePath:instancePath+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/0/pattern",keyword:"pattern",params:{pattern: "idle"},message:"must match pattern \""+"idle"+"\""};
if(vErrors === null){
vErrors = [err1];
}
else {
vErrors.push(err1);
}
errors++;
}
}
}
var _valid0 = _errs8 === errors;
if(_valid0){
valid1 = true;
passing0 = 0;
}
const _errs10 = errors;
if(typeof data2 !== "boolean"){
let coerced3 = undefined;
if(!(coerced3 !== undefined)){
if(data2 === "false" || data2 === 0 || data2 === null){
coerced3 = false;
}
else if(data2 === "true" || data2 === 1){
coerced3 = true;
}
else {
const err2 = {instancePath:instancePath+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/1/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"};
if(vErrors === null){
vErrors = [err2];
}
else {
vErrors.push(err2);
}
errors++;
}
}
if(coerced3 !== undefined){
data2 = coerced3;
if(data !== undefined){
data["forceCloseConnections"] = coerced3;
}
}
}
var _valid0 = _errs10 === errors;
if(_valid0 && valid1){
valid1 = false;
passing0 = [passing0, 1];
}
else {
if(_valid0){
valid1 = true;
passing0 = 1;
}
}
if(!valid1){
const err3 = {instancePath:instancePath+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf",keyword:"oneOf",params:{passingSchemas: passing0},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err3];
}
else {
vErrors.push(err3);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs7;
if(vErrors !== null){
if(_errs7){
vErrors.length = _errs7;
}
else {
vErrors = null;
}
}
}
var valid0 = _errs6 === errors;
}
else {
var valid0 = true;
}
if(valid0){
let data3 = data.maxRequestsPerSocket;
const _errs12 = errors;
if((!(((typeof data3 == "number") && (!(data3 % 1) && !isNaN(data3))) && (isFinite(data3)))) && (data3 !== null)){
let dataType4 = typeof data3;
let coerced4 = undefined;
if(!(coerced4 !== undefined)){
if(dataType4 === "boolean" || data3 === null
|| (dataType4 === "string" && data3 && data3 == +data3 && !(data3 % 1))){
coerced4 = +data3;
}
else if(data3 === "" || data3 === 0 || data3 === false){
coerced4 = null;
}
else {
validate10.errors = [{instancePath:instancePath+"/maxRequestsPerSocket",schemaPath:"#/properties/maxRequestsPerSocket/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced4 !== undefined){
data3 = coerced4;
if(data !== undefined){
data["maxRequestsPerSocket"] = coerced4;
}
}
}
var valid0 = _errs12 === errors;
if(valid0){
let data4 = data.requestTimeout;
const _errs15 = errors;
if(!(((typeof data4 == "number") && (!(data4 % 1) && !isNaN(data4))) && (isFinite(data4)))){
let dataType5 = typeof data4;
let coerced5 = undefined;
if(!(coerced5 !== undefined)){
if(dataType5 === "boolean" || data4 === null
|| (dataType5 === "string" && data4 && data4 == +data4 && !(data4 % 1))){
coerced5 = +data4;
}
else {
validate10.errors = [{instancePath:instancePath+"/requestTimeout",schemaPath:"#/properties/requestTimeout/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced5 !== undefined){
data4 = coerced5;
if(data !== undefined){
data["requestTimeout"] = coerced5;
}
}
}
var valid0 = _errs15 === errors;
if(valid0){
let data5 = data.bodyLimit;
const _errs17 = errors;
if(!(((typeof data5 == "number") && (!(data5 % 1) && !isNaN(data5))) && (isFinite(data5)))){
let dataType6 = typeof data5;
let coerced6 = undefined;
if(!(coerced6 !== undefined)){
if(dataType6 === "boolean" || data5 === null
|| (dataType6 === "string" && data5 && data5 == +data5 && !(data5 % 1))){
coerced6 = +data5;
}
else {
validate10.errors = [{instancePath:instancePath+"/bodyLimit",schemaPath:"#/properties/bodyLimit/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced6 !== undefined){
data5 = coerced6;
if(data !== undefined){
data["bodyLimit"] = coerced6;
}
}
}
var valid0 = _errs17 === errors;
if(valid0){
let data6 = data.caseSensitive;
const _errs19 = errors;
if(typeof data6 !== "boolean"){
let coerced7 = undefined;
if(!(coerced7 !== undefined)){
if(data6 === "false" || data6 === 0 || data6 === null){
coerced7 = false;
}
else if(data6 === "true" || data6 === 1){
coerced7 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/caseSensitive",schemaPath:"#/properties/caseSensitive/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced7 !== undefined){
data6 = coerced7;
if(data !== undefined){
data["caseSensitive"] = coerced7;
}
}
}
var valid0 = _errs19 === errors;
if(valid0){
let data7 = data.allowUnsafeRegex;
const _errs21 = errors;
if(typeof data7 !== "boolean"){
let coerced8 = undefined;
if(!(coerced8 !== undefined)){
if(data7 === "false" || data7 === 0 || data7 === null){
coerced8 = false;
}
else if(data7 === "true" || data7 === 1){
coerced8 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/allowUnsafeRegex",schemaPath:"#/properties/allowUnsafeRegex/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced8 !== undefined){
data7 = coerced8;
if(data !== undefined){
data["allowUnsafeRegex"] = coerced8;
}
}
}
var valid0 = _errs21 === errors;
if(valid0){
if(data.http2 !== undefined){
let data8 = data.http2;
const _errs23 = errors;
if(typeof data8 !== "boolean"){
let coerced9 = undefined;
if(!(coerced9 !== undefined)){
if(data8 === "false" || data8 === 0 || data8 === null){
coerced9 = false;
}
else if(data8 === "true" || data8 === 1){
coerced9 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/http2",schemaPath:"#/properties/http2/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced9 !== undefined){
data8 = coerced9;
if(data !== undefined){
data["http2"] = coerced9;
}
}
}
var valid0 = _errs23 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.https !== undefined){
let data9 = data.https;
const _errs25 = errors;
const _errs26 = errors;
let valid2 = true;
const _errs27 = errors;
const _errs28 = errors;
const _errs29 = errors;
const _errs30 = errors;
let valid4 = false;
let passing1 = null;
const _errs31 = errors;
if(typeof data9 !== "boolean"){
let coerced10 = undefined;
if(!(coerced10 !== undefined)){
if(data9 === "false" || data9 === 0 || data9 === null){
coerced10 = false;
}
else if(data9 === "true" || data9 === 1){
coerced10 = true;
}
else {
const err4 = {};
if(vErrors === null){
vErrors = [err4];
}
else {
vErrors.push(err4);
}
errors++;
}
}
if(coerced10 !== undefined){
data9 = coerced10;
if(data !== undefined){
data["https"] = coerced10;
}
}
}
var _valid2 = _errs31 === errors;
if(_valid2){
valid4 = true;
passing1 = 0;
}
const _errs33 = errors;
if(data9 !== null){
let coerced11 = undefined;
if(!(coerced11 !== undefined)){
if(data9 === "" || data9 === 0 || data9 === false){
coerced11 = null;
}
else {
const err5 = {};
if(vErrors === null){
vErrors = [err5];
}
else {
vErrors.push(err5);
}
errors++;
}
}
if(coerced11 !== undefined){
data9 = coerced11;
if(data !== undefined){
data["https"] = coerced11;
}
}
}
var _valid2 = _errs33 === errors;
if(_valid2 && valid4){
valid4 = false;
passing1 = [passing1, 1];
}
else {
if(_valid2){
valid4 = true;
passing1 = 1;
}
const _errs35 = errors;
if(errors === _errs35){
if(data9 && typeof data9 == "object" && !Array.isArray(data9)){
let missing0;
if((data9.allowHTTP1 === undefined) && (missing0 = "allowHTTP1")){
const err6 = {};
if(vErrors === null){
vErrors = [err6];
}
else {
vErrors.push(err6);
}
errors++;
}
else {
const _errs37 = errors;
for(const key1 in data9){
if(!(key1 === "allowHTTP1")){
delete data9[key1];
}
}
if(_errs37 === errors){
if(data9.allowHTTP1 !== undefined){
let data10 = data9.allowHTTP1;
if(typeof data10 !== "boolean"){
let coerced12 = undefined;
if(!(coerced12 !== undefined)){
if(data10 === "false" || data10 === 0 || data10 === null){
coerced12 = false;
}
else if(data10 === "true" || data10 === 1){
coerced12 = true;
}
else {
const err7 = {};
if(vErrors === null){
vErrors = [err7];
}
else {
vErrors.push(err7);
}
errors++;
}
}
if(coerced12 !== undefined){
data10 = coerced12;
if(data9 !== undefined){
data9["allowHTTP1"] = coerced12;
}
}
}
}
}
}
}
else {
const err8 = {};
if(vErrors === null){
vErrors = [err8];
}
else {
vErrors.push(err8);
}
errors++;
}
}
var _valid2 = _errs35 === errors;
if(_valid2 && valid4){
valid4 = false;
passing1 = [passing1, 2];
}
else {
if(_valid2){
valid4 = true;
passing1 = 2;
}
}
}
if(!valid4){
const err9 = {};
if(vErrors === null){
vErrors = [err9];
}
else {
vErrors.push(err9);
}
errors++;
}
else {
errors = _errs30;
if(vErrors !== null){
if(_errs30){
vErrors.length = _errs30;
}
else {
vErrors = null;
}
}
}
var valid3 = _errs29 === errors;
if(valid3){
const err10 = {};
if(vErrors === null){
vErrors = [err10];
}
else {
vErrors.push(err10);
}
errors++;
}
else {
errors = _errs28;
if(vErrors !== null){
if(_errs28){
vErrors.length = _errs28;
}
else {
vErrors = null;
}
}
}
var _valid1 = _errs27 === errors;
errors = _errs26;
if(vErrors !== null){
if(_errs26){
vErrors.length = _errs26;
}
else {
vErrors = null;
}
}
if(_valid1){
const _errs40 = errors;
data["https"] = true;
var _valid1 = _errs40 === errors;
valid2 = _valid1;
}
if(!valid2){
const err11 = {instancePath:instancePath+"/https",schemaPath:"#/properties/https/if",keyword:"if",params:{failingKeyword: "then"},message:"must match \"then\" schema"};
if(vErrors === null){
vErrors = [err11];
}
else {
vErrors.push(err11);
}
errors++;
validate10.errors = vErrors;
return false;
}
var valid0 = _errs25 === errors;
}
else {
var valid0 = true;
}
if(valid0){
let data11 = data.ignoreTrailingSlash;
const _errs41 = errors;
if(typeof data11 !== "boolean"){
let coerced13 = undefined;
if(!(coerced13 !== undefined)){
if(data11 === "false" || data11 === 0 || data11 === null){
coerced13 = false;
}
else if(data11 === "true" || data11 === 1){
coerced13 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/ignoreTrailingSlash",schemaPath:"#/properties/ignoreTrailingSlash/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced13 !== undefined){
data11 = coerced13;
if(data !== undefined){
data["ignoreTrailingSlash"] = coerced13;
}
}
}
var valid0 = _errs41 === errors;
if(valid0){
let data12 = data.ignoreDuplicateSlashes;
const _errs43 = errors;
if(typeof data12 !== "boolean"){
let coerced14 = undefined;
if(!(coerced14 !== undefined)){
if(data12 === "false" || data12 === 0 || data12 === null){
coerced14 = false;
}
else if(data12 === "true" || data12 === 1){
coerced14 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/ignoreDuplicateSlashes",schemaPath:"#/properties/ignoreDuplicateSlashes/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced14 !== undefined){
data12 = coerced14;
if(data !== undefined){
data["ignoreDuplicateSlashes"] = coerced14;
}
}
}
var valid0 = _errs43 === errors;
if(valid0){
let data13 = data.disableRequestLogging;
const _errs45 = errors;
if(typeof data13 !== "boolean"){
let coerced15 = undefined;
if(!(coerced15 !== undefined)){
if(data13 === "false" || data13 === 0 || data13 === null){
coerced15 = false;
}
else if(data13 === "true" || data13 === 1){
coerced15 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/disableRequestLogging",schemaPath:"#/properties/disableRequestLogging/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced15 !== undefined){
data13 = coerced15;
if(data !== undefined){
data["disableRequestLogging"] = coerced15;
}
}
}
var valid0 = _errs45 === errors;
if(valid0){
let data14 = data.jsonShorthand;
const _errs47 = errors;
if(typeof data14 !== "boolean"){
let coerced16 = undefined;
if(!(coerced16 !== undefined)){
if(data14 === "false" || data14 === 0 || data14 === null){
coerced16 = false;
}
else if(data14 === "true" || data14 === 1){
coerced16 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/jsonShorthand",schemaPath:"#/properties/jsonShorthand/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced16 !== undefined){
data14 = coerced16;
if(data !== undefined){
data["jsonShorthand"] = coerced16;
}
}
}
var valid0 = _errs47 === errors;
if(valid0){
let data15 = data.maxParamLength;
const _errs49 = errors;
if(!(((typeof data15 == "number") && (!(data15 % 1) && !isNaN(data15))) && (isFinite(data15)))){
let dataType17 = typeof data15;
let coerced17 = undefined;
if(!(coerced17 !== undefined)){
if(dataType17 === "boolean" || data15 === null
|| (dataType17 === "string" && data15 && data15 == +data15 && !(data15 % 1))){
coerced17 = +data15;
}
else {
validate10.errors = [{instancePath:instancePath+"/maxParamLength",schemaPath:"#/properties/maxParamLength/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced17 !== undefined){
data15 = coerced17;
if(data !== undefined){
data["maxParamLength"] = coerced17;
}
}
}
var valid0 = _errs49 === errors;
if(valid0){
let data16 = data.onProtoPoisoning;
const _errs51 = errors;
if(typeof data16 !== "string"){
let dataType18 = typeof data16;
let coerced18 = undefined;
if(!(coerced18 !== undefined)){
if(dataType18 == "number" || dataType18 == "boolean"){
coerced18 = "" + data16;
}
else if(data16 === null){
coerced18 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/onProtoPoisoning",schemaPath:"#/properties/onProtoPoisoning/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced18 !== undefined){
data16 = coerced18;
if(data !== undefined){
data["onProtoPoisoning"] = coerced18;
}
}
}
var valid0 = _errs51 === errors;
if(valid0){
let data17 = data.onConstructorPoisoning;
const _errs53 = errors;
if(typeof data17 !== "string"){
let dataType19 = typeof data17;
let coerced19 = undefined;
if(!(coerced19 !== undefined)){
if(dataType19 == "number" || dataType19 == "boolean"){
coerced19 = "" + data17;
}
else if(data17 === null){
coerced19 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/onConstructorPoisoning",schemaPath:"#/properties/onConstructorPoisoning/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced19 !== undefined){
data17 = coerced19;
if(data !== undefined){
data["onConstructorPoisoning"] = coerced19;
}
}
}
var valid0 = _errs53 === errors;
if(valid0){
let data18 = data.pluginTimeout;
const _errs55 = errors;
if(!(((typeof data18 == "number") && (!(data18 % 1) && !isNaN(data18))) && (isFinite(data18)))){
let dataType20 = typeof data18;
let coerced20 = undefined;
if(!(coerced20 !== undefined)){
if(dataType20 === "boolean" || data18 === null
|| (dataType20 === "string" && data18 && data18 == +data18 && !(data18 % 1))){
coerced20 = +data18;
}
else {
validate10.errors = [{instancePath:instancePath+"/pluginTimeout",schemaPath:"#/properties/pluginTimeout/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced20 !== undefined){
data18 = coerced20;
if(data !== undefined){
data["pluginTimeout"] = coerced20;
}
}
}
var valid0 = _errs55 === errors;
if(valid0){
let data19 = data.requestIdHeader;
const _errs57 = errors;
const _errs58 = errors;
let valid6 = false;
const _errs59 = errors;
if(!(data19 === false)){
const err12 = {instancePath:instancePath+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf/0/enum",keyword:"enum",params:{allowedValues: schema11.properties.requestIdHeader.anyOf[0].enum},message:"must be equal to one of the allowed values"};
if(vErrors === null){
vErrors = [err12];
}
else {
vErrors.push(err12);
}
errors++;
}
var _valid3 = _errs59 === errors;
valid6 = valid6 || _valid3;
if(!valid6){
const _errs60 = errors;
if(typeof data19 !== "string"){
let dataType21 = typeof data19;
let coerced21 = undefined;
if(!(coerced21 !== undefined)){
if(dataType21 == "number" || dataType21 == "boolean"){
coerced21 = "" + data19;
}
else if(data19 === null){
coerced21 = "";
}
else {
const err13 = {instancePath:instancePath+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf/1/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err13];
}
else {
vErrors.push(err13);
}
errors++;
}
}
if(coerced21 !== undefined){
data19 = coerced21;
if(data !== undefined){
data["requestIdHeader"] = coerced21;
}
}
}
var _valid3 = _errs60 === errors;
valid6 = valid6 || _valid3;
}
if(!valid6){
const err14 = {instancePath:instancePath+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err14];
}
else {
vErrors.push(err14);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs58;
if(vErrors !== null){
if(_errs58){
vErrors.length = _errs58;
}
else {
vErrors = null;
}
}
}
var valid0 = _errs57 === errors;
if(valid0){
let data20 = data.requestIdLogLabel;
const _errs62 = errors;
if(typeof data20 !== "string"){
let dataType22 = typeof data20;
let coerced22 = undefined;
if(!(coerced22 !== undefined)){
if(dataType22 == "number" || dataType22 == "boolean"){
coerced22 = "" + data20;
}
else if(data20 === null){
coerced22 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/requestIdLogLabel",schemaPath:"#/properties/requestIdLogLabel/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced22 !== undefined){
data20 = coerced22;
if(data !== undefined){
data["requestIdLogLabel"] = coerced22;
}
}
}
var valid0 = _errs62 === errors;
if(valid0){
let data21 = data.http2SessionTimeout;
const _errs64 = errors;
if(!(((typeof data21 == "number") && (!(data21 % 1) && !isNaN(data21))) && (isFinite(data21)))){
let dataType23 = typeof data21;
let coerced23 = undefined;
if(!(coerced23 !== undefined)){
if(dataType23 === "boolean" || data21 === null
|| (dataType23 === "string" && data21 && data21 == +data21 && !(data21 % 1))){
coerced23 = +data21;
}
else {
validate10.errors = [{instancePath:instancePath+"/http2SessionTimeout",schemaPath:"#/properties/http2SessionTimeout/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];
return false;
}
}
if(coerced23 !== undefined){
data21 = coerced23;
if(data !== undefined){
data["http2SessionTimeout"] = coerced23;
}
}
}
var valid0 = _errs64 === errors;
if(valid0){
let data22 = data.exposeHeadRoutes;
const _errs66 = errors;
if(typeof data22 !== "boolean"){
let coerced24 = undefined;
if(!(coerced24 !== undefined)){
if(data22 === "false" || data22 === 0 || data22 === null){
coerced24 = false;
}
else if(data22 === "true" || data22 === 1){
coerced24 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/exposeHeadRoutes",schemaPath:"#/properties/exposeHeadRoutes/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced24 !== undefined){
data22 = coerced24;
if(data !== undefined){
data["exposeHeadRoutes"] = coerced24;
}
}
}
var valid0 = _errs66 === errors;
if(valid0){
let data23 = data.useSemicolonDelimiter;
const _errs68 = errors;
if(typeof data23 !== "boolean"){
let coerced25 = undefined;
if(!(coerced25 !== undefined)){
if(data23 === "false" || data23 === 0 || data23 === null){
coerced25 = false;
}
else if(data23 === "true" || data23 === 1){
coerced25 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/useSemicolonDelimiter",schemaPath:"#/properties/useSemicolonDelimiter/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced25 !== undefined){
data23 = coerced25;
if(data !== undefined){
data["useSemicolonDelimiter"] = coerced25;
}
}
}
var valid0 = _errs68 === errors;
if(valid0){
if(data.versioning !== undefined){
let data24 = data.versioning;
const _errs70 = errors;
if(errors === _errs70){
if(data24 && typeof data24 == "object" && !Array.isArray(data24)){
let missing1;
if(((data24.storage === undefined) && (missing1 = "storage")) || ((data24.deriveVersion === undefined) && (missing1 = "deriveVersion"))){
validate10.errors = [{instancePath:instancePath+"/versioning",schemaPath:"#/properties/versioning/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];
return false;
}
}
else {
validate10.errors = [{instancePath:instancePath+"/versioning",schemaPath:"#/properties/versioning/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs70 === errors;
}
else {
var valid0 = true;
}
if(valid0){
if(data.constraints !== undefined){
let data25 = data.constraints;
const _errs73 = errors;
if(errors === _errs73){
if(data25 && typeof data25 == "object" && !Array.isArray(data25)){
for(const key2 in data25){
let data26 = data25[key2];
const _errs76 = errors;
if(errors === _errs76){
if(data26 && typeof data26 == "object" && !Array.isArray(data26)){
let missing2;
if(((((data26.name === undefined) && (missing2 = "name")) || ((data26.storage === undefined) && (missing2 = "storage"))) || ((data26.validate === undefined) && (missing2 = "validate"))) || ((data26.deriveConstraint === undefined) && (missing2 = "deriveConstraint"))){
validate10.errors = [{instancePath:instancePath+"/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"),schemaPath:"#/properties/constraints/additionalProperties/required",keyword:"required",params:{missingProperty: missing2},message:"must have required property '"+missing2+"'"}];
return false;
}
else {
if(data26.name !== undefined){
let data27 = data26.name;
if(typeof data27 !== "string"){
let dataType26 = typeof data27;
let coerced26 = undefined;
if(!(coerced26 !== undefined)){
if(dataType26 == "number" || dataType26 == "boolean"){
coerced26 = "" + data27;
}
else if(data27 === null){
coerced26 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1")+"/name",schemaPath:"#/properties/constraints/additionalProperties/properties/name/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced26 !== undefined){
data27 = coerced26;
if(data26 !== undefined){
data26["name"] = coerced26;
}
}
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"),schemaPath:"#/properties/constraints/additionalProperties/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid7 = _errs76 === errors;
if(!valid7){
break;
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/constraints",schemaPath:"#/properties/constraints/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid0 = _errs73 === errors;
}
else {
var valid0 = true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
else {
validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
validate10.errors = vErrors;
return errors === 0;
}
module.exports.defaultInitOptions = {"connectionTimeout":0,"keepAliveTimeout":72000,"maxRequestsPerSocket":0,"requestTimeout":0,"bodyLimit":1048576,"caseSensitive":true,"allowUnsafeRegex":false,"disableRequestLogging":false,"jsonShorthand":true,"ignoreTrailingSlash":false,"ignoreDuplicateSlashes":false,"maxParamLength":100,"onProtoPoisoning":"error","onConstructorPoisoning":"error","pluginTimeout":10000,"requestIdHeader":"request-id","requestIdLogLabel":"reqId","http2SessionTimeout":72000,"exposeHeadRoutes":true,"useSemicolonDelimiter":true}
/***/ }),
/***/ 76696:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { AsyncResource } = __nccwpck_require__(92761)
const { FifoMap: Fifo } = __nccwpck_require__(76420)
const { safeParse: safeParseContentType, defaultContentType } = __nccwpck_require__(46673)
const secureJson = __nccwpck_require__(70707)
const {
kDefaultJsonParse,
kContentTypeParser,
kBodyLimit,
kRequestPayloadStream,
kState,
kTestInternals,
kReplyIsError,
kRouteContext
} = __nccwpck_require__(28622)
const {
FST_ERR_CTP_INVALID_TYPE,
FST_ERR_CTP_EMPTY_TYPE,
FST_ERR_CTP_ALREADY_PRESENT,
FST_ERR_CTP_INVALID_HANDLER,
FST_ERR_CTP_INVALID_PARSE_TYPE,
FST_ERR_CTP_BODY_TOO_LARGE,
FST_ERR_CTP_INVALID_MEDIA_TYPE,
FST_ERR_CTP_INVALID_CONTENT_LENGTH,
FST_ERR_CTP_EMPTY_JSON_BODY,
FST_ERR_CTP_INSTANCE_ALREADY_STARTED
} = __nccwpck_require__(89005)
function ContentTypeParser (bodyLimit, onProtoPoisoning, onConstructorPoisoning) {
this[kDefaultJsonParse] = getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning)
// using a map instead of a plain object to avoid prototype hijack attacks
this.customParsers = new Map()
this.customParsers.set('application/json', new Parser(true, false, bodyLimit, this[kDefaultJsonParse]))
this.customParsers.set('text/plain', new Parser(true, false, bodyLimit, defaultPlainTextParser))
this.parserList = [new ParserListItem('application/json'), new ParserListItem('text/plain')]
this.parserRegExpList = []
this.cache = new Fifo(100)
}
ContentTypeParser.prototype.add = function (contentType, opts, parserFn) {
const contentTypeIsString = typeof contentType === 'string'
if (!contentTypeIsString && !(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()
if (contentTypeIsString && contentType.length === 0) throw new FST_ERR_CTP_EMPTY_TYPE()
if (typeof parserFn !== 'function') throw new FST_ERR_CTP_INVALID_HANDLER()
if (this.existingParser(contentType)) {
throw new FST_ERR_CTP_ALREADY_PRESENT(contentType)
}
if (opts.parseAs !== undefined) {
if (opts.parseAs !== 'string' && opts.parseAs !== 'buffer') {
throw new FST_ERR_CTP_INVALID_PARSE_TYPE(opts.parseAs)
}
}
const parser = new Parser(
opts.parseAs === 'string',
opts.parseAs === 'buffer',
opts.bodyLimit,
parserFn
)
if (contentTypeIsString && contentType === '*') {
this.customParsers.set('', parser)
} else {
if (contentTypeIsString) {
this.parserList.unshift(new ParserListItem(contentType))
} else {
contentType.isEssence = contentType.source.indexOf(';') === -1
this.parserRegExpList.unshift(contentType)
}
this.customParsers.set(contentType.toString(), parser)
}
}
ContentTypeParser.prototype.hasParser = function (contentType) {
return this.customParsers.has(typeof contentType === 'string' ? contentType : contentType.toString())
}
ContentTypeParser.prototype.existingParser = function (contentType) {
if (contentType === 'application/json' && this.customParsers.has(contentType)) {
return this.customParsers.get(contentType).fn !== this[kDefaultJsonParse]
}
if (contentType === 'text/plain' && this.customParsers.has(contentType)) {
return this.customParsers.get(contentType).fn !== defaultPlainTextParser
}
return this.hasParser(contentType)
}
ContentTypeParser.prototype.getParser = function (contentType) {
if (this.hasParser(contentType)) {
return this.customParsers.get(contentType)
}
const parser = this.cache.get(contentType)
if (parser !== undefined) return parser
const parsed = safeParseContentType(contentType)
// dummyContentType always the same object
// we can use === for the comparison and return early
if (parsed === defaultContentType) {
return this.customParsers.get('')
}
// eslint-disable-next-line no-var
for (var i = 0; i !== this.parserList.length; ++i) {
const parserListItem = this.parserList[i]
if (compareContentType(parsed, parserListItem)) {
const parser = this.customParsers.get(parserListItem.name)
// we set request content-type in cache to reduce parsing of MIME type
this.cache.set(contentType, parser)
return parser
}
}
// eslint-disable-next-line no-var
for (var j = 0; j !== this.parserRegExpList.length; ++j) {
const parserRegExp = this.parserRegExpList[j]
if (compareRegExpContentType(contentType, parsed.type, parserRegExp)) {
const parser = this.customParsers.get(parserRegExp.toString())
// we set request content-type in cache to reduce parsing of MIME type
this.cache.set(contentType, parser)
return parser
}
}
return this.customParsers.get('')
}
ContentTypeParser.prototype.removeAll = function () {
this.customParsers = new Map()
this.parserRegExpList = []
this.parserList = []
this.cache = new Fifo(100)
}
ContentTypeParser.prototype.remove = function (contentType) {
if (!(typeof contentType === 'string' || contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()
const removed = this.customParsers.delete(contentType.toString())
const parsers = typeof contentType === 'string' ? this.parserList : this.parserRegExpList
const idx = parsers.findIndex(ct => ct.toString() === contentType.toString())
if (idx > -1) {
parsers.splice(idx, 1)
}
return removed || idx > -1
}
ContentTypeParser.prototype.run = function (contentType, handler, request, reply) {
const parser = this.getParser(contentType)
if (parser === undefined) {
if (request.is404) {
handler(request, reply)
} else {
reply.send(new FST_ERR_CTP_INVALID_MEDIA_TYPE(contentType || undefined))
}
// Early return to avoid allocating an AsyncResource if it's not needed
return
}
const resource = new AsyncResource('content-type-parser:run', request)
if (parser.asString === true || parser.asBuffer === true) {
rawBody(
request,
reply,
reply[kRouteContext]._parserOptions,
parser,
done
)
} else {
const result = parser.fn(request, request[kRequestPayloadStream], done)
if (result && typeof result.then === 'function') {
result.then(body => done(null, body), done)
}
}
function done (error, body) {
// We cannot use resource.bind() because it is broken in node v12 and v14
resource.runInAsyncScope(() => {
resource.emitDestroy()
if (error) {
reply[kReplyIsError] = true
reply.send(error)
} else {
request.body = body
handler(request, reply)
}
})
}
}
function rawBody (request, reply, options, parser, done) {
const asString = parser.asString
const limit = options.limit === null ? parser.bodyLimit : options.limit
const contentLength = request.headers['content-length'] === undefined
? NaN
: Number(request.headers['content-length'])
if (contentLength > limit) {
// We must close the connection as the client is going
// to send this data anyway
reply.header('connection', 'close')
reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())
return
}
let receivedLength = 0
let body = asString === true ? '' : []
const payload = request[kRequestPayloadStream] || request.raw
if (asString === true) {
payload.setEncoding('utf8')
}
payload.on('data', onData)
payload.on('end', onEnd)
payload.on('error', onEnd)
payload.resume()
function onData (chunk) {
receivedLength += chunk.length
const { receivedEncodedLength = 0 } = payload
// The resulting body length must not exceed bodyLimit (see "zip bomb").
// The case when encoded length is larger than received length is rather theoretical,
// unless the stream returned by preParsing hook is broken and reports wrong value.
if (receivedLength > limit || receivedEncodedLength > limit) {
payload.removeListener('data', onData)
payload.removeListener('end', onEnd)
payload.removeListener('error', onEnd)
reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())
return
}
if (asString === true) {
body += chunk
} else {
body.push(chunk)
}
}
function onEnd (err) {
payload.removeListener('data', onData)
payload.removeListener('end', onEnd)
payload.removeListener('error', onEnd)
if (err !== undefined) {
if (!(typeof err.statusCode === 'number' && err.statusCode >= 400)) {
err.statusCode = 400
}
reply[kReplyIsError] = true
reply.code(err.statusCode).send(err)
return
}
if (asString === true) {
receivedLength = Buffer.byteLength(body)
}
if (!Number.isNaN(contentLength) && (payload.receivedEncodedLength || receivedLength) !== contentLength) {
reply.header('connection', 'close')
reply.send(new FST_ERR_CTP_INVALID_CONTENT_LENGTH())
return
}
if (asString === false) {
body = Buffer.concat(body)
}
const result = parser.fn(request, body, done)
if (result && typeof result.then === 'function') {
result.then(body => done(null, body), done)
}
}
}
function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {
return defaultJsonParser
function defaultJsonParser (req, body, done) {
if (body === '' || body == null || (Buffer.isBuffer(body) && body.length === 0)) {
return done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)
}
let json
try {
json = secureJson.parse(body, { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning })
} catch (err) {
err.statusCode = 400
return done(err, undefined)
}
done(null, json)
}
}
function defaultPlainTextParser (req, body, done) {
done(null, body)
}
function Parser (asString, asBuffer, bodyLimit, fn) {
this.asString = asString
this.asBuffer = asBuffer
this.bodyLimit = bodyLimit
this.fn = fn
}
function buildContentTypeParser (c) {
const contentTypeParser = new ContentTypeParser()
contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]
contentTypeParser.customParsers = new Map(c.customParsers.entries())
contentTypeParser.parserList = c.parserList.slice()
contentTypeParser.parserRegExpList = c.parserRegExpList.slice()
return contentTypeParser
}
function addContentTypeParser (contentType, opts, parser) {
if (this[kState].started) {
throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED('addContentTypeParser')
}
if (typeof opts === 'function') {
parser = opts
opts = {}
}
if (!opts) opts = {}
if (!opts.bodyLimit) opts.bodyLimit = this[kBodyLimit]
if (Array.isArray(contentType)) {
contentType.forEach((type) => this[kContentTypeParser].add(type, opts, parser))
} else {
this[kContentTypeParser].add(contentType, opts, parser)
}
return this
}
function hasContentTypeParser (contentType) {
return this[kContentTypeParser].hasParser(contentType)
}
function removeContentTypeParser (contentType) {
if (this[kState].started) {
throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED('removeContentTypeParser')
}
if (Array.isArray(contentType)) {
for (const type of contentType) {
this[kContentTypeParser].remove(type)
}
} else {
this[kContentTypeParser].remove(contentType)
}
}
function removeAllContentTypeParsers () {
if (this[kState].started) {
throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED('removeAllContentTypeParsers')
}
this[kContentTypeParser].removeAll()
}
function compareContentType (contentType, parserListItem) {
if (parserListItem.isEssence) {
// we do essence check
return contentType.type.indexOf(parserListItem) !== -1
} else {
// when the content-type includes parameters
// we do a full-text search
// reject essence content-type before checking parameters
if (contentType.type.indexOf(parserListItem.type) === -1) return false
for (const key of parserListItem.parameterKeys) {
// reject when missing parameters
if (!(key in contentType.parameters)) return false
// reject when parameters do not match
if (contentType.parameters[key] !== parserListItem.parameters[key]) return false
}
return true
}
}
function compareRegExpContentType (contentType, essenceMIMEType, regexp) {
if (regexp.isEssence) {
// we do essence check
return regexp.test(essenceMIMEType)
} else {
// when the content-type includes parameters
// we do a full-text match
return regexp.test(contentType)
}
}
function ParserListItem (contentType) {
this.name = contentType
// we pre-calculate all the needed information
// before content-type comparison
const parsed = safeParseContentType(contentType)
this.isEssence = contentType.indexOf(';') === -1
// we should not allow empty string for parser list item
// because it would become a match-all handler
if (this.isEssence === false && parsed.type === '') {
// handle semicolon or empty string
const tmp = contentType.split(';', 1)[0]
this.type = tmp === '' ? contentType : tmp
} else {
this.type = parsed.type
}
this.parameters = parsed.parameters
this.parameterKeys = Object.keys(parsed.parameters)
}
// used in ContentTypeParser.remove
ParserListItem.prototype.toString = function () {
return this.name
}
module.exports = ContentTypeParser
module.exports.helpers = {
buildContentTypeParser,
addContentTypeParser,
hasContentTypeParser,
removeContentTypeParser,
removeAllContentTypeParsers
}
module.exports.defaultParsers = {
getDefaultJsonParser,
defaultTextParser: defaultPlainTextParser
}
module.exports[kTestInternals] = { rawBody }
/***/ }),
/***/ 76676:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kFourOhFourContext,
kReplySerializerDefault,
kSchemaErrorFormatter,
kErrorHandler,
kChildLoggerFactory,
kOptions,
kReply,
kRequest,
kBodyLimit,
kLogLevel,
kContentTypeParser,
kRouteByFastify,
kRequestCacheValidateFns,
kReplyCacheSerializeFns,
kPublicRouteContext
} = __nccwpck_require__(28622)
// Object that holds the context of every request
// Every route holds an instance of this object.
function Context ({
schema,
handler,
config,
requestIdLogLabel,
childLoggerFactory,
errorHandler,
bodyLimit,
logLevel,
logSerializers,
attachValidation,
validatorCompiler,
serializerCompiler,
replySerializer,
schemaErrorFormatter,
exposeHeadRoute,
prefixTrailingSlash,
server,
isFastify
}) {
this.schema = schema
this.handler = handler
this.Reply = server[kReply]
this.Request = server[kRequest]
this.contentTypeParser = server[kContentTypeParser]
this.onRequest = null
this.onSend = null
this.onError = null
this.onTimeout = null
this.preHandler = null
this.onResponse = null
this.preSerialization = null
this.onRequestAbort = null
this.config = config
this.errorHandler = errorHandler || server[kErrorHandler]
this.requestIdLogLabel = requestIdLogLabel || server[kOptions].requestIdLogLabel
this.childLoggerFactory = childLoggerFactory || server[kChildLoggerFactory]
this._middie = null
this._parserOptions = {
limit: bodyLimit || server[kBodyLimit]
}
this.exposeHeadRoute = exposeHeadRoute
this.prefixTrailingSlash = prefixTrailingSlash
this.logLevel = logLevel || server[kLogLevel]
this.logSerializers = logSerializers
this[kFourOhFourContext] = null
this.attachValidation = attachValidation
this[kReplySerializerDefault] = replySerializer
this.schemaErrorFormatter =
schemaErrorFormatter ||
server[kSchemaErrorFormatter] ||
defaultSchemaErrorFormatter
this[kRouteByFastify] = isFastify
this[kRequestCacheValidateFns] = null
this[kReplyCacheSerializeFns] = null
this.validatorCompiler = validatorCompiler || null
this.serializerCompiler = serializerCompiler || null
// Route + Userland configurations for the route
this[kPublicRouteContext] = getPublicRouteContext(this)
this.server = server
}
function getPublicRouteContext (context) {
return Object.create(null, {
schema: {
enumerable: true,
get () {
return context.schema
}
},
config: {
enumerable: true,
get () {
return context.config
}
}
})
}
function defaultSchemaErrorFormatter (errors, dataVar) {
let text = ''
const separator = ', '
// eslint-disable-next-line no-var
for (var i = 0; i !== errors.length; ++i) {
const e = errors[i]
text += dataVar + (e.instancePath || '') + ' ' + e.message + separator
}
return new Error(text.slice(0, -separator.length))
}
module.exports = Context
/***/ }),
/***/ 7629:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const {
kReply,
kRequest,
kState,
kHasBeenDecorated
} = __nccwpck_require__(28622)
const {
FST_ERR_DEC_ALREADY_PRESENT,
FST_ERR_DEC_MISSING_DEPENDENCY,
FST_ERR_DEC_AFTER_START,
FST_ERR_DEC_DEPENDENCY_INVALID_TYPE
} = __nccwpck_require__(89005)
const { FSTDEP006 } = __nccwpck_require__(59283)
function decorate (instance, name, fn, dependencies) {
if (Object.prototype.hasOwnProperty.call(instance, name)) {
throw new FST_ERR_DEC_ALREADY_PRESENT(name)
}
checkDependencies(instance, name, dependencies)
if (fn && (typeof fn.getter === 'function' || typeof fn.setter === 'function')) {
Object.defineProperty(instance, name, {
get: fn.getter,
set: fn.setter
})
} else {
instance[name] = fn
}
}
function decorateConstructor (konstructor, name, fn, dependencies) {
const instance = konstructor.prototype
if (Object.prototype.hasOwnProperty.call(instance, name) || hasKey(konstructor, name)) {
throw new FST_ERR_DEC_ALREADY_PRESENT(name)
}
konstructor[kHasBeenDecorated] = true
checkDependencies(konstructor, name, dependencies)
if (fn && (typeof fn.getter === 'function' || typeof fn.setter === 'function')) {
Object.defineProperty(instance, name, {
get: fn.getter,
set: fn.setter
})
} else if (typeof fn === 'function') {
instance[name] = fn
} else {
konstructor.props.push({ key: name, value: fn })
}
}
function checkReferenceType (name, fn) {
if (typeof fn === 'object' && fn && !(typeof fn.getter === 'function' || typeof fn.setter === 'function')) {
FSTDEP006(name)
}
}
function decorateFastify (name, fn, dependencies) {
assertNotStarted(this, name)
decorate(this, name, fn, dependencies)
return this
}
function checkExistence (instance, name) {
if (name) {
return name in instance || (instance.prototype && name in instance.prototype) || hasKey(instance, name)
}
return instance in this
}
function hasKey (fn, name) {
if (fn.props) {
return fn.props.find(({ key }) => key === name)
}
return false
}
function checkRequestExistence (name) {
if (name && hasKey(this[kRequest], name)) return true
return checkExistence(this[kRequest].prototype, name)
}
function checkReplyExistence (name) {
if (name && hasKey(this[kReply], name)) return true
return checkExistence(this[kReply].prototype, name)
}
function checkDependencies (instance, name, deps) {
if (deps === undefined || deps === null) {
return
}
if (!Array.isArray(deps)) {
throw new FST_ERR_DEC_DEPENDENCY_INVALID_TYPE(name)
}
// eslint-disable-next-line no-var
for (var i = 0; i !== deps.length; ++i) {
if (!checkExistence(instance, deps[i])) {
throw new FST_ERR_DEC_MISSING_DEPENDENCY(deps[i])
}
}
}
function decorateReply (name, fn, dependencies) {
assertNotStarted(this, name)
checkReferenceType(name, fn)
decorateConstructor(this[kReply], name, fn, dependencies)
return this
}
function decorateRequest (name, fn, dependencies) {
assertNotStarted(this, name)
checkReferenceType(name, fn)
decorateConstructor(this[kRequest], name, fn, dependencies)
return this
}
function assertNotStarted (instance, name) {
if (instance[kState].started) {
throw new FST_ERR_DEC_AFTER_START(name)
}
}
module.exports = {
add: decorateFastify,
exist: checkExistence,
existRequest: checkRequestExistence,
existReply: checkReplyExistence,
dependencies: checkDependencies,
decorateReply,
decorateRequest
}
/***/ }),
/***/ 58755:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const statusCodes = (__nccwpck_require__(88849).STATUS_CODES)
const wrapThenable = __nccwpck_require__(20195)
const {
kReplyHeaders,
kReplyNextErrorHandler,
kReplyIsRunningOnErrorHook,
kReplyHasStatusCode,
kRouteContext,
kDisableRequestLogging
} = __nccwpck_require__(28622)
const {
FST_ERR_REP_INVALID_PAYLOAD_TYPE,
FST_ERR_FAILED_ERROR_SERIALIZATION
} = __nccwpck_require__(89005)
const { getSchemaSerializer } = __nccwpck_require__(48122)
const serializeError = __nccwpck_require__(65785)
const rootErrorHandler = {
func: defaultErrorHandler,
toJSON () {
return this.func.name.toString() + '()'
}
}
function handleError (reply, error, cb) {
reply[kReplyIsRunningOnErrorHook] = false
const context = reply[kRouteContext]
if (reply[kReplyNextErrorHandler] === false) {
fallbackErrorHandler(error, reply, function (reply, payload) {
try {
reply.raw.writeHead(reply.raw.statusCode, reply[kReplyHeaders])
} catch (error) {
if (!reply.log[kDisableRequestLogging]) {
reply.log.warn(
{ req: reply.request, res: reply, err: error },
error && error.message
)
}
reply.raw.writeHead(reply.raw.statusCode)
}
reply.raw.end(payload)
})
return
}
const errorHandler = reply[kReplyNextErrorHandler] || context.errorHandler
// In case the error handler throws, we set the next errorHandler so we can error again
reply[kReplyNextErrorHandler] = Object.getPrototypeOf(errorHandler)
// we need to remove content-type to allow content-type guessing for serialization
delete reply[kReplyHeaders]['content-type']
delete reply[kReplyHeaders]['content-length']
const func = errorHandler.func
if (!func) {
reply[kReplyNextErrorHandler] = false
fallbackErrorHandler(error, reply, cb)
return
}
try {
const result = func(error, reply.request, reply)
if (result !== undefined) {
if (result !== null && typeof result.then === 'function') {
wrapThenable(result, reply)
} else {
reply.send(result)
}
}
} catch (err) {
reply.send(err)
}
}
function defaultErrorHandler (error, request, reply) {
setErrorHeaders(error, reply)
if (!reply[kReplyHasStatusCode] || reply.statusCode === 200) {
const statusCode = error.statusCode || error.status
reply.code(statusCode >= 400 ? statusCode : 500)
}
if (reply.statusCode < 500) {
if (!reply.log[kDisableRequestLogging]) {
reply.log.info(
{ res: reply, err: error },
error && error.message
)
}
} else {
if (!reply.log[kDisableRequestLogging]) {
reply.log.error(
{ req: request, res: reply, err: error },
error && error.message
)
}
}
reply.send(error)
}
function fallbackErrorHandler (error, reply, cb) {
const res = reply.raw
const statusCode = reply.statusCode
reply[kReplyHeaders]['content-type'] = reply[kReplyHeaders]['content-type'] ?? 'application/json; charset=utf-8'
let payload
try {
const serializerFn = getSchemaSerializer(reply[kRouteContext], statusCode, reply[kReplyHeaders]['content-type'])
payload = (serializerFn === false)
? serializeError({
error: statusCodes[statusCode + ''],
code: error.code,
message: error.message,
statusCode
})
: serializerFn(Object.create(error, {
error: { value: statusCodes[statusCode + ''] },
message: { value: error.message },
statusCode: { value: statusCode }
}))
} catch (err) {
if (!reply.log[kDisableRequestLogging]) {
// error is always FST_ERR_SCH_SERIALIZATION_BUILD because this is called from route/compileSchemasForSerialization
reply.log.error({ err, statusCode: res.statusCode }, 'The serializer for the given status code failed')
}
reply.code(500)
payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error.message))
}
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload))
}
reply[kReplyHeaders]['content-length'] = '' + Buffer.byteLength(payload)
cb(reply, payload)
}
function buildErrorHandler (parent = rootErrorHandler, func) {
if (!func) {
return parent
}
const errorHandler = Object.create(parent)
errorHandler.func = func
return errorHandler
}
function setErrorHeaders (error, reply) {
const res = reply.raw
let statusCode = res.statusCode
statusCode = (statusCode >= 400) ? statusCode : 500
// treat undefined and null as same
if (error != null) {
if (error.headers !== undefined) {
reply.headers(error.headers)
}
if (error.status >= 400) {
statusCode = error.status
} else if (error.statusCode >= 400) {
statusCode = error.statusCode
}
}
res.statusCode = statusCode
}
module.exports = {
buildErrorHandler,
handleError
}
/***/ }),
/***/ 65785:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// This file is autogenerated by build/build-error-serializer.js, do not edit
/* istanbul ignore file */
const { dependencies } = __nccwpck_require__(23591)
const { Serializer, Validator } = dependencies
const serializerState = {"mode":"standalone"}
const serializer = Serializer.restoreFromState(serializerState)
const validator = null
module.exports = function anonymous(validator,serializer
) {
// #
function anonymous0 (input) {
const obj = (input && typeof input.toJSON === 'function')
? input.toJSON()
: input
if (obj === null) return '{}'
let json = '{'
let addComma = false
if (obj["statusCode"] !== undefined) {
!addComma && (addComma = true) || (json += ',')
json += "\"statusCode\":"
json += serializer.asNumber(obj["statusCode"])
}
if (obj["code"] !== undefined) {
!addComma && (addComma = true) || (json += ',')
json += "\"code\":"
json += serializer.asString(obj["code"])
}
if (obj["error"] !== undefined) {
!addComma && (addComma = true) || (json += ',')
json += "\"error\":"
json += serializer.asString(obj["error"])
}
if (obj["message"] !== undefined) {
!addComma && (addComma = true) || (json += ',')
json += "\"message\":"
json += serializer.asString(obj["message"])
}
return json + '}'
}
const main = anonymous0
return main
}(validator, serializer)
/***/ }),
/***/ 89005:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const createError = __nccwpck_require__(22259)
const codes = {
/**
* Basic
*/
FST_ERR_NOT_FOUND: createError(
'FST_ERR_NOT_FOUND',
'Not Found',
404
),
FST_ERR_OPTIONS_NOT_OBJ: createError(
'FST_ERR_OPTIONS_NOT_OBJ',
'Options must be an object',
500,
TypeError
),
FST_ERR_QSP_NOT_FN: createError(
'FST_ERR_QSP_NOT_FN',
"querystringParser option should be a function, instead got '%s'",
500,
TypeError
),
FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN: createError(
'FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN',
"schemaController.bucket option should be a function, instead got '%s'",
500,
TypeError
),
FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN: createError(
'FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN',
"schemaErrorFormatter option should be a non async function. Instead got '%s'.",
500,
TypeError
),
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ: createError(
'FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ',
"ajv.customOptions option should be an object, instead got '%s'",
500,
TypeError
),
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR: createError(
'FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR',
"ajv.plugins option should be an array, instead got '%s'",
500,
TypeError
),
FST_ERR_VERSION_CONSTRAINT_NOT_STR: createError(
'FST_ERR_VERSION_CONSTRAINT_NOT_STR',
'Version constraint should be a string.',
500,
TypeError
),
FST_ERR_VALIDATION: createError(
'FST_ERR_VALIDATION',
'%s',
400
),
FST_ERR_LISTEN_OPTIONS_INVALID: createError(
'FST_ERR_LISTEN_OPTIONS_INVALID',
"Invalid listen options: '%s'",
500,
TypeError
),
FST_ERR_ERROR_HANDLER_NOT_FN: createError(
'FST_ERR_ERROR_HANDLER_NOT_FN',
'Error Handler must be a function',
500,
TypeError
),
/**
* ContentTypeParser
*/
FST_ERR_CTP_ALREADY_PRESENT: createError(
'FST_ERR_CTP_ALREADY_PRESENT',
"Content type parser '%s' already present."
),
FST_ERR_CTP_INVALID_TYPE: createError(
'FST_ERR_CTP_INVALID_TYPE',
'The content type should be a string or a RegExp',
500,
TypeError
),
FST_ERR_CTP_EMPTY_TYPE: createError(
'FST_ERR_CTP_EMPTY_TYPE',
'The content type cannot be an empty string',
500,
TypeError
),
FST_ERR_CTP_INVALID_HANDLER: createError(
'FST_ERR_CTP_INVALID_HANDLER',
'The content type handler should be a function',
500,
TypeError
),
FST_ERR_CTP_INVALID_PARSE_TYPE: createError(
'FST_ERR_CTP_INVALID_PARSE_TYPE',
"The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.",
500,
TypeError
),
FST_ERR_CTP_BODY_TOO_LARGE: createError(
'FST_ERR_CTP_BODY_TOO_LARGE',
'Request body is too large',
413,
RangeError
),
FST_ERR_CTP_INVALID_MEDIA_TYPE: createError(
'FST_ERR_CTP_INVALID_MEDIA_TYPE',
'Unsupported Media Type: %s',
415
),
FST_ERR_CTP_INVALID_CONTENT_LENGTH: createError(
'FST_ERR_CTP_INVALID_CONTENT_LENGTH',
'Request body size did not match Content-Length',
400,
RangeError
),
FST_ERR_CTP_EMPTY_JSON_BODY: createError(
'FST_ERR_CTP_EMPTY_JSON_BODY',
"Body cannot be empty when content-type is set to 'application/json'",
400
),
FST_ERR_CTP_INSTANCE_ALREADY_STARTED: createError(
'FST_ERR_CTP_INSTANCE_ALREADY_STARTED',
'Cannot call "%s" when fastify instance is already started!',
400
),
/**
* decorate
*/
FST_ERR_DEC_ALREADY_PRESENT: createError(
'FST_ERR_DEC_ALREADY_PRESENT',
"The decorator '%s' has already been added!"
),
FST_ERR_DEC_DEPENDENCY_INVALID_TYPE: createError(
'FST_ERR_DEC_DEPENDENCY_INVALID_TYPE',
"The dependencies of decorator '%s' must be of type Array.",
500,
TypeError
),
FST_ERR_DEC_MISSING_DEPENDENCY: createError(
'FST_ERR_DEC_MISSING_DEPENDENCY',
"The decorator is missing dependency '%s'."
),
FST_ERR_DEC_AFTER_START: createError(
'FST_ERR_DEC_AFTER_START',
"The decorator '%s' has been added after start!"
),
/**
* hooks
*/
FST_ERR_HOOK_INVALID_TYPE: createError(
'FST_ERR_HOOK_INVALID_TYPE',
'The hook name must be a string',
500,
TypeError
),
FST_ERR_HOOK_INVALID_HANDLER: createError(
'FST_ERR_HOOK_INVALID_HANDLER',
'%s hook should be a function, instead got %s',
500,
TypeError
),
FST_ERR_HOOK_INVALID_ASYNC_HANDLER: createError(
'FST_ERR_HOOK_INVALID_ASYNC_HANDLER',
'Async function has too many arguments. Async hooks should not use the \'done\' argument.',
500,
TypeError
),
FST_ERR_HOOK_NOT_SUPPORTED: createError(
'FST_ERR_HOOK_NOT_SUPPORTED',
'%s hook not supported!',
500,
TypeError
),
/**
* Middlewares
*/
FST_ERR_MISSING_MIDDLEWARE: createError(
'FST_ERR_MISSING_MIDDLEWARE',
'You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.',
500
),
FST_ERR_HOOK_TIMEOUT: createError(
'FST_ERR_HOOK_TIMEOUT',
"A callback for '%s' hook timed out. You may have forgotten to call 'done' function or to resolve a Promise"
),
/**
* logger
*/
FST_ERR_LOG_INVALID_DESTINATION: createError(
'FST_ERR_LOG_INVALID_DESTINATION',
'Cannot specify both logger.stream and logger.file options'
),
FST_ERR_LOG_INVALID_LOGGER: createError(
'FST_ERR_LOG_INVALID_LOGGER',
"Invalid logger object provided. The logger instance should have these functions(s): '%s'.",
500,
TypeError
),
/**
* reply
*/
FST_ERR_REP_INVALID_PAYLOAD_TYPE: createError(
'FST_ERR_REP_INVALID_PAYLOAD_TYPE',
"Attempted to send payload of invalid type '%s'. Expected a string or Buffer.",
500,
TypeError
),
FST_ERR_REP_RESPONSE_BODY_CONSUMED: createError(
'FST_ERR_REP_RESPONSE_BODY_CONSUMED',
'Response.body is already consumed.'
),
FST_ERR_REP_ALREADY_SENT: createError(
'FST_ERR_REP_ALREADY_SENT',
'Reply was already sent, did you forget to "return reply" in "%s" (%s)?'
),
FST_ERR_REP_SENT_VALUE: createError(
'FST_ERR_REP_SENT_VALUE',
'The only possible value for reply.sent is true.',
500,
TypeError
),
FST_ERR_SEND_INSIDE_ONERR: createError(
'FST_ERR_SEND_INSIDE_ONERR',
'You cannot use `send` inside the `onError` hook'
),
FST_ERR_SEND_UNDEFINED_ERR: createError(
'FST_ERR_SEND_UNDEFINED_ERR',
'Undefined error has occurred'
),
FST_ERR_BAD_STATUS_CODE: createError(
'FST_ERR_BAD_STATUS_CODE',
'Called reply with an invalid status code: %s'
),
FST_ERR_BAD_TRAILER_NAME: createError(
'FST_ERR_BAD_TRAILER_NAME',
'Called reply.trailer with an invalid header name: %s'
),
FST_ERR_BAD_TRAILER_VALUE: createError(
'FST_ERR_BAD_TRAILER_VALUE',
"Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function."
),
FST_ERR_FAILED_ERROR_SERIALIZATION: createError(
'FST_ERR_FAILED_ERROR_SERIALIZATION',
'Failed to serialize an error. Error: %s. Original error: %s'
),
FST_ERR_MISSING_SERIALIZATION_FN: createError(
'FST_ERR_MISSING_SERIALIZATION_FN',
'Missing serialization function. Key "%s"'
),
FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN: createError(
'FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN',
'Missing serialization function. Key "%s:%s"'
),
FST_ERR_REQ_INVALID_VALIDATION_INVOCATION: createError(
'FST_ERR_REQ_INVALID_VALIDATION_INVOCATION',
'Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.'
),
/**
* schemas
*/
FST_ERR_SCH_MISSING_ID: createError(
'FST_ERR_SCH_MISSING_ID',
'Missing schema $id property'
),
FST_ERR_SCH_ALREADY_PRESENT: createError(
'FST_ERR_SCH_ALREADY_PRESENT',
"Schema with id '%s' already declared!"
),
FST_ERR_SCH_CONTENT_MISSING_SCHEMA: createError(
'FST_ERR_SCH_CONTENT_MISSING_SCHEMA',
"Schema is missing for the content type '%s'"
),
FST_ERR_SCH_DUPLICATE: createError(
'FST_ERR_SCH_DUPLICATE',
"Schema with '%s' already present!"
),
FST_ERR_SCH_VALIDATION_BUILD: createError(
'FST_ERR_SCH_VALIDATION_BUILD',
'Failed building the validation schema for %s: %s, due to error %s'
),
FST_ERR_SCH_SERIALIZATION_BUILD: createError(
'FST_ERR_SCH_SERIALIZATION_BUILD',
'Failed building the serialization schema for %s: %s, due to error %s'
),
FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX: createError(
'FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX',
'response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }'
),
/**
* http2
*/
FST_ERR_HTTP2_INVALID_VERSION: createError(
'FST_ERR_HTTP2_INVALID_VERSION',
'HTTP2 is available only from node >= 8.8.1'
),
/**
* initialConfig
*/
FST_ERR_INIT_OPTS_INVALID: createError(
'FST_ERR_INIT_OPTS_INVALID',
"Invalid initialization options: '%s'"
),
FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE: createError(
'FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE',
"Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method"
),
/**
* router
*/
FST_ERR_DUPLICATED_ROUTE: createError(
'FST_ERR_DUPLICATED_ROUTE',
"Method '%s' already declared for route '%s'"
),
FST_ERR_BAD_URL: createError(
'FST_ERR_BAD_URL',
"'%s' is not a valid url component",
400,
URIError
),
FST_ERR_ASYNC_CONSTRAINT: createError(
'FST_ERR_ASYNC_CONSTRAINT',
'Unexpected error from async constraint',
500
),
FST_ERR_DEFAULT_ROUTE_INVALID_TYPE: createError(
'FST_ERR_DEFAULT_ROUTE_INVALID_TYPE',
'The defaultRoute type should be a function',
500,
TypeError
),
FST_ERR_INVALID_URL: createError(
'FST_ERR_INVALID_URL',
"URL must be a string. Received '%s'",
400,
TypeError
),
FST_ERR_ROUTE_OPTIONS_NOT_OBJ: createError(
'FST_ERR_ROUTE_OPTIONS_NOT_OBJ',
'Options for "%s:%s" route must be an object',
500,
TypeError
),
FST_ERR_ROUTE_DUPLICATED_HANDLER: createError(
'FST_ERR_ROUTE_DUPLICATED_HANDLER',
'Duplicate handler for "%s:%s" route is not allowed!',
500
),
FST_ERR_ROUTE_HANDLER_NOT_FN: createError(
'FST_ERR_ROUTE_HANDLER_NOT_FN',
'Error Handler for %s:%s route, if defined, must be a function',
500,
TypeError
),
FST_ERR_ROUTE_MISSING_HANDLER: createError(
'FST_ERR_ROUTE_MISSING_HANDLER',
'Missing handler function for "%s:%s" route.',
500
),
FST_ERR_ROUTE_METHOD_INVALID: createError(
'FST_ERR_ROUTE_METHOD_INVALID',
'Provided method is invalid!',
500,
TypeError
),
FST_ERR_ROUTE_METHOD_NOT_SUPPORTED: createError(
'FST_ERR_ROUTE_METHOD_NOT_SUPPORTED',
'%s method is not supported.',
500
),
FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED: createError(
'FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED',
'Body validation schema for %s:%s route is not supported!',
500
),
FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT: createError(
'FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT',
"'bodyLimit' option must be an integer > 0. Got '%s'",
500,
TypeError
),
FST_ERR_ROUTE_REWRITE_NOT_STR: createError(
'FST_ERR_ROUTE_REWRITE_NOT_STR',
'Rewrite url for "%s" needs to be of type "string" but received "%s"',
500,
TypeError
),
/**
* again listen when close server
*/
FST_ERR_REOPENED_CLOSE_SERVER: createError(
'FST_ERR_REOPENED_CLOSE_SERVER',
'Fastify has already been closed and cannot be reopened'
),
FST_ERR_REOPENED_SERVER: createError(
'FST_ERR_REOPENED_SERVER',
'Fastify is already listening'
),
FST_ERR_INSTANCE_ALREADY_LISTENING: createError(
'FST_ERR_INSTANCE_ALREADY_LISTENING',
'Fastify instance is already listening. %s'
),
/**
* plugin
*/
FST_ERR_PLUGIN_VERSION_MISMATCH: createError(
'FST_ERR_PLUGIN_VERSION_MISMATCH',
"fastify-plugin: %s - expected '%s' fastify version, '%s' is installed"
),
FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE: createError(
'FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE',
"The decorator '%s'%s is not present in %s"
),
/**
* Avvio Errors
*/
FST_ERR_PLUGIN_CALLBACK_NOT_FN: createError(
'FST_ERR_PLUGIN_CALLBACK_NOT_FN',
'fastify-plugin: %s',
500,
TypeError
),
FST_ERR_PLUGIN_NOT_VALID: createError(
'FST_ERR_PLUGIN_NOT_VALID',
'fastify-plugin: %s'
),
FST_ERR_ROOT_PLG_BOOTED: createError(
'FST_ERR_ROOT_PLG_BOOTED',
'fastify-plugin: %s'
),
FST_ERR_PARENT_PLUGIN_BOOTED: createError(
'FST_ERR_PARENT_PLUGIN_BOOTED',
'fastify-plugin: %s'
),
FST_ERR_PLUGIN_TIMEOUT: createError(
'FST_ERR_PLUGIN_TIMEOUT',
'fastify-plugin: %s'
)
}
function appendStackTrace (oldErr, newErr) {
newErr.cause = oldErr
return newErr
}
module.exports = codes
module.exports.appendStackTrace = appendStackTrace
module.exports.AVVIO_ERRORS_MAP = {
AVV_ERR_CALLBACK_NOT_FN: codes.FST_ERR_PLUGIN_CALLBACK_NOT_FN,
AVV_ERR_PLUGIN_NOT_VALID: codes.FST_ERR_PLUGIN_NOT_VALID,
AVV_ERR_ROOT_PLG_BOOTED: codes.FST_ERR_ROOT_PLG_BOOTED,
AVV_ERR_PARENT_PLG_LOADED: codes.FST_ERR_PARENT_PLUGIN_BOOTED,
AVV_ERR_READY_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT,
AVV_ERR_PLUGIN_EXEC_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT
}
/***/ }),
/***/ 48660:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const FindMyWay = __nccwpck_require__(72026)
const Reply = __nccwpck_require__(55479)
const Request = __nccwpck_require__(11696)
const Context = __nccwpck_require__(76676)
const {
kRoutePrefix,
kCanSetNotFoundHandler,
kFourOhFourLevelInstance,
kFourOhFourContext,
kHooks,
kErrorHandler
} = __nccwpck_require__(28622)
const { lifecycleHooks } = __nccwpck_require__(26133)
const { buildErrorHandler } = __nccwpck_require__(58755)
const {
FST_ERR_NOT_FOUND
} = __nccwpck_require__(89005)
const { createChildLogger } = __nccwpck_require__(8102)
const { getGenReqId } = __nccwpck_require__(74729)
/**
* Each fastify instance have a:
* kFourOhFourLevelInstance: point to a fastify instance that has the 404 handler set
* kCanSetNotFoundHandler: bool to track if the 404 handler has already been set
* kFourOhFour: the singleton instance of this 404 module
* kFourOhFourContext: the context in the reply object where the handler will be executed
*/
function fourOhFour (options) {
const { logger, disableRequestLogging } = options
// 404 router, used for handling encapsulated 404 handlers
const router = FindMyWay({ onBadUrl: createOnBadUrl(), defaultRoute: fourOhFourFallBack })
let _onBadUrlHandler = null
return { router, setNotFoundHandler, setContext, arrange404 }
function arrange404 (instance) {
// Change the pointer of the fastify instance to itself, so register + prefix can add new 404 handler
instance[kFourOhFourLevelInstance] = instance
instance[kCanSetNotFoundHandler] = true
// we need to bind instance for the context
router.onBadUrl = router.onBadUrl.bind(instance)
router.defaultRoute = router.defaultRoute.bind(instance)
}
function basic404 (request, reply) {
const { url, method } = request.raw
const message = `Route ${method}:${url} not found`
if (!disableRequestLogging) {
request.log.info(message)
}
reply.code(404).send({
message,
error: 'Not Found',
statusCode: 404
})
}
function createOnBadUrl () {
return function onBadUrl (path, req, res) {
const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]
const id = getGenReqId(fourOhFourContext.server, req)
const childLogger = createChildLogger(fourOhFourContext, logger, req, id)
const request = new Request(id, null, req, null, childLogger, fourOhFourContext)
const reply = new Reply(res, request, childLogger)
_onBadUrlHandler(request, reply)
}
}
function setContext (instance, context) {
const _404Context = Object.assign({}, instance[kFourOhFourContext])
_404Context.onSend = context.onSend
context[kFourOhFourContext] = _404Context
}
function setNotFoundHandler (opts, handler, avvio, routeHandler) {
// First initialization of the fastify root instance
if (this[kCanSetNotFoundHandler] === undefined) {
this[kCanSetNotFoundHandler] = true
}
if (this[kFourOhFourContext] === undefined) {
this[kFourOhFourContext] = null
}
const _fastify = this
const prefix = this[kRoutePrefix] || '/'
if (this[kCanSetNotFoundHandler] === false) {
throw new Error(`Not found handler already set for Fastify instance with prefix: '${prefix}'`)
}
if (typeof opts === 'object') {
if (opts.preHandler) {
if (Array.isArray(opts.preHandler)) {
opts.preHandler = opts.preHandler.map(hook => hook.bind(_fastify))
} else {
opts.preHandler = opts.preHandler.bind(_fastify)
}
}
if (opts.preValidation) {
if (Array.isArray(opts.preValidation)) {
opts.preValidation = opts.preValidation.map(hook => hook.bind(_fastify))
} else {
opts.preValidation = opts.preValidation.bind(_fastify)
}
}
}
if (typeof opts === 'function') {
handler = opts
opts = undefined
}
opts = opts || {}
if (handler) {
this[kFourOhFourLevelInstance][kCanSetNotFoundHandler] = false
handler = handler.bind(this)
// update onBadUrl handler
_onBadUrlHandler = handler
} else {
handler = basic404
// update onBadUrl handler
_onBadUrlHandler = basic404
}
this.after((notHandledErr, done) => {
_setNotFoundHandler.call(this, prefix, opts, handler, avvio, routeHandler)
done(notHandledErr)
})
}
function _setNotFoundHandler (prefix, opts, handler, avvio, routeHandler) {
const context = new Context({
schema: opts.schema,
handler,
config: opts.config || {},
server: this
})
avvio.once('preReady', () => {
const context = this[kFourOhFourContext]
for (const hook of lifecycleHooks) {
const toSet = this[kHooks][hook]
.concat(opts[hook] || [])
.map(h => h.bind(this))
context[hook] = toSet.length ? toSet : null
}
context.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]
})
if (this[kFourOhFourContext] !== null && prefix === '/') {
Object.assign(this[kFourOhFourContext], context) // Replace the default 404 handler
return
}
this[kFourOhFourLevelInstance][kFourOhFourContext] = context
router.all(prefix + (prefix.endsWith('/') ? '*' : '/*'), routeHandler, context)
router.all(prefix, routeHandler, context)
}
function fourOhFourFallBack (req, res) {
// if this happen, we have a very bad bug
// we might want to do some hard debugging
// here, let's print out as much info as
// we can
const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]
const id = getGenReqId(fourOhFourContext.server, req)
const childLogger = createChildLogger(fourOhFourContext, logger, req, id)
childLogger.info({ req }, 'incoming request')
const request = new Request(id, null, req, null, childLogger, fourOhFourContext)
const reply = new Reply(res, request, childLogger)
request.log.warn('the default handler for 404 did not catch this, this is likely a fastify bug, please report it')
request.log.warn(router.prettyPrint())
reply.code(404).send(new FST_ERR_NOT_FOUND())
}
}
module.exports = fourOhFour
/***/ }),
/***/ 8322:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { validate: validateSchema } = __nccwpck_require__(78365)
const { preValidationHookRunner, preHandlerHookRunner } = __nccwpck_require__(26133)
const wrapThenable = __nccwpck_require__(20195)
const {
kReplyIsError,
kRouteContext
} = __nccwpck_require__(28622)
function handleRequest (err, request, reply) {
if (reply.sent === true) return
if (err != null) {
reply[kReplyIsError] = true
reply.send(err)
return
}
const method = request.raw.method
const headers = request.headers
const context = request[kRouteContext]
if (method === 'GET' || method === 'HEAD') {
handler(request, reply)
return
}
const contentType = headers['content-type']
if (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'TRACE' || method === 'SEARCH' ||
method === 'PROPFIND' || method === 'PROPPATCH' || method === 'LOCK' || method === 'REPORT' || method === 'MKCALENDAR') {
if (contentType === undefined) {
if (
headers['transfer-encoding'] === undefined &&
(headers['content-length'] === '0' || headers['content-length'] === undefined)
) { // Request has no body to parse
handler(request, reply)
} else {
context.contentTypeParser.run('', handler, request, reply)
}
} else {
context.contentTypeParser.run(contentType, handler, request, reply)
}
return
}
if (method === 'OPTIONS' || method === 'DELETE') {
if (
contentType !== undefined &&
(
headers['transfer-encoding'] !== undefined ||
headers['content-length'] !== undefined
)
) {
context.contentTypeParser.run(contentType, handler, request, reply)
} else {
handler(request, reply)
}
return
}
// Return 404 instead of 405 see https://github.com/fastify/fastify/pull/862 for discussion
handler(request, reply)
}
function handler (request, reply) {
try {
if (request[kRouteContext].preValidation !== null) {
preValidationHookRunner(
request[kRouteContext].preValidation,
request,
reply,
preValidationCallback
)
} else {
preValidationCallback(null, request, reply)
}
} catch (err) {
preValidationCallback(err, request, reply)
}
}
function preValidationCallback (err, request, reply) {
if (reply.sent === true) return
if (err != null) {
reply[kReplyIsError] = true
reply.send(err)
return
}
const validationErr = validateSchema(reply[kRouteContext], request)
const isAsync = (validationErr && typeof validationErr.then === 'function') || false
if (isAsync) {
const cb = validationCompleted.bind(null, request, reply)
validationErr.then(cb, cb)
} else {
validationCompleted(request, reply, validationErr)
}
}
function validationCompleted (request, reply, validationErr) {
if (validationErr) {
if (reply[kRouteContext].attachValidation === false) {
reply.send(validationErr)
return
}
reply.request.validationError = validationErr
}
// preHandler hook
if (request[kRouteContext].preHandler !== null) {
preHandlerHookRunner(
request[kRouteContext].preHandler,
request,
reply,
preHandlerCallback
)
} else {
preHandlerCallback(null, request, reply)
}
}
function preHandlerCallback (err, request, reply) {
if (reply.sent) return
if (err != null) {
reply[kReplyIsError] = true
reply.send(err)
return
}
let result
try {
result = request[kRouteContext].handler(request, reply)
} catch (err) {
reply[kReplyIsError] = true
reply.send(err)
return
}
if (result !== undefined) {
if (result !== null && typeof result.then === 'function') {
wrapThenable(result, reply)
} else {
reply.send(result)
}
}
}
module.exports = handleRequest
module.exports[Symbol.for('internals')] = { handler, preHandlerCallback }
/***/ }),
/***/ 25379:
/***/ ((module) => {
"use strict";
function headRouteOnSendHandler (req, reply, payload, done) {
// If payload is undefined
if (payload === undefined) {
reply.header('content-length', '0')
return done(null, null)
}
if (typeof payload.resume === 'function') {
payload.on('error', (err) => {
reply.log.error({ err }, 'Error on Stream found for HEAD route')
})
payload.resume()
return done(null, null)
}
const size = '' + Buffer.byteLength(payload)
reply.header('content-length', size)
done(null, null)
}
function parseHeadOnSendHandlers (onSendHandlers) {
if (onSendHandlers == null) return headRouteOnSendHandler
return Array.isArray(onSendHandlers) ? [...onSendHandlers, headRouteOnSendHandler] : [onSendHandlers, headRouteOnSendHandler]
}
module.exports = {
parseHeadOnSendHandlers
}
/***/ }),
/***/ 26133:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const applicationHooks = [
'onRoute',
'onRegister',
'onReady',
'onListen',
'preClose',
'onClose'
]
const lifecycleHooks = [
'onTimeout',
'onRequest',
'preParsing',
'preValidation',
'preSerialization',
'preHandler',
'onSend',
'onResponse',
'onError',
'onRequestAbort'
]
const supportedHooks = lifecycleHooks.concat(applicationHooks)
const {
FST_ERR_HOOK_INVALID_TYPE,
FST_ERR_HOOK_INVALID_HANDLER,
FST_ERR_SEND_UNDEFINED_ERR,
FST_ERR_HOOK_TIMEOUT,
FST_ERR_HOOK_NOT_SUPPORTED,
AVVIO_ERRORS_MAP,
appendStackTrace
} = __nccwpck_require__(89005)
const {
kChildren,
kHooks,
kRequestPayloadStream
} = __nccwpck_require__(28622)
function Hooks () {
this.onRequest = []
this.preParsing = []
this.preValidation = []
this.preSerialization = []
this.preHandler = []
this.onResponse = []
this.onSend = []
this.onError = []
this.onRoute = []
this.onRegister = []
this.onReady = []
this.onListen = []
this.onTimeout = []
this.onRequestAbort = []
this.preClose = []
}
Hooks.prototype = Object.create(null)
Hooks.prototype.validate = function (hook, fn) {
if (typeof hook !== 'string') throw new FST_ERR_HOOK_INVALID_TYPE()
if (Array.isArray(this[hook]) === false) {
throw new FST_ERR_HOOK_NOT_SUPPORTED(hook)
}
if (typeof fn !== 'function') throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(fn))
}
Hooks.prototype.add = function (hook, fn) {
this.validate(hook, fn)
this[hook].push(fn)
}
function buildHooks (h) {
const hooks = new Hooks()
hooks.onRequest = h.onRequest.slice()
hooks.preParsing = h.preParsing.slice()
hooks.preValidation = h.preValidation.slice()
hooks.preSerialization = h.preSerialization.slice()
hooks.preHandler = h.preHandler.slice()
hooks.onSend = h.onSend.slice()
hooks.onResponse = h.onResponse.slice()
hooks.onError = h.onError.slice()
hooks.onRoute = h.onRoute.slice()
hooks.onRegister = h.onRegister.slice()
hooks.onTimeout = h.onTimeout.slice()
hooks.onRequestAbort = h.onRequestAbort.slice()
hooks.onReady = []
hooks.onListen = []
hooks.preClose = []
return hooks
}
function hookRunnerApplication (hookName, boot, server, cb) {
const hooks = server[kHooks][hookName]
let i = 0
let c = 0
next()
function exit (err) {
if (err) {
if (err.code === 'AVV_ERR_READY_TIMEOUT') {
err = appendStackTrace(err, new FST_ERR_HOOK_TIMEOUT(hookName))
} else {
err = AVVIO_ERRORS_MAP[err.code] != null
? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message))
: err
}
cb(err)
return
}
cb()
}
function next (err) {
if (err) {
exit(err)
return
}
if (i === hooks.length && c === server[kChildren].length) {
if (i === 0 && c === 0) { // speed up start
exit()
} else {
// This is the last function executed for every fastify instance
boot(function manageTimeout (err, done) {
// this callback is needed by fastify to provide an hook interface without the error
// as first parameter and managing it on behalf the user
exit(err)
// this callback is needed by avvio to continue the loading of the next `register` plugins
done(err)
})
}
return
}
if (i === hooks.length && c < server[kChildren].length) {
const child = server[kChildren][c++]
hookRunnerApplication(hookName, boot, child, next)
return
}
boot(wrap(hooks[i++], server))
next()
}
function wrap (fn, server) {
return function (err, done) {
if (err) {
done(err)
return
}
if (fn.length === 1) {
try {
fn.call(server, done)
} catch (error) {
done(error)
}
return
}
try {
const ret = fn.call(server)
if (ret && typeof ret.then === 'function') {
ret.then(done, done)
return
}
} catch (error) {
err = error
}
done(err) // auto done
}
}
}
function onListenHookRunner (server) {
const hooks = server[kHooks].onListen
const hooksLen = hooks.length
let i = 0
let c = 0
next()
function next (err) {
err && server.log.error(err)
if (
i === hooksLen
) {
while (c < server[kChildren].length) {
const child = server[kChildren][c++]
onListenHookRunner(child)
}
return
}
wrap(hooks[i++], server, next)
}
async function wrap (fn, server, done) {
if (fn.length === 1) {
try {
fn.call(server, done)
} catch (e) {
done(e)
}
return
}
try {
const ret = fn.call(server)
if (ret && typeof ret.then === 'function') {
ret.then(done, done)
return
}
done()
} catch (error) {
done(error)
}
}
}
function hookRunnerGenerator (iterator) {
return function hookRunner (functions, request, reply, cb) {
let i = 0
function next (err) {
if (err || i === functions.length) {
cb(err, request, reply)
return
}
let result
try {
result = iterator(functions[i++], request, reply, next)
} catch (error) {
cb(error, request, reply)
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, handleReject)
}
}
function handleResolve () {
next()
}
function handleReject (err) {
if (!err) {
err = new FST_ERR_SEND_UNDEFINED_ERR()
}
cb(err, request, reply)
}
next()
}
}
function onResponseHookIterator (fn, request, reply, next) {
return fn(request, reply, next)
}
const onResponseHookRunner = hookRunnerGenerator(onResponseHookIterator)
const preValidationHookRunner = hookRunnerGenerator(hookIterator)
const preHandlerHookRunner = hookRunnerGenerator(hookIterator)
const onTimeoutHookRunner = hookRunnerGenerator(hookIterator)
const onRequestHookRunner = hookRunnerGenerator(hookIterator)
function onSendHookRunner (functions, request, reply, payload, cb) {
let i = 0
function next (err, newPayload) {
if (err) {
cb(err, request, reply, payload)
return
}
if (newPayload !== undefined) {
payload = newPayload
}
if (i === functions.length) {
cb(null, request, reply, payload)
return
}
let result
try {
result = functions[i++](request, reply, payload, next)
} catch (error) {
cb(error, request, reply)
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, handleReject)
}
}
function handleResolve (newPayload) {
next(null, newPayload)
}
function handleReject (err) {
if (!err) {
err = new FST_ERR_SEND_UNDEFINED_ERR()
}
cb(err, request, reply, payload)
}
next()
}
const preSerializationHookRunner = onSendHookRunner
function preParsingHookRunner (functions, request, reply, cb) {
let i = 0
function next (err, newPayload) {
if (reply.sent) {
return
}
if (newPayload !== undefined) {
request[kRequestPayloadStream] = newPayload
}
if (err || i === functions.length) {
cb(err, request, reply)
return
}
let result
try {
result = functions[i++](request, reply, request[kRequestPayloadStream], next)
} catch (error) {
cb(error, request, reply)
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, handleReject)
}
}
function handleResolve (newPayload) {
next(null, newPayload)
}
function handleReject (err) {
if (!err) {
err = new FST_ERR_SEND_UNDEFINED_ERR()
}
cb(err, request, reply)
}
next()
}
function onRequestAbortHookRunner (functions, request, cb) {
let i = 0
function next (err) {
if (err || i === functions.length) {
cb(err, request)
return
}
let result
try {
result = functions[i++](request, next)
} catch (error) {
cb(error, request)
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, handleReject)
}
}
function handleResolve () {
next()
}
function handleReject (err) {
if (!err) {
err = new FST_ERR_SEND_UNDEFINED_ERR()
}
cb(err, request)
}
next()
}
function hookIterator (fn, request, reply, next) {
if (reply.sent === true) return undefined
return fn(request, reply, next)
}
module.exports = {
Hooks,
buildHooks,
hookRunnerGenerator,
preParsingHookRunner,
onResponseHookRunner,
onSendHookRunner,
preSerializationHookRunner,
onRequestAbortHookRunner,
hookIterator,
hookRunnerApplication,
onListenHookRunner,
preHandlerHookRunner,
preValidationHookRunner,
onRequestHookRunner,
onTimeoutHookRunner,
lifecycleHooks,
supportedHooks
}
/***/ }),
/***/ 8340:
/***/ ((module) => {
"use strict";
module.exports = {
supportedMethods: [
'DELETE',
'GET',
'HEAD',
'PATCH',
'POST',
'PUT',
'OPTIONS',
'PROPFIND',
'PROPPATCH',
'MKCOL',
'COPY',
'MOVE',
'LOCK',
'UNLOCK',
'TRACE',
'SEARCH',
'REPORT',
'MKCALENDAR'
]
}
/***/ }),
/***/ 39643:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const validate = __nccwpck_require__(51612)
const deepClone = __nccwpck_require__(11868)({ circles: true, proto: false })
const { FST_ERR_INIT_OPTS_INVALID } = __nccwpck_require__(89005)
function validateInitialConfig (options) {
const opts = deepClone(options)
if (!validate(opts)) {
const error = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map(e => e.message)))
error.errors = validate.errors
throw error
}
return deepFreezeObject(opts)
}
function deepFreezeObject (object) {
const properties = Object.getOwnPropertyNames(object)
for (const name of properties) {
const value = object[name]
if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
continue
}
object[name] = value && typeof value === 'object' ? deepFreezeObject(value) : value
}
return Object.freeze(object)
}
module.exports = validateInitialConfig
module.exports.defaultInitOptions = validate.defaultInitOptions
module.exports.utils = { deepFreezeObject }
/***/ }),
/***/ 8102:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/**
* Code imported from `pino-http`
* Repo: https://github.com/pinojs/pino-http
* License: MIT (https://raw.githubusercontent.com/pinojs/pino-http/master/LICENSE)
*/
const nullLogger = __nccwpck_require__(32861)
const pino = __nccwpck_require__(78085)
const { serializersSym } = pino.symbols
const {
FST_ERR_LOG_INVALID_DESTINATION,
FST_ERR_LOG_INVALID_LOGGER
} = __nccwpck_require__(89005)
function createPinoLogger (opts) {
if (opts.stream && opts.file) {
throw new FST_ERR_LOG_INVALID_DESTINATION()
} else if (opts.file) {
// we do not have stream
opts.stream = pino.destination(opts.file)
delete opts.file
}
const prevLogger = opts.logger
const prevGenReqId = opts.genReqId
let logger = null
if (prevLogger) {
opts.logger = undefined
opts.genReqId = undefined
// we need to tap into pino internals because in v5 it supports
// adding serializers in child loggers
if (prevLogger[serializersSym]) {
opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym])
}
logger = prevLogger.child({}, opts)
opts.logger = prevLogger
opts.genReqId = prevGenReqId
} else {
logger = pino(opts, opts.stream)
}
return logger
}
const serializers = {
req: function asReqValue (req) {
return {
method: req.method,
url: req.url,
version: req.headers && req.headers['accept-version'],
hostname: req.hostname,
remoteAddress: req.ip,
remotePort: req.socket ? req.socket.remotePort : undefined
}
},
err: pino.stdSerializers.err,
res: function asResValue (reply) {
return {
statusCode: reply.statusCode
}
}
}
function now () {
const ts = process.hrtime()
return (ts[0] * 1e3) + (ts[1] / 1e6)
}
function createLogger (options) {
if (!options.logger) {
const logger = nullLogger
logger.child = () => logger
return { logger, hasLogger: false }
}
if (validateLogger(options.logger)) {
const logger = createPinoLogger({
logger: options.logger,
serializers: Object.assign({}, serializers, options.logger.serializers)
})
return { logger, hasLogger: true }
}
const localLoggerOptions = {}
if (Object.prototype.toString.call(options.logger) === '[object Object]') {
Reflect.ownKeys(options.logger).forEach(prop => {
Object.defineProperty(localLoggerOptions, prop, {
value: options.logger[prop],
writable: true,
enumerable: true,
configurable: true
})
})
}
localLoggerOptions.level = localLoggerOptions.level || 'info'
localLoggerOptions.serializers = Object.assign({}, serializers, localLoggerOptions.serializers)
options.logger = localLoggerOptions
const logger = createPinoLogger(options.logger)
return { logger, hasLogger: true }
}
/**
* Determines if a provided logger object meets the requirements
* of a Fastify compatible logger.
*
* @param {object} logger Object to validate.
* @param {boolean?} strict `true` if the object must be a logger (always throw if any methods missing)
*
* @returns {boolean} `true` when the logger meets the requirements.
*
* @throws {FST_ERR_LOG_INVALID_LOGGER} When the logger object is
* missing required methods.
*/
function validateLogger (logger, strict) {
const methods = ['info', 'error', 'debug', 'fatal', 'warn', 'trace', 'child']
const missingMethods = logger
? methods.filter(method => !logger[method] || typeof logger[method] !== 'function')
: methods
if (!missingMethods.length) {
return true
} else if ((missingMethods.length === methods.length) && !strict) {
return false
} else {
throw FST_ERR_LOG_INVALID_LOGGER(missingMethods.join(','))
}
}
/**
* Utility for creating a child logger with the appropriate bindings, logger factory
* and validation.
* @param {object} context
* @param {import('../fastify').FastifyBaseLogger} logger
* @param {import('../fastify').RawRequestDefaultExpression<any>} req
* @param {string} reqId
* @param {import('../types/logger.js').ChildLoggerOptions?} loggerOpts
*/
function createChildLogger (context, logger, req, reqId, loggerOpts) {
const loggerBindings = {
[context.requestIdLogLabel]: reqId
}
const child = context.childLoggerFactory.call(context.server, logger, loggerBindings, loggerOpts || {}, req)
// Optimization: bypass validation if the factory is our own default factory
if (context.childLoggerFactory !== defaultChildLoggerFactory) {
validateLogger(child, true) // throw if the child is not a valid logger
}
return child
}
/**
* @param {import('../fastify.js').FastifyBaseLogger} logger
* @param {import('../types/logger.js').Bindings} bindings
* @param {import('../types/logger.js').ChildLoggerOptions} opts
*/
function defaultChildLoggerFactory (logger, bindings, opts) {
return logger.child(bindings, opts)
}
module.exports = {
createLogger,
createChildLogger,
defaultChildLoggerFactory,
serializers,
now
}
/***/ }),
/***/ 4679:
/***/ ((module) => {
"use strict";
module.exports = function noopSet () {
return {
[Symbol.iterator]: function * () {},
add () {},
delete () {},
has () { return true }
}
}
/***/ }),
/***/ 28243:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kAvvioBoot,
kChildren,
kRoutePrefix,
kLogLevel,
kLogSerializers,
kHooks,
kSchemaController,
kContentTypeParser,
kReply,
kRequest,
kFourOhFour,
kPluginNameChain
} = __nccwpck_require__(28622)
const Reply = __nccwpck_require__(55479)
const Request = __nccwpck_require__(11696)
const SchemaController = __nccwpck_require__(92310)
const ContentTypeParser = __nccwpck_require__(76696)
const { buildHooks } = __nccwpck_require__(26133)
const pluginUtils = __nccwpck_require__(41057)
// Function that runs the encapsulation magic.
// Everything that need to be encapsulated must be handled in this function.
module.exports = function override (old, fn, opts) {
const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn)
const fnName = pluginUtils.getPluginName(fn) || pluginUtils.getFuncPreview(fn)
if (shouldSkipOverride) {
// after every plugin registration we will enter a new name
old[kPluginNameChain].push(fnName)
return old
}
const instance = Object.create(old)
old[kChildren].push(instance)
instance.ready = old[kAvvioBoot].bind(instance)
instance[kChildren] = []
instance[kReply] = Reply.buildReply(instance[kReply])
instance[kRequest] = Request.buildRequest(instance[kRequest])
instance[kContentTypeParser] = ContentTypeParser.helpers.buildContentTypeParser(instance[kContentTypeParser])
instance[kHooks] = buildHooks(instance[kHooks])
instance[kRoutePrefix] = buildRoutePrefix(instance[kRoutePrefix], opts.prefix)
instance[kLogLevel] = opts.logLevel || instance[kLogLevel]
instance[kSchemaController] = SchemaController.buildSchemaController(old[kSchemaController])
instance.getSchema = instance[kSchemaController].getSchema.bind(instance[kSchemaController])
instance.getSchemas = instance[kSchemaController].getSchemas.bind(instance[kSchemaController])
// Track the registered and loaded plugins since the root instance.
// It does not track the current encapsulated plugin.
instance[pluginUtils.kRegisteredPlugins] = Object.create(instance[pluginUtils.kRegisteredPlugins])
// Track the plugin chain since the root instance.
// When an non-encapsulated plugin is added, the chain will be updated.
instance[kPluginNameChain] = [fnName]
if (instance[kLogSerializers] || opts.logSerializers) {
instance[kLogSerializers] = Object.assign(Object.create(instance[kLogSerializers]), opts.logSerializers)
}
if (opts.prefix) {
instance[kFourOhFour].arrange404(instance)
}
for (const hook of instance[kHooks].onRegister) hook.call(this, instance, opts)
return instance
}
function buildRoutePrefix (instancePrefix, pluginPrefix) {
if (!pluginPrefix) {
return instancePrefix
}
// Ensure that there is a '/' between the prefixes
if (instancePrefix.endsWith('/') && pluginPrefix[0] === '/') {
// Remove the extra '/' to avoid: '/first//second'
pluginPrefix = pluginPrefix.slice(1)
} else if (pluginPrefix[0] !== '/') {
pluginPrefix = '/' + pluginPrefix
}
return instancePrefix + pluginPrefix
}
/***/ }),
/***/ 41057:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const semver = __nccwpck_require__(11383)
const assert = __nccwpck_require__(98061)
const kRegisteredPlugins = Symbol.for('registered-plugin')
const {
kTestInternals
} = __nccwpck_require__(28622)
const { exist, existReply, existRequest } = __nccwpck_require__(7629)
const {
FST_ERR_PLUGIN_VERSION_MISMATCH,
FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE
} = __nccwpck_require__(89005)
const { FSTWRN002 } = __nccwpck_require__(59283)
function getMeta (fn) {
return fn[Symbol.for('plugin-meta')]
}
function getPluginName (func) {
const display = getDisplayName(func)
if (display) {
return display
}
// let's see if this is a file, and in that case use that
// this is common for plugins
const cache = require.cache
// cache is undefined inside SEA
if (cache) {
const keys = Object.keys(cache)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (cache[key].exports === func) {
return key
}
}
}
// if not maybe it's a named function, so use that
if (func.name) {
return func.name
}
return null
}
function getFuncPreview (func) {
// takes the first two lines of the function if nothing else works
return func.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ')
}
function getDisplayName (fn) {
return fn[Symbol.for('fastify.display-name')]
}
function shouldSkipOverride (fn) {
return !!fn[Symbol.for('skip-override')]
}
function checkDependencies (fn) {
const meta = getMeta(fn)
if (!meta) return
const dependencies = meta.dependencies
if (!dependencies) return
assert(Array.isArray(dependencies), 'The dependencies should be an array of strings')
dependencies.forEach(dependency => {
assert(
this[kRegisteredPlugins].indexOf(dependency) > -1,
`The dependency '${dependency}' of plugin '${meta.name}' is not registered`
)
})
}
function checkDecorators (fn) {
const meta = getMeta(fn)
if (!meta) return
const { decorators, name } = meta
if (!decorators) return
if (decorators.fastify) _checkDecorators(this, 'Fastify', decorators.fastify, name)
if (decorators.reply) _checkDecorators(this, 'Reply', decorators.reply, name)
if (decorators.request) _checkDecorators(this, 'Request', decorators.request, name)
}
const checks = {
Fastify: exist,
Request: existRequest,
Reply: existReply
}
function _checkDecorators (that, instance, decorators, name) {
assert(Array.isArray(decorators), 'The decorators should be an array of strings')
decorators.forEach(decorator => {
const withPluginName = typeof name === 'string' ? ` required by '${name}'` : ''
if (!checks[instance].call(that, decorator)) {
throw new FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE(decorator, withPluginName, instance)
}
})
}
function checkVersion (fn) {
const meta = getMeta(fn)
if (!meta) return
const requiredVersion = meta.fastify
const fastifyRc = /-rc.+$/.test(this.version)
if (fastifyRc === true && semver.gt(this.version, semver.coerce(requiredVersion)) === true) {
// A Fastify release candidate phase is taking place. In order to reduce
// the effort needed to test plugins with the RC, we allow plugins targeting
// the prior Fastify release to be loaded.
return
}
if (requiredVersion && semver.satisfies(this.version, requiredVersion, { includePrerelease: fastifyRc }) === false) {
// We are not in a release candidate phase. Thus, we must honor the semver
// ranges defined by the plugin's metadata. Which is to say, if the plugin
// expects an older version of Fastify than the _current_ version, we will
// throw an error.
throw new FST_ERR_PLUGIN_VERSION_MISMATCH(meta.name, requiredVersion, this.version)
}
}
function registerPluginName (fn) {
const meta = getMeta(fn)
if (!meta) return
const name = meta.name
if (!name) return
this[kRegisteredPlugins].push(name)
return name
}
function checkPluginHealthiness (fn, pluginName) {
if (fn.constructor.name === 'AsyncFunction' && fn.length === 3) {
FSTWRN002(pluginName || 'anonymous')
}
}
function registerPlugin (fn) {
const pluginName = registerPluginName.call(this, fn) || getPluginName(fn)
checkPluginHealthiness.call(this, fn, pluginName)
checkVersion.call(this, fn)
checkDecorators.call(this, fn)
checkDependencies.call(this, fn)
return shouldSkipOverride(fn)
}
module.exports = {
getPluginName,
getFuncPreview,
kRegisteredPlugins,
getDisplayName,
registerPlugin
}
module.exports[kTestInternals] = {
shouldSkipOverride,
getMeta,
checkDecorators,
checkDependencies
}
/***/ }),
/***/ 55479:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const eos = (__nccwpck_require__(84492).finished)
const Readable = (__nccwpck_require__(84492).Readable)
const {
kFourOhFourContext,
kPublicRouteContext,
kReplyErrorHandlerCalled,
kReplyHijacked,
kReplyStartTime,
kReplyEndTime,
kReplySerializer,
kReplySerializerDefault,
kReplyIsError,
kReplyHeaders,
kReplyTrailers,
kReplyHasStatusCode,
kReplyIsRunningOnErrorHook,
kReplyNextErrorHandler,
kDisableRequestLogging,
kSchemaResponse,
kReplyCacheSerializeFns,
kSchemaController,
kOptions,
kRouteContext
} = __nccwpck_require__(28622)
const {
onSendHookRunner,
onResponseHookRunner,
preHandlerHookRunner,
preSerializationHookRunner
} = __nccwpck_require__(26133)
const internals = __nccwpck_require__(8322)[Symbol.for('internals')]
const loggerUtils = __nccwpck_require__(8102)
const now = loggerUtils.now
const { handleError } = __nccwpck_require__(58755)
const { getSchemaSerializer } = __nccwpck_require__(48122)
const CONTENT_TYPE = {
JSON: 'application/json; charset=utf-8',
PLAIN: 'text/plain; charset=utf-8',
OCTET: 'application/octet-stream'
}
const {
FST_ERR_REP_INVALID_PAYLOAD_TYPE,
FST_ERR_REP_RESPONSE_BODY_CONSUMED,
FST_ERR_REP_ALREADY_SENT,
FST_ERR_REP_SENT_VALUE,
FST_ERR_SEND_INSIDE_ONERR,
FST_ERR_BAD_STATUS_CODE,
FST_ERR_BAD_TRAILER_NAME,
FST_ERR_BAD_TRAILER_VALUE,
FST_ERR_MISSING_SERIALIZATION_FN,
FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN
} = __nccwpck_require__(89005)
const { FSTDEP010, FSTDEP013, FSTDEP019, FSTDEP020 } = __nccwpck_require__(59283)
const toString = Object.prototype.toString
function Reply (res, request, log) {
this.raw = res
this[kReplySerializer] = null
this[kReplyErrorHandlerCalled] = false
this[kReplyIsError] = false
this[kReplyIsRunningOnErrorHook] = false
this.request = request
this[kReplyHeaders] = {}
this[kReplyTrailers] = null
this[kReplyHasStatusCode] = false
this[kReplyStartTime] = undefined
this.log = log
}
Reply.props = []
Object.defineProperties(Reply.prototype, {
[kRouteContext]: {
get () {
return this.request[kRouteContext]
}
},
// TODO: remove once v5 is done
// Is temporary to avoid constant conflicts between `next` and `main`
context: {
get () {
FSTDEP019()
return this.request[kRouteContext]
}
},
elapsedTime: {
get () {
if (this[kReplyStartTime] === undefined) {
return 0
}
return (this[kReplyEndTime] || now()) - this[kReplyStartTime]
}
},
server: {
get () {
return this.request[kRouteContext].server
}
},
sent: {
enumerable: true,
get () {
// We are checking whether reply was hijacked or the response has ended.
return (this[kReplyHijacked] || this.raw.writableEnded) === true
},
set (value) {
FSTDEP010()
if (value !== true) {
throw new FST_ERR_REP_SENT_VALUE()
}
// We throw only if sent was overwritten from Fastify
if (this.sent && this[kReplyHijacked]) {
throw new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method)
}
this[kReplyHijacked] = true
}
},
statusCode: {
get () {
return this.raw.statusCode
},
set (value) {
this.code(value)
}
},
[kPublicRouteContext]: {
get () {
return this.request[kPublicRouteContext]
}
}
})
Reply.prototype.hijack = function () {
this[kReplyHijacked] = true
return this
}
Reply.prototype.send = function (payload) {
if (this[kReplyIsRunningOnErrorHook] === true) {
throw new FST_ERR_SEND_INSIDE_ONERR()
}
if (this.sent) {
this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method) })
return this
}
if (payload instanceof Error || this[kReplyIsError] === true) {
this[kReplyIsError] = false
onErrorHook(this, payload, onSendHook)
return this
}
if (payload === undefined) {
onSendHook(this, payload)
return this
}
const contentType = this.getHeader('content-type')
const hasContentType = contentType !== undefined
if (payload !== null) {
if (
// node:stream
typeof payload.pipe === 'function' ||
// node:stream/web
typeof payload.getReader === 'function' ||
// Response
toString.call(payload) === '[object Response]'
) {
onSendHook(this, payload)
return this
}
if (payload?.buffer instanceof ArrayBuffer) {
if (hasContentType === false) {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.OCTET
}
const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength)
onSendHook(this, payloadToSend)
return this
}
if (hasContentType === false && typeof payload === 'string') {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.PLAIN
onSendHook(this, payload)
return this
}
}
if (this[kReplySerializer] !== null) {
if (typeof payload !== 'string') {
preSerializationHook(this, payload)
return this
} else {
payload = this[kReplySerializer](payload)
}
// The indexOf below also matches custom json mimetypes such as 'application/hal+json' or 'application/ld+json'
} else if (hasContentType === false || contentType.indexOf('json') > -1) {
if (hasContentType === false) {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.JSON
} else {
// If user doesn't set charset, we will set charset to utf-8
if (contentType.indexOf('charset') === -1) {
const customContentType = contentType.trim()
if (customContentType.endsWith(';')) {
// custom content-type is ended with ';'
this[kReplyHeaders]['content-type'] = `${customContentType} charset=utf-8`
} else {
this[kReplyHeaders]['content-type'] = `${customContentType}; charset=utf-8`
}
}
}
if (typeof payload !== 'string') {
preSerializationHook(this, payload)
return this
}
}
onSendHook(this, payload)
return this
}
Reply.prototype.getHeader = function (key) {
key = key.toLowerCase()
const res = this.raw
let value = this[kReplyHeaders][key]
if (value === undefined && res.hasHeader(key)) {
value = res.getHeader(key)
}
return value
}
Reply.prototype.getHeaders = function () {
return {
...this.raw.getHeaders(),
...this[kReplyHeaders]
}
}
Reply.prototype.hasHeader = function (key) {
key = key.toLowerCase()
return this[kReplyHeaders][key] !== undefined || this.raw.hasHeader(key)
}
Reply.prototype.removeHeader = function (key) {
// Node.js does not like headers with keys set to undefined,
// so we have to delete the key.
delete this[kReplyHeaders][key.toLowerCase()]
return this
}
Reply.prototype.header = function (key, value = '') {
key = key.toLowerCase()
if (this[kReplyHeaders][key] && key === 'set-cookie') {
// https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.2
if (typeof this[kReplyHeaders][key] === 'string') {
this[kReplyHeaders][key] = [this[kReplyHeaders][key]]
}
if (Array.isArray(value)) {
Array.prototype.push.apply(this[kReplyHeaders][key], value)
} else {
this[kReplyHeaders][key].push(value)
}
} else {
this[kReplyHeaders][key] = value
}
return this
}
Reply.prototype.headers = function (headers) {
const keys = Object.keys(headers)
/* eslint-disable no-var */
for (var i = 0; i !== keys.length; ++i) {
const key = keys[i]
this.header(key, headers[key])
}
return this
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer#directives
// https://datatracker.ietf.org/doc/html/rfc7230.html#chunked.trailer.part
const INVALID_TRAILERS = new Set([
'transfer-encoding',
'content-length',
'host',
'cache-control',
'max-forwards',
'te',
'authorization',
'set-cookie',
'content-encoding',
'content-type',
'content-range',
'trailer'
])
Reply.prototype.trailer = function (key, fn) {
key = key.toLowerCase()
if (INVALID_TRAILERS.has(key)) {
throw new FST_ERR_BAD_TRAILER_NAME(key)
}
if (typeof fn !== 'function') {
throw new FST_ERR_BAD_TRAILER_VALUE(key, typeof fn)
}
if (this[kReplyTrailers] === null) this[kReplyTrailers] = {}
this[kReplyTrailers][key] = fn
return this
}
Reply.prototype.hasTrailer = function (key) {
return this[kReplyTrailers]?.[key.toLowerCase()] !== undefined
}
Reply.prototype.removeTrailer = function (key) {
if (this[kReplyTrailers] === null) return this
this[kReplyTrailers][key.toLowerCase()] = undefined
return this
}
Reply.prototype.code = function (code) {
const intValue = Number(code)
if (isNaN(intValue) || intValue < 100 || intValue > 599) {
throw new FST_ERR_BAD_STATUS_CODE(code || String(code))
}
this.raw.statusCode = intValue
this[kReplyHasStatusCode] = true
return this
}
Reply.prototype.status = Reply.prototype.code
Reply.prototype.getSerializationFunction = function (schemaOrStatus, contentType) {
let serialize
if (typeof schemaOrStatus === 'string' || typeof schemaOrStatus === 'number') {
if (typeof contentType === 'string') {
serialize = this[kRouteContext][kSchemaResponse]?.[schemaOrStatus]?.[contentType]
} else {
serialize = this[kRouteContext][kSchemaResponse]?.[schemaOrStatus]
}
} else if (typeof schemaOrStatus === 'object') {
serialize = this[kRouteContext][kReplyCacheSerializeFns]?.get(schemaOrStatus)
}
return serialize
}
Reply.prototype.compileSerializationSchema = function (schema, httpStatus = null, contentType = null) {
const { request } = this
const { method, url } = request
// Check if serialize function already compiled
if (this[kRouteContext][kReplyCacheSerializeFns]?.has(schema)) {
return this[kRouteContext][kReplyCacheSerializeFns].get(schema)
}
const serializerCompiler = this[kRouteContext].serializerCompiler ||
this.server[kSchemaController].serializerCompiler ||
(
// We compile the schemas if no custom serializerCompiler is provided
// nor set
this.server[kSchemaController].setupSerializer(this.server[kOptions]) ||
this.server[kSchemaController].serializerCompiler
)
const serializeFn = serializerCompiler({
schema,
method,
url,
httpStatus,
contentType
})
// We create a WeakMap to compile the schema only once
// Its done lazily to avoid add overhead by creating the WeakMap
// if it is not used
// TODO: Explore a central cache for all the schemas shared across
// encapsulated contexts
if (this[kRouteContext][kReplyCacheSerializeFns] == null) {
this[kRouteContext][kReplyCacheSerializeFns] = new WeakMap()
}
this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn)
return serializeFn
}
Reply.prototype.serializeInput = function (input, schema, httpStatus, contentType) {
const possibleContentType = httpStatus
let serialize
httpStatus = typeof schema === 'string' || typeof schema === 'number'
? schema
: httpStatus
contentType = httpStatus && possibleContentType !== httpStatus
? possibleContentType
: contentType
if (httpStatus != null) {
if (contentType != null) {
serialize = this[kRouteContext][kSchemaResponse]?.[httpStatus]?.[contentType]
} else {
serialize = this[kRouteContext][kSchemaResponse]?.[httpStatus]
}
if (serialize == null) {
if (contentType) throw new FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN(httpStatus, contentType)
throw new FST_ERR_MISSING_SERIALIZATION_FN(httpStatus)
}
} else {
// Check if serialize function already compiled
if (this[kRouteContext][kReplyCacheSerializeFns]?.has(schema)) {
serialize = this[kRouteContext][kReplyCacheSerializeFns].get(schema)
} else {
serialize = this.compileSerializationSchema(schema, httpStatus, contentType)
}
}
return serialize(input)
}
Reply.prototype.serialize = function (payload) {
if (this[kReplySerializer] !== null) {
return this[kReplySerializer](payload)
} else {
if (this[kRouteContext] && this[kRouteContext][kReplySerializerDefault]) {
return this[kRouteContext][kReplySerializerDefault](payload, this.raw.statusCode)
} else {
return serialize(this[kRouteContext], payload, this.raw.statusCode)
}
}
}
Reply.prototype.serializer = function (fn) {
this[kReplySerializer] = fn
return this
}
Reply.prototype.type = function (type) {
this[kReplyHeaders]['content-type'] = type
return this
}
Reply.prototype.redirect = function (code, url) {
if (typeof code === 'string') {
url = code
code = this[kReplyHasStatusCode] ? this.raw.statusCode : 302
}
return this.header('location', url).code(code).send()
}
Reply.prototype.callNotFound = function () {
notFound(this)
return this
}
// TODO: should be removed in fastify@5
Reply.prototype.getResponseTime = function () {
FSTDEP020()
return this.elapsedTime
}
// Make reply a thenable, so it could be used with async/await.
// See
// - https://github.com/fastify/fastify/issues/1864 for the discussions
// - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then for the signature
Reply.prototype.then = function (fulfilled, rejected) {
if (this.sent) {
fulfilled()
return
}
eos(this.raw, (err) => {
// We must not treat ERR_STREAM_PREMATURE_CLOSE as
// an error because it is created by eos, not by the stream.
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
if (rejected) {
rejected(err)
} else {
this.log && this.log.warn('unhandled rejection on reply.then')
}
} else {
fulfilled()
}
})
}
function preSerializationHook (reply, payload) {
if (reply[kRouteContext].preSerialization !== null) {
preSerializationHookRunner(
reply[kRouteContext].preSerialization,
reply.request,
reply,
payload,
preSerializationHookEnd
)
} else {
preSerializationHookEnd(null, reply.request, reply, payload)
}
}
function preSerializationHookEnd (err, request, reply, payload) {
if (err != null) {
onErrorHook(reply, err)
return
}
try {
if (reply[kReplySerializer] !== null) {
payload = reply[kReplySerializer](payload)
} else if (reply[kRouteContext] && reply[kRouteContext][kReplySerializerDefault]) {
payload = reply[kRouteContext][kReplySerializerDefault](payload, reply.raw.statusCode)
} else {
payload = serialize(reply[kRouteContext], payload, reply.raw.statusCode, reply[kReplyHeaders]['content-type'])
}
} catch (e) {
wrapSerializationError(e, reply)
onErrorHook(reply, e)
return
}
onSendHook(reply, payload)
}
function wrapSerializationError (error, reply) {
error.serialization = reply[kRouteContext].config
}
function onSendHook (reply, payload) {
if (reply[kRouteContext].onSend !== null) {
onSendHookRunner(
reply[kRouteContext].onSend,
reply.request,
reply,
payload,
wrapOnSendEnd
)
} else {
onSendEnd(reply, payload)
}
}
function wrapOnSendEnd (err, request, reply, payload) {
if (err != null) {
onErrorHook(reply, err)
} else {
onSendEnd(reply, payload)
}
}
function safeWriteHead (reply, statusCode) {
const res = reply.raw
try {
res.writeHead(statusCode, reply[kReplyHeaders])
} catch (err) {
if (err.code === 'ERR_HTTP_HEADERS_SENT') {
reply.log.warn(`Reply was already sent, did you forget to "return reply" in the "${reply.request.raw.url}" (${reply.request.raw.method}) route?`)
}
throw err
}
}
function onSendEnd (reply, payload) {
const res = reply.raw
const req = reply.request
// we check if we need to update the trailers header and set it
if (reply[kReplyTrailers] !== null) {
const trailerHeaders = Object.keys(reply[kReplyTrailers])
let header = ''
for (const trailerName of trailerHeaders) {
if (typeof reply[kReplyTrailers][trailerName] !== 'function') continue
header += ' '
header += trailerName
}
// it must be chunked for trailer to work
reply.header('Transfer-Encoding', 'chunked')
reply.header('Trailer', header.trim())
}
// since Response contain status code, we need to update before
// any action that used statusCode
const isResponse = toString.call(payload) === '[object Response]'
if (isResponse) {
// https://developer.mozilla.org/en-US/docs/Web/API/Response/status
if (typeof payload.status === 'number') {
reply.code(payload.status)
}
}
const statusCode = res.statusCode
if (payload === undefined || payload === null) {
// according to https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
// we cannot send a content-length for 304 and 204, and all status code
// < 200
// A sender MUST NOT send a Content-Length header field in any message
// that contains a Transfer-Encoding header field.
// For HEAD we don't overwrite the `content-length`
if (statusCode >= 200 && statusCode !== 204 && statusCode !== 304 && req.method !== 'HEAD' && reply[kReplyTrailers] === null) {
reply[kReplyHeaders]['content-length'] = '0'
}
safeWriteHead(reply, statusCode)
sendTrailer(payload, res, reply)
return
}
if ((statusCode >= 100 && statusCode < 200) || statusCode === 204) {
// Responses without a content body must not send content-type
// or content-length headers.
// See https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6.
reply.removeHeader('content-type')
reply.removeHeader('content-length')
safeWriteHead(reply, statusCode)
sendTrailer(undefined, res, reply)
if (typeof payload.resume === 'function') {
payload.on('error', noop)
payload.resume()
}
return
}
// node:stream
if (typeof payload.pipe === 'function') {
sendStream(payload, res, reply)
return
}
// node:stream/web
if (typeof payload.getReader === 'function') {
sendWebStream(payload, res, reply)
return
}
// Response
if (isResponse) {
// https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
if (typeof payload.headers === 'object' && typeof payload.headers.forEach === 'function') {
for (const [headerName, headerValue] of payload.headers) {
reply.header(headerName, headerValue)
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Response/body
if (payload.body != null) {
if (payload.bodyUsed) {
throw new FST_ERR_REP_RESPONSE_BODY_CONSUMED()
}
// Response.body always a ReadableStream
sendWebStream(payload.body, res, reply)
}
return
}
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
throw new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)
}
if (reply[kReplyTrailers] === null) {
const contentLength = reply[kReplyHeaders]['content-length']
if (!contentLength ||
(req.raw.method !== 'HEAD' &&
Number(contentLength) !== Buffer.byteLength(payload)
)
) {
reply[kReplyHeaders]['content-length'] = '' + Buffer.byteLength(payload)
}
}
safeWriteHead(reply, statusCode)
// write payload first
res.write(payload)
// then send trailers
sendTrailer(payload, res, reply)
}
function logStreamError (logger, err, res) {
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
if (!logger[kDisableRequestLogging]) {
logger.info({ res }, 'stream closed prematurely')
}
} else {
logger.warn({ err }, 'response terminated with an error with headers already sent')
}
}
function sendWebStream (payload, res, reply) {
const nodeStream = Readable.fromWeb(payload)
sendStream(nodeStream, res, reply)
}
function sendStream (payload, res, reply) {
let sourceOpen = true
let errorLogged = false
// set trailer when stream ended
sendStreamTrailer(payload, res, reply)
eos(payload, { readable: true, writable: false }, function (err) {
sourceOpen = false
if (err != null) {
if (res.headersSent || reply.request.raw.aborted === true) {
if (!errorLogged) {
errorLogged = true
logStreamError(reply.log, err, res)
}
res.destroy()
} else {
onErrorHook(reply, err)
}
}
// there is nothing to do if there is not an error
})
eos(res, function (err) {
if (sourceOpen) {
if (err != null && res.headersSent && !errorLogged) {
errorLogged = true
logStreamError(reply.log, err, res)
}
if (typeof payload.destroy === 'function') {
payload.destroy()
} else if (typeof payload.close === 'function') {
payload.close(noop)
} else if (typeof payload.abort === 'function') {
payload.abort()
} else {
reply.log.warn('stream payload does not end properly')
}
}
})
// streams will error asynchronously, and we want to handle that error
// appropriately, e.g. a 404 for a missing file. So we cannot use
// writeHead, and we need to resort to setHeader, which will trigger
// a writeHead when there is data to send.
if (!res.headersSent) {
for (const key in reply[kReplyHeaders]) {
res.setHeader(key, reply[kReplyHeaders][key])
}
} else {
reply.log.warn('response will send, but you shouldn\'t use res.writeHead in stream mode')
}
payload.pipe(res)
}
function sendTrailer (payload, res, reply) {
if (reply[kReplyTrailers] === null) {
// when no trailer, we close the stream
res.end(null, null, null) // avoid ArgumentsAdaptorTrampoline from V8
return
}
const trailerHeaders = Object.keys(reply[kReplyTrailers])
const trailers = {}
let handled = 0
let skipped = true
function send () {
// add trailers when all handler handled
/* istanbul ignore else */
if (handled === 0) {
res.addTrailers(trailers)
// we need to properly close the stream
// after trailers sent
res.end(null, null, null) // avoid ArgumentsAdaptorTrampoline from V8
}
}
for (const trailerName of trailerHeaders) {
if (typeof reply[kReplyTrailers][trailerName] !== 'function') continue
skipped = false
handled--
function cb (err, value) {
// TODO: we may protect multiple callback calls
// or mixing async-await with callback
handled++
// we can safely ignore error for trailer
// since it does affect the client
// we log in here only for debug usage
if (err) reply.log.debug(err)
else trailers[trailerName] = value
// we push the check to the end of event
// loop, so the registration continue to
// process.
process.nextTick(send)
}
const result = reply[kReplyTrailers][trailerName](reply, payload, cb)
if (typeof result === 'object' && typeof result.then === 'function') {
result.then((v) => cb(null, v), cb)
} else if (result !== null && result !== undefined) {
// TODO: should be removed in fastify@5
FSTDEP013()
cb(null, result)
}
}
// when all trailers are skipped
// we need to close the stream
if (skipped) res.end(null, null, null) // avoid ArgumentsAdaptorTrampoline from V8
}
function sendStreamTrailer (payload, res, reply) {
if (reply[kReplyTrailers] === null) return
payload.on('end', () => sendTrailer(null, res, reply))
}
function onErrorHook (reply, error, cb) {
if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) {
reply[kReplyIsRunningOnErrorHook] = true
onSendHookRunner(
reply[kRouteContext].onError,
reply.request,
reply,
error,
() => handleError(reply, error, cb)
)
} else {
handleError(reply, error, cb)
}
}
function setupResponseListeners (reply) {
reply[kReplyStartTime] = now()
const onResFinished = err => {
reply[kReplyEndTime] = now()
reply.raw.removeListener('finish', onResFinished)
reply.raw.removeListener('error', onResFinished)
const ctx = reply[kRouteContext]
if (ctx && ctx.onResponse !== null) {
onResponseHookRunner(
ctx.onResponse,
reply.request,
reply,
onResponseCallback
)
} else {
onResponseCallback(err, reply.request, reply)
}
}
reply.raw.on('finish', onResFinished)
reply.raw.on('error', onResFinished)
}
function onResponseCallback (err, request, reply) {
if (reply.log[kDisableRequestLogging]) {
return
}
const responseTime = reply.elapsedTime
if (err != null) {
reply.log.error({
res: reply,
err,
responseTime
}, 'request errored')
return
}
reply.log.info({
res: reply,
responseTime
}, 'request completed')
}
function buildReply (R) {
const props = R.props.slice()
function _Reply (res, request, log) {
this.raw = res
this[kReplyIsError] = false
this[kReplyErrorHandlerCalled] = false
this[kReplyHijacked] = false
this[kReplySerializer] = null
this.request = request
this[kReplyHeaders] = {}
this[kReplyTrailers] = null
this[kReplyStartTime] = undefined
this[kReplyEndTime] = undefined
this.log = log
// eslint-disable-next-line no-var
var prop
// eslint-disable-next-line no-var
for (var i = 0; i < props.length; i++) {
prop = props[i]
this[prop.key] = prop.value
}
}
Object.setPrototypeOf(_Reply.prototype, R.prototype)
Object.setPrototypeOf(_Reply, R)
_Reply.parent = R
_Reply.props = props
return _Reply
}
function notFound (reply) {
if (reply[kRouteContext][kFourOhFourContext] === null) {
reply.log.warn('Trying to send a NotFound error inside a 404 handler. Sending basic 404 response.')
reply.code(404).send('404 Not Found')
return
}
reply.request[kRouteContext] = reply[kRouteContext][kFourOhFourContext]
// preHandler hook
if (reply[kRouteContext].preHandler !== null) {
preHandlerHookRunner(
reply[kRouteContext].preHandler,
reply.request,
reply,
internals.preHandlerCallback
)
} else {
internals.preHandlerCallback(null, reply.request, reply)
}
}
/**
* This function runs when a payload that is not a string|buffer|stream or null
* should be serialized to be streamed to the response.
* This is the default serializer that can be customized by the user using the replySerializer
*
* @param {object} context the request context
* @param {object} data the JSON payload to serialize
* @param {number} statusCode the http status code
* @param {string} [contentType] the reply content type
* @returns {string} the serialized payload
*/
function serialize (context, data, statusCode, contentType) {
const fnSerialize = getSchemaSerializer(context, statusCode, contentType)
if (fnSerialize) {
return fnSerialize(data)
}
return JSON.stringify(data)
}
function noop () { }
module.exports = Reply
module.exports.buildReply = buildReply
module.exports.setupResponseListeners = setupResponseListeners
/***/ }),
/***/ 74729:
/***/ ((module) => {
"use strict";
/**
* @callback GenerateRequestId
* @param {Object} req
* @returns {string}
*/
/**
* @param {string} [requestIdHeader]
* @param {GenerateRequestId} [optGenReqId]
* @returns {GenerateRequestId}
*/
function reqIdGenFactory (requestIdHeader, optGenReqId) {
const genReqId = optGenReqId || buildDefaultGenReqId()
if (requestIdHeader) {
return buildOptionalHeaderReqId(requestIdHeader, genReqId)
}
return genReqId
}
function getGenReqId (contextServer, req) {
return contextServer.genReqId(req)
}
function buildDefaultGenReqId () {
// 2,147,483,647 (2^31 1) stands for max SMI value (an internal optimization of V8).
// With this upper bound, if you'll be generating 1k ids/sec, you're going to hit it in ~25 days.
// This is very likely to happen in real-world applications, hence the limit is enforced.
// Growing beyond this value will make the id generation slower and cause a deopt.
// In the worst cases, it will become a float, losing accuracy.
const maxInt = 2147483647
let nextReqId = 0
return function defaultGenReqId () {
nextReqId = (nextReqId + 1) & maxInt
return `req-${nextReqId.toString(36)}`
}
}
function buildOptionalHeaderReqId (requestIdHeader, genReqId) {
return function (req) {
return req.headers[requestIdHeader] || genReqId(req)
}
}
module.exports = {
getGenReqId,
reqIdGenFactory
}
/***/ }),
/***/ 11696:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const proxyAddr = __nccwpck_require__(80140)
const semver = __nccwpck_require__(11383)
const {
FSTDEP005,
FSTDEP012,
FSTDEP015,
FSTDEP016,
FSTDEP017,
FSTDEP018
} = __nccwpck_require__(59283)
const {
kHasBeenDecorated,
kSchemaBody,
kSchemaHeaders,
kSchemaParams,
kSchemaQuerystring,
kSchemaController,
kOptions,
kRequestCacheValidateFns,
kRouteContext,
kPublicRouteContext,
kRequestOriginalUrl
} = __nccwpck_require__(28622)
const { FST_ERR_REQ_INVALID_VALIDATION_INVOCATION } = __nccwpck_require__(89005)
const HTTP_PART_SYMBOL_MAP = {
body: kSchemaBody,
headers: kSchemaHeaders,
params: kSchemaParams,
querystring: kSchemaQuerystring,
query: kSchemaQuerystring
}
function Request (id, params, req, query, log, context) {
this.id = id
this[kRouteContext] = context
this.params = params
this.raw = req
this.query = query
this.log = log
this.body = undefined
}
Request.props = []
function getTrustProxyFn (tp) {
if (typeof tp === 'function') {
return tp
}
if (tp === true) {
// Support plain true/false
return function () { return true }
}
if (typeof tp === 'number') {
// Support trusting hop count
return function (a, i) { return i < tp }
}
if (typeof tp === 'string') {
// Support comma-separated tps
const values = tp.split(',').map(it => it.trim())
return proxyAddr.compile(values)
}
return proxyAddr.compile(tp)
}
function buildRequest (R, trustProxy) {
if (trustProxy) {
return buildRequestWithTrustProxy(R, trustProxy)
}
return buildRegularRequest(R)
}
function buildRegularRequest (R) {
const props = R.props.slice()
function _Request (id, params, req, query, log, context) {
this.id = id
this[kRouteContext] = context
this.params = params
this.raw = req
this.query = query
this.log = log
this.body = undefined
// eslint-disable-next-line no-var
var prop
// eslint-disable-next-line no-var
for (var i = 0; i < props.length; i++) {
prop = props[i]
this[prop.key] = prop.value
}
}
Object.setPrototypeOf(_Request.prototype, R.prototype)
Object.setPrototypeOf(_Request, R)
_Request.props = props
_Request.parent = R
return _Request
}
function getLastEntryInMultiHeaderValue (headerValue) {
// we use the last one if the header is set more than once
const lastIndex = headerValue.lastIndexOf(',')
return lastIndex === -1 ? headerValue.trim() : headerValue.slice(lastIndex + 1).trim()
}
function buildRequestWithTrustProxy (R, trustProxy) {
const _Request = buildRegularRequest(R)
const proxyFn = getTrustProxyFn(trustProxy)
// This is a more optimized version of decoration
_Request[kHasBeenDecorated] = true
Object.defineProperties(_Request.prototype, {
ip: {
get () {
return proxyAddr(this.raw, proxyFn)
}
},
ips: {
get () {
return proxyAddr.all(this.raw, proxyFn)
}
},
hostname: {
get () {
if (this.ip !== undefined && this.headers['x-forwarded-host']) {
return getLastEntryInMultiHeaderValue(this.headers['x-forwarded-host'])
}
return this.headers.host || this.headers[':authority']
}
},
protocol: {
get () {
if (this.headers['x-forwarded-proto']) {
return getLastEntryInMultiHeaderValue(this.headers['x-forwarded-proto'])
}
if (this.socket) {
return this.socket.encrypted ? 'https' : 'http'
}
}
}
})
return _Request
}
Object.defineProperties(Request.prototype, {
server: {
get () {
return this[kRouteContext].server
}
},
url: {
get () {
return this.raw.url
}
},
originalUrl: {
get () {
/* istanbul ignore else */
if (!this[kRequestOriginalUrl]) {
this[kRequestOriginalUrl] = this.raw.originalUrl || this.raw.url
}
return this[kRequestOriginalUrl]
}
},
method: {
get () {
return this.raw.method
}
},
context: {
get () {
FSTDEP012()
return this[kRouteContext]
}
},
routerPath: {
get () {
FSTDEP017()
return this[kRouteContext].config?.url
}
},
routeOptions: {
get () {
const context = this[kRouteContext]
const routeLimit = context._parserOptions.limit
const serverLimit = context.server.initialConfig.bodyLimit
const version = context.server.hasConstraintStrategy('version') ? this.raw.headers['accept-version'] : undefined
const options = {
method: context.config?.method,
url: context.config?.url,
bodyLimit: (routeLimit || serverLimit),
attachValidation: context.attachValidation,
logLevel: context.logLevel,
exposeHeadRoute: context.exposeHeadRoute,
prefixTrailingSlash: context.prefixTrailingSlash,
handler: context.handler,
version
}
Object.defineProperties(options, {
config: {
get: () => context.config
},
schema: {
get: () => context.schema
}
})
return Object.freeze(options)
}
},
routerMethod: {
get () {
FSTDEP018()
return this[kRouteContext].config?.method
}
},
routeConfig: {
get () {
FSTDEP016()
return this[kRouteContext][kPublicRouteContext]?.config
}
},
routeSchema: {
get () {
FSTDEP015()
return this[kRouteContext][kPublicRouteContext].schema
}
},
is404: {
get () {
return this[kRouteContext].config?.url === undefined
}
},
connection: {
get () {
/* istanbul ignore next */
if (semver.gte(process.versions.node, '13.0.0')) {
FSTDEP005()
}
return this.raw.connection
}
},
socket: {
get () {
return this.raw.socket
}
},
ip: {
get () {
if (this.socket) {
return this.socket.remoteAddress
}
}
},
hostname: {
get () {
return this.raw.headers.host || this.raw.headers[':authority']
}
},
protocol: {
get () {
if (this.socket) {
return this.socket.encrypted ? 'https' : 'http'
}
}
},
headers: {
get () {
if (this.additionalHeaders) {
return Object.assign({}, this.raw.headers, this.additionalHeaders)
}
return this.raw.headers
},
set (headers) {
this.additionalHeaders = headers
}
},
getValidationFunction: {
value: function (httpPartOrSchema) {
if (typeof httpPartOrSchema === 'string') {
const symbol = HTTP_PART_SYMBOL_MAP[httpPartOrSchema]
return this[kRouteContext][symbol]
} else if (typeof httpPartOrSchema === 'object') {
return this[kRouteContext][kRequestCacheValidateFns]?.get(httpPartOrSchema)
}
}
},
compileValidationSchema: {
value: function (schema, httpPart = null) {
const { method, url } = this
if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) {
return this[kRouteContext][kRequestCacheValidateFns].get(schema)
}
const validatorCompiler = this[kRouteContext].validatorCompiler ||
this.server[kSchemaController].validatorCompiler ||
(
// We compile the schemas if no custom validatorCompiler is provided
// nor set
this.server[kSchemaController].setupValidator(this.server[kOptions]) ||
this.server[kSchemaController].validatorCompiler
)
const validateFn = validatorCompiler({
schema,
method,
url,
httpPart
})
// We create a WeakMap to compile the schema only once
// Its done lazily to avoid add overhead by creating the WeakMap
// if it is not used
// TODO: Explore a central cache for all the schemas shared across
// encapsulated contexts
if (this[kRouteContext][kRequestCacheValidateFns] == null) {
this[kRouteContext][kRequestCacheValidateFns] = new WeakMap()
}
this[kRouteContext][kRequestCacheValidateFns].set(schema, validateFn)
return validateFn
}
},
validateInput: {
value: function (input, schema, httpPart) {
httpPart = typeof schema === 'string' ? schema : httpPart
const symbol = (httpPart != null && typeof httpPart === 'string') && HTTP_PART_SYMBOL_MAP[httpPart]
let validate
if (symbol) {
// Validate using the HTTP Request Part schema
validate = this[kRouteContext][symbol]
}
// We cannot compile if the schema is missed
if (validate == null && (schema == null ||
typeof schema !== 'object' ||
Array.isArray(schema))
) {
throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart)
}
if (validate == null) {
if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) {
validate = this[kRouteContext][kRequestCacheValidateFns].get(schema)
} else {
// We proceed to compile if there's no validate function yet
validate = this.compileValidationSchema(schema, httpPart)
}
}
return validate(input)
}
}
})
module.exports = Request
module.exports.buildRequest = buildRequest
/***/ }),
/***/ 61237:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const FindMyWay = __nccwpck_require__(72026)
const Context = __nccwpck_require__(76676)
const handleRequest = __nccwpck_require__(8322)
const { onRequestAbortHookRunner, lifecycleHooks, preParsingHookRunner, onTimeoutHookRunner, onRequestHookRunner } = __nccwpck_require__(26133)
const { supportedMethods } = __nccwpck_require__(8340)
const { normalizeSchema } = __nccwpck_require__(48122)
const { parseHeadOnSendHandlers } = __nccwpck_require__(25379)
const {
FSTDEP007,
FSTDEP008,
FSTDEP014
} = __nccwpck_require__(59283)
const {
compileSchemasForValidation,
compileSchemasForSerialization
} = __nccwpck_require__(78365)
const {
FST_ERR_SCH_VALIDATION_BUILD,
FST_ERR_SCH_SERIALIZATION_BUILD,
FST_ERR_DEFAULT_ROUTE_INVALID_TYPE,
FST_ERR_DUPLICATED_ROUTE,
FST_ERR_INVALID_URL,
FST_ERR_HOOK_INVALID_HANDLER,
FST_ERR_ROUTE_OPTIONS_NOT_OBJ,
FST_ERR_ROUTE_DUPLICATED_HANDLER,
FST_ERR_ROUTE_HANDLER_NOT_FN,
FST_ERR_ROUTE_MISSING_HANDLER,
FST_ERR_ROUTE_METHOD_NOT_SUPPORTED,
FST_ERR_ROUTE_METHOD_INVALID,
FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED,
FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT,
FST_ERR_HOOK_INVALID_ASYNC_HANDLER
} = __nccwpck_require__(89005)
const {
kRoutePrefix,
kLogLevel,
kLogSerializers,
kHooks,
kSchemaController,
kOptions,
kReplySerializerDefault,
kReplyIsError,
kRequestPayloadStream,
kDisableRequestLogging,
kSchemaErrorFormatter,
kErrorHandler,
kHasBeenDecorated,
kRequestAcceptVersion,
kRouteByFastify,
kRouteContext
} = __nccwpck_require__(28622)
const { buildErrorHandler } = __nccwpck_require__(58755)
const { createChildLogger } = __nccwpck_require__(8102)
const { getGenReqId } = __nccwpck_require__(74729)
function buildRouting (options) {
const router = FindMyWay(options.config)
let avvio
let fourOhFour
let logger
let hasLogger
let setupResponseListeners
let throwIfAlreadyStarted
let disableRequestLogging
let ignoreTrailingSlash
let ignoreDuplicateSlashes
let return503OnClosing
let globalExposeHeadRoutes
let validateHTTPVersion
let keepAliveConnections
let closing = false
return {
/**
* @param {import('../fastify').FastifyServerOptions} options
* @param {*} fastifyArgs
*/
setup (options, fastifyArgs) {
avvio = fastifyArgs.avvio
fourOhFour = fastifyArgs.fourOhFour
logger = fastifyArgs.logger
hasLogger = fastifyArgs.hasLogger
setupResponseListeners = fastifyArgs.setupResponseListeners
throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted
validateHTTPVersion = fastifyArgs.validateHTTPVersion
globalExposeHeadRoutes = options.exposeHeadRoutes
disableRequestLogging = options.disableRequestLogging
ignoreTrailingSlash = options.ignoreTrailingSlash
ignoreDuplicateSlashes = options.ignoreDuplicateSlashes
return503OnClosing = Object.prototype.hasOwnProperty.call(options, 'return503OnClosing') ? options.return503OnClosing : true
keepAliveConnections = fastifyArgs.keepAliveConnections
},
routing: router.lookup.bind(router), // router func to find the right handler to call
route, // configure a route in the fastify instance
hasRoute,
prepareRoute,
getDefaultRoute: function () {
FSTDEP014()
return router.defaultRoute
},
setDefaultRoute: function (defaultRoute) {
FSTDEP014()
if (typeof defaultRoute !== 'function') {
throw new FST_ERR_DEFAULT_ROUTE_INVALID_TYPE()
}
router.defaultRoute = defaultRoute
},
routeHandler,
closeRoutes: () => { closing = true },
printRoutes: router.prettyPrint.bind(router),
addConstraintStrategy,
hasConstraintStrategy,
isAsyncConstraint,
findRoute
}
function addConstraintStrategy (strategy) {
throwIfAlreadyStarted('Cannot add constraint strategy!')
return router.addConstraintStrategy(strategy)
}
function hasConstraintStrategy (strategyName) {
return router.hasConstraintStrategy(strategyName)
}
function isAsyncConstraint () {
return router.constrainer.asyncStrategiesInUse.size > 0
}
// Convert shorthand to extended route declaration
function prepareRoute ({ method, url, options, handler, isFastify }) {
if (typeof url !== 'string') {
throw new FST_ERR_INVALID_URL(typeof url)
}
if (!handler && typeof options === 'function') {
handler = options // for support over direct function calls such as fastify.get() options are reused as the handler
options = {}
} else if (handler && typeof handler === 'function') {
if (Object.prototype.toString.call(options) !== '[object Object]') {
throw new FST_ERR_ROUTE_OPTIONS_NOT_OBJ(method, url)
} else if (options.handler) {
if (typeof options.handler === 'function') {
throw new FST_ERR_ROUTE_DUPLICATED_HANDLER(method, url)
} else {
throw new FST_ERR_ROUTE_HANDLER_NOT_FN(method, url)
}
}
}
options = Object.assign({}, options, {
method,
url,
path: url,
handler: handler || (options && options.handler)
})
return route.call(this, { options, isFastify })
}
function hasRoute ({ options }) {
return findRoute(options) !== null
}
function findRoute (options) {
const route = router.find(
options.method,
options.url || '',
options.constraints
)
if (route) {
// we must reduce the expose surface, otherwise
// we provide the ability for the user to modify
// all the route and server information in runtime
return {
handler: route.handler,
params: route.params,
searchParams: route.searchParams
}
} else {
return null
}
}
/**
* Route management
* @param {{ options: import('../fastify').RouteOptions, isFastify: boolean }}
*/
function route ({ options, isFastify }) {
// Since we are mutating/assigning only top level props, it is fine to have a shallow copy using the spread operator
const opts = { ...options }
const { exposeHeadRoute } = opts
const hasRouteExposeHeadRouteFlag = exposeHeadRoute != null
const shouldExposeHead = hasRouteExposeHeadRouteFlag ? exposeHeadRoute : globalExposeHeadRoutes
const isGetRoute = opts.method === 'GET' ||
(Array.isArray(opts.method) && opts.method.includes('GET'))
const isHeadRoute = opts.method === 'HEAD' ||
(Array.isArray(opts.method) && opts.method.includes('HEAD'))
// we need to clone a set of initial options for HEAD route
const headOpts = shouldExposeHead && isGetRoute ? { ...options } : null
throwIfAlreadyStarted('Cannot add route!')
const path = opts.url || opts.path || ''
if (Array.isArray(opts.method)) {
// eslint-disable-next-line no-var
for (var i = 0; i < opts.method.length; ++i) {
opts.method[i] = normalizeAndValidateMethod(opts.method[i])
validateSchemaBodyOption(opts.method[i], path, opts.schema)
}
} else {
opts.method = normalizeAndValidateMethod(opts.method)
validateSchemaBodyOption(opts.method, path, opts.schema)
}
if (!opts.handler) {
throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path)
}
if (opts.errorHandler !== undefined && typeof opts.errorHandler !== 'function') {
throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path)
}
validateBodyLimitOption(opts.bodyLimit)
const prefix = this[kRoutePrefix]
if (path === '/' && prefix.length > 0 && opts.method !== 'HEAD') {
switch (opts.prefixTrailingSlash) {
case 'slash':
addNewRoute.call(this, { path, isFastify })
break
case 'no-slash':
addNewRoute.call(this, { path: '', isFastify })
break
case 'both':
default:
addNewRoute.call(this, { path: '', isFastify })
// If ignoreTrailingSlash is set to true we need to add only the '' route to prevent adding an incomplete one.
if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith('/'))) {
addNewRoute.call(this, { path, prefixing: true, isFastify })
}
}
} else if (path[0] === '/' && prefix.endsWith('/')) {
// Ensure that '/prefix/' + '/route' gets registered as '/prefix/route'
addNewRoute.call(this, { path: path.slice(1), isFastify })
} else {
addNewRoute.call(this, { path, isFastify })
}
// chainable api
return this
function addNewRoute ({ path, prefixing = false, isFastify = false }) {
const url = prefix + path
opts.url = url
opts.path = url
opts.routePath = path
opts.prefix = prefix
opts.logLevel = opts.logLevel || this[kLogLevel]
if (this[kLogSerializers] || opts.logSerializers) {
opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers)
}
if (opts.attachValidation == null) {
opts.attachValidation = false
}
if (prefixing === false) {
// run 'onRoute' hooks
for (const hook of this[kHooks].onRoute) {
hook.call(this, opts)
}
}
for (const hook of lifecycleHooks) {
if (opts && hook in opts) {
if (Array.isArray(opts[hook])) {
for (const func of opts[hook]) {
if (typeof func !== 'function') {
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(func))
}
if (hook === 'onSend' || hook === 'preSerialization' || hook === 'onError' || hook === 'preParsing') {
if (func.constructor.name === 'AsyncFunction' && func.length === 4) {
throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
} else if (hook === 'onRequestAbort') {
if (func.constructor.name === 'AsyncFunction' && func.length !== 1) {
throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
} else {
if (func.constructor.name === 'AsyncFunction' && func.length === 3) {
throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
}
}
}
} else if (opts[hook] !== undefined && typeof opts[hook] !== 'function') {
throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(opts[hook]))
}
}
}
const constraints = opts.constraints || {}
const config = {
...opts.config,
url,
method: opts.method
}
const context = new Context({
schema: opts.schema,
handler: opts.handler.bind(this),
config,
errorHandler: opts.errorHandler,
childLoggerFactory: opts.childLoggerFactory,
bodyLimit: opts.bodyLimit,
logLevel: opts.logLevel,
logSerializers: opts.logSerializers,
attachValidation: opts.attachValidation,
schemaErrorFormatter: opts.schemaErrorFormatter,
replySerializer: this[kReplySerializerDefault],
validatorCompiler: opts.validatorCompiler,
serializerCompiler: opts.serializerCompiler,
exposeHeadRoute: shouldExposeHead,
prefixTrailingSlash: (opts.prefixTrailingSlash || 'both'),
server: this,
isFastify
})
if (opts.version) {
FSTDEP008()
constraints.version = opts.version
}
const headHandler = router.findRoute('HEAD', opts.url, constraints)
const hasHEADHandler = headHandler !== null
// remove the head route created by fastify
if (isHeadRoute && hasHEADHandler && !context[kRouteByFastify] && headHandler.store[kRouteByFastify]) {
router.off('HEAD', opts.url, constraints)
}
try {
router.on(opts.method, opts.url, { constraints }, routeHandler, context)
} catch (error) {
// any route insertion error created by fastify can be safely ignore
// because it only duplicate route for head
if (!context[kRouteByFastify]) {
const isDuplicatedRoute = error.message.includes(`Method '${opts.method}' already declared for route '${opts.url}'`)
if (isDuplicatedRoute) {
throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url)
}
throw error
}
}
this.after((notHandledErr, done) => {
// Send context async
context.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]
context._parserOptions.limit = opts.bodyLimit || null
context.logLevel = opts.logLevel
context.logSerializers = opts.logSerializers
context.attachValidation = opts.attachValidation
context[kReplySerializerDefault] = this[kReplySerializerDefault]
context.schemaErrorFormatter = opts.schemaErrorFormatter || this[kSchemaErrorFormatter] || context.schemaErrorFormatter
// Run hooks and more
avvio.once('preReady', () => {
for (const hook of lifecycleHooks) {
const toSet = this[kHooks][hook]
.concat(opts[hook] || [])
.map(h => h.bind(this))
context[hook] = toSet.length ? toSet : null
}
// Optimization: avoid encapsulation if no decoration has been done.
while (!context.Request[kHasBeenDecorated] && context.Request.parent) {
context.Request = context.Request.parent
}
while (!context.Reply[kHasBeenDecorated] && context.Reply.parent) {
context.Reply = context.Reply.parent
}
// Must store the 404 Context in 'preReady' because it is only guaranteed to
// be available after all of the plugins and routes have been loaded.
fourOhFour.setContext(this, context)
if (opts.schema) {
context.schema = normalizeSchema(context.schema, this.initialConfig)
const schemaController = this[kSchemaController]
if (!opts.validatorCompiler && (opts.schema.body || opts.schema.headers || opts.schema.querystring || opts.schema.params)) {
schemaController.setupValidator(this[kOptions])
}
try {
const isCustom = typeof opts?.validatorCompiler === 'function' || schemaController.isCustomValidatorCompiler
compileSchemasForValidation(context, opts.validatorCompiler || schemaController.validatorCompiler, isCustom)
} catch (error) {
throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url, error.message)
}
if (opts.schema.response && !opts.serializerCompiler) {
schemaController.setupSerializer(this[kOptions])
}
try {
compileSchemasForSerialization(context, opts.serializerCompiler || schemaController.serializerCompiler)
} catch (error) {
throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url, error.message)
}
}
})
done(notHandledErr)
})
// register head route in sync
// we must place it after the `this.after`
if (shouldExposeHead && isGetRoute && !isHeadRoute && !hasHEADHandler) {
const onSendHandlers = parseHeadOnSendHandlers(headOpts.onSend)
prepareRoute.call(this, { method: 'HEAD', url: path, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true })
} else if (hasHEADHandler && exposeHeadRoute) {
FSTDEP007()
}
}
}
// HTTP request entry point, the routing has already been executed
function routeHandler (req, res, params, context, query) {
const id = getGenReqId(context.server, req)
const loggerOpts = {
level: context.logLevel
}
if (context.logSerializers) {
loggerOpts.serializers = context.logSerializers
}
const childLogger = createChildLogger(context, logger, req, id, loggerOpts)
childLogger[kDisableRequestLogging] = disableRequestLogging
// TODO: The check here should be removed once https://github.com/nodejs/node/issues/43115 resolve in core.
if (!validateHTTPVersion(req.httpVersion)) {
childLogger.info({ res: { statusCode: 505 } }, 'request aborted - invalid HTTP version')
const message = '{"error":"HTTP Version Not Supported","message":"HTTP Version Not Supported","statusCode":505}'
const headers = {
'Content-Type': 'application/json',
'Content-Length': message.length
}
res.writeHead(505, headers)
res.end(message)
return
}
if (closing === true) {
/* istanbul ignore next mac, windows */
if (req.httpVersionMajor !== 2) {
res.setHeader('Connection', 'close')
}
// TODO remove return503OnClosing after Node v18 goes EOL
/* istanbul ignore else */
if (return503OnClosing) {
// On Node v19 we cannot test this behavior as it won't be necessary
// anymore. It will close all the idle connections before they reach this
// stage.
const headers = {
'Content-Type': 'application/json',
'Content-Length': '80'
}
res.writeHead(503, headers)
res.end('{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}')
childLogger.info({ res: { statusCode: 503 } }, 'request aborted - refusing to accept new requests as server is closing')
return
}
}
// When server.forceCloseConnections is true, we will collect any requests
// that have indicated they want persistence so that they can be reaped
// on server close. Otherwise, the container is a noop container.
const connHeader = String.prototype.toLowerCase.call(req.headers.connection || '')
if (connHeader === 'keep-alive') {
if (keepAliveConnections.has(req.socket) === false) {
keepAliveConnections.add(req.socket)
req.socket.on('close', removeTrackedSocket.bind({ keepAliveConnections, socket: req.socket }))
}
}
// we revert the changes in defaultRoute
if (req.headers[kRequestAcceptVersion] !== undefined) {
req.headers['accept-version'] = req.headers[kRequestAcceptVersion]
req.headers[kRequestAcceptVersion] = undefined
}
const request = new context.Request(id, params, req, query, childLogger, context)
const reply = new context.Reply(res, request, childLogger)
if (disableRequestLogging === false) {
childLogger.info({ req: request }, 'incoming request')
}
if (hasLogger === true || context.onResponse !== null) {
setupResponseListeners(reply)
}
if (context.onRequest !== null) {
onRequestHookRunner(
context.onRequest,
request,
reply,
runPreParsing
)
} else {
runPreParsing(null, request, reply)
}
if (context.onRequestAbort !== null) {
req.on('close', () => {
/* istanbul ignore else */
if (req.aborted) {
onRequestAbortHookRunner(
context.onRequestAbort,
request,
handleOnRequestAbortHooksErrors.bind(null, reply)
)
}
})
}
if (context.onTimeout !== null) {
if (!request.raw.socket._meta) {
request.raw.socket.on('timeout', handleTimeout)
}
request.raw.socket._meta = { context, request, reply }
}
}
}
function handleOnRequestAbortHooksErrors (reply, err) {
if (err) {
reply.log.error({ err }, 'onRequestAborted hook failed')
}
}
function handleTimeout () {
const { context, request, reply } = this._meta
onTimeoutHookRunner(
context.onTimeout,
request,
reply,
noop
)
}
function normalizeAndValidateMethod (method) {
if (typeof method !== 'string') {
throw new FST_ERR_ROUTE_METHOD_INVALID()
}
method = method.toUpperCase()
if (supportedMethods.indexOf(method) === -1) {
throw new FST_ERR_ROUTE_METHOD_NOT_SUPPORTED(method)
}
return method
}
function validateSchemaBodyOption (method, path, schema) {
if ((method === 'GET' || method === 'HEAD') && schema && schema.body) {
throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path)
}
}
function validateBodyLimitOption (bodyLimit) {
if (bodyLimit === undefined) return
if (!Number.isInteger(bodyLimit) || bodyLimit <= 0) {
throw new FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT(bodyLimit)
}
}
function runPreParsing (err, request, reply) {
if (reply.sent === true) return
if (err != null) {
reply[kReplyIsError] = true
reply.send(err)
return
}
request[kRequestPayloadStream] = request.raw
if (request[kRouteContext].preParsing !== null) {
preParsingHookRunner(request[kRouteContext].preParsing, request, reply, handleRequest)
} else {
handleRequest(null, request, reply)
}
}
/**
* Used within the route handler as a `net.Socket.close` event handler.
* The purpose is to remove a socket from the tracked sockets collection when
* the socket has naturally timed out.
*/
function removeTrackedSocket () {
this.keepAliveConnections.delete(this.socket)
}
function noop () { }
module.exports = { buildRouting, validateBodyLimitOption }
/***/ }),
/***/ 92310:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { buildSchemas } = __nccwpck_require__(48122)
const SerializerSelector = __nccwpck_require__(94908)
const ValidatorSelector = __nccwpck_require__(14018)
/**
* Called at every fastify context that is being created.
* @param {object} parentSchemaCtrl: the SchemaController instance of the Fastify parent context
* @param {object} opts: the `schemaController` server option. It can be undefined when a parentSchemaCtrl is set
* @return {object}:a new SchemaController
*/
function buildSchemaController (parentSchemaCtrl, opts) {
if (parentSchemaCtrl) {
return new SchemaController(parentSchemaCtrl, opts)
}
const compilersFactory = Object.assign({
buildValidator: null,
buildSerializer: null
}, opts?.compilersFactory)
if (!compilersFactory.buildValidator) {
compilersFactory.buildValidator = ValidatorSelector()
}
if (!compilersFactory.buildSerializer) {
compilersFactory.buildSerializer = SerializerSelector()
}
const option = {
bucket: (opts && opts.bucket) || buildSchemas,
compilersFactory,
isCustomValidatorCompiler: typeof opts?.compilersFactory?.buildValidator === 'function',
isCustomSerializerCompiler: typeof opts?.compilersFactory?.buildValidator === 'function'
}
return new SchemaController(undefined, option)
}
class SchemaController {
constructor (parent, options) {
this.opts = options || parent?.opts
this.addedSchemas = false
this.compilersFactory = this.opts.compilersFactory
if (parent) {
this.schemaBucket = this.opts.bucket(parent.getSchemas())
this.validatorCompiler = parent.getValidatorCompiler()
this.serializerCompiler = parent.getSerializerCompiler()
this.isCustomValidatorCompiler = parent.isCustomValidatorCompiler
this.isCustomSerializerCompiler = parent.isCustomSerializerCompiler
this.parent = parent
} else {
this.schemaBucket = this.opts.bucket()
this.isCustomValidatorCompiler = this.opts.isCustomValidatorCompiler || false
this.isCustomSerializerCompiler = this.opts.isCustomSerializerCompiler || false
}
}
// Bucket interface
add (schema) {
this.addedSchemas = true
return this.schemaBucket.add(schema)
}
getSchema (schemaId) {
return this.schemaBucket.getSchema(schemaId)
}
getSchemas () {
return this.schemaBucket.getSchemas()
}
setValidatorCompiler (validatorCompiler) {
// Set up as if the fixed validator compiler had been provided
// by a custom 'options.compilersFactory.buildValidator' that
// always returns the same compiler object. This is required because:
//
// - setValidatorCompiler must immediately install a compiler to preserve
// legacy behavior
// - setupValidator will recreate compilers from builders in some
// circumstances, so we have to install this adapter to make it
// behave the same if the legacy API is used
//
// The cloning of the compilersFactory object is necessary because
// we are aliasing the parent compilersFactory if none was provided
// to us (see constructor.)
this.compilersFactory = Object.assign(
{},
this.compilersFactory,
{ buildValidator: () => validatorCompiler })
this.validatorCompiler = validatorCompiler
this.isCustomValidatorCompiler = true
}
setSerializerCompiler (serializerCompiler) {
// Set up as if the fixed serializer compiler had been provided
// by a custom 'options.compilersFactory.buildSerializer' that
// always returns the same compiler object. This is required because:
//
// - setSerializerCompiler must immediately install a compiler to preserve
// legacy behavior
// - setupSerializer will recreate compilers from builders in some
// circumstances, so we have to install this adapter to make it
// behave the same if the legacy API is used
//
// The cloning of the compilersFactory object is necessary because
// we are aliasing the parent compilersFactory if none was provided
// to us (see constructor.)
this.compilersFactory = Object.assign(
{},
this.compilersFactory,
{ buildSerializer: () => serializerCompiler })
this.serializerCompiler = serializerCompiler
this.isCustomSerializerCompiler = true
}
getValidatorCompiler () {
return this.validatorCompiler || (this.parent && this.parent.getValidatorCompiler())
}
getSerializerCompiler () {
return this.serializerCompiler || (this.parent && this.parent.getSerializerCompiler())
}
getSerializerBuilder () {
return this.compilersFactory.buildSerializer || (this.parent && this.parent.getSerializerBuilder())
}
getValidatorBuilder () {
return this.compilersFactory.buildValidator || (this.parent && this.parent.getValidatorBuilder())
}
/**
* This method will be called when a validator must be setup.
* Do not setup the compiler more than once
* @param {object} serverOptions the fastify server options
*/
setupValidator (serverOptions) {
const isReady = this.validatorCompiler !== undefined && !this.addedSchemas
if (isReady) {
return
}
this.validatorCompiler = this.getValidatorBuilder()(this.schemaBucket.getSchemas(), serverOptions.ajv)
}
/**
* This method will be called when a serializer must be setup.
* Do not setup the compiler more than once
* @param {object} serverOptions the fastify server options
*/
setupSerializer (serverOptions) {
const isReady = this.serializerCompiler !== undefined && !this.addedSchemas
if (isReady) {
return
}
this.serializerCompiler = this.getSerializerBuilder()(this.schemaBucket.getSchemas(), serverOptions.serializerOpts)
}
}
SchemaController.buildSchemaController = buildSchemaController
module.exports = SchemaController
/***/ }),
/***/ 48122:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastClone = __nccwpck_require__(11868)({ circles: false, proto: true })
const { kSchemaVisited, kSchemaResponse } = __nccwpck_require__(28622)
const kFluentSchema = Symbol.for('fluent-schema-object')
const {
FST_ERR_SCH_MISSING_ID,
FST_ERR_SCH_ALREADY_PRESENT,
FST_ERR_SCH_DUPLICATE,
FST_ERR_SCH_CONTENT_MISSING_SCHEMA
} = __nccwpck_require__(89005)
const SCHEMAS_SOURCE = ['params', 'body', 'querystring', 'query', 'headers']
function Schemas (initStore) {
this.store = initStore || {}
}
Schemas.prototype.add = function (inputSchema) {
const schema = fastClone((inputSchema.isFluentSchema || inputSchema.isFluentJSONSchema || inputSchema[kFluentSchema])
? inputSchema.valueOf()
: inputSchema
)
// developers can add schemas without $id, but with $def instead
const id = schema.$id
if (!id) {
throw new FST_ERR_SCH_MISSING_ID()
}
if (this.store[id]) {
throw new FST_ERR_SCH_ALREADY_PRESENT(id)
}
this.store[id] = schema
}
Schemas.prototype.getSchemas = function () {
return Object.assign({}, this.store)
}
Schemas.prototype.getSchema = function (schemaId) {
return this.store[schemaId]
}
/**
* Checks whether a schema is a non-plain object.
*
* @param {*} schema the schema to check
* @returns {boolean} true if schema has a custom prototype
*/
function isCustomSchemaPrototype (schema) {
return typeof schema === 'object' && Object.getPrototypeOf(schema) !== Object.prototype
}
function normalizeSchema (routeSchemas, serverOptions) {
if (routeSchemas[kSchemaVisited]) {
return routeSchemas
}
// alias query to querystring schema
if (routeSchemas.query) {
// check if our schema has both querystring and query
if (routeSchemas.querystring) {
throw new FST_ERR_SCH_DUPLICATE('querystring')
}
routeSchemas.querystring = routeSchemas.query
}
generateFluentSchema(routeSchemas)
for (const key of SCHEMAS_SOURCE) {
const schema = routeSchemas[key]
if (schema && !isCustomSchemaPrototype(schema)) {
routeSchemas[key] = getSchemaAnyway(schema, serverOptions.jsonShorthand)
}
}
if (routeSchemas.response) {
const httpCodes = Object.keys(routeSchemas.response)
for (const code of httpCodes) {
if (isCustomSchemaPrototype(routeSchemas.response[code])) {
continue
}
const contentProperty = routeSchemas.response[code].content
let hasContentMultipleContentTypes = false
if (contentProperty) {
const keys = Object.keys(contentProperty)
for (let i = 0; i < keys.length; i++) {
const mediaName = keys[i]
if (!contentProperty[mediaName].schema) {
if (keys.length === 1) { break }
throw new FST_ERR_SCH_CONTENT_MISSING_SCHEMA(mediaName)
}
routeSchemas.response[code].content[mediaName].schema = getSchemaAnyway(contentProperty[mediaName].schema, serverOptions.jsonShorthand)
if (i === keys.length - 1) {
hasContentMultipleContentTypes = true
}
}
}
if (!hasContentMultipleContentTypes) {
routeSchemas.response[code] = getSchemaAnyway(routeSchemas.response[code], serverOptions.jsonShorthand)
}
}
}
routeSchemas[kSchemaVisited] = true
return routeSchemas
}
function generateFluentSchema (schema) {
for (const key of SCHEMAS_SOURCE) {
if (schema[key] && (schema[key].isFluentSchema || schema[key][kFluentSchema])) {
schema[key] = schema[key].valueOf()
}
}
if (schema.response) {
const httpCodes = Object.keys(schema.response)
for (const code of httpCodes) {
if (schema.response[code].isFluentSchema || schema.response[code][kFluentSchema]) {
schema.response[code] = schema.response[code].valueOf()
}
}
}
}
function getSchemaAnyway (schema, jsonShorthand) {
if (!jsonShorthand || schema.$ref || schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema
if (!schema.type && !schema.properties) {
return {
type: 'object',
properties: schema
}
}
return schema
}
/**
* Search for the right JSON schema compiled function in the request context
* setup by the route configuration `schema.response`.
* It will look for the exact match (eg 200) or generic (eg 2xx)
*
* @param {object} context the request context
* @param {number} statusCode the http status code
* @param {string} [contentType] the reply content type
* @returns {function|false} the right JSON Schema function to serialize
* the reply or false if it is not set
*/
function getSchemaSerializer (context, statusCode, contentType) {
const responseSchemaDef = context[kSchemaResponse]
if (!responseSchemaDef) {
return false
}
if (responseSchemaDef[statusCode]) {
if (responseSchemaDef[statusCode].constructor === Object && contentType) {
const mediaName = contentType.split(';', 1)[0]
if (responseSchemaDef[statusCode][mediaName]) {
return responseSchemaDef[statusCode][mediaName]
}
return false
}
return responseSchemaDef[statusCode]
}
const fallbackStatusCode = (statusCode + '')[0] + 'xx'
if (responseSchemaDef[fallbackStatusCode]) {
if (responseSchemaDef[fallbackStatusCode].constructor === Object && contentType) {
const mediaName = contentType.split(';', 1)[0]
if (responseSchemaDef[fallbackStatusCode][mediaName]) {
return responseSchemaDef[fallbackStatusCode][mediaName]
}
return false
}
return responseSchemaDef[fallbackStatusCode]
}
if (responseSchemaDef.default) {
if (responseSchemaDef.default.constructor === Object && contentType) {
const mediaName = contentType.split(';', 1)[0]
if (responseSchemaDef.default[mediaName]) {
return responseSchemaDef.default[mediaName]
}
return false
}
return responseSchemaDef.default
}
return false
}
module.exports = {
buildSchemas (initStore) { return new Schemas(initStore) },
getSchemaSerializer,
normalizeSchema
}
/***/ }),
/***/ 60410:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const http = __nccwpck_require__(88849)
const https = __nccwpck_require__(22286)
const dns = __nccwpck_require__(30604)
const { FSTDEP011 } = __nccwpck_require__(59283)
const { kState, kOptions, kServerBindings } = __nccwpck_require__(28622)
const { onListenHookRunner } = __nccwpck_require__(26133)
const {
FST_ERR_HTTP2_INVALID_VERSION,
FST_ERR_REOPENED_CLOSE_SERVER,
FST_ERR_REOPENED_SERVER,
FST_ERR_LISTEN_OPTIONS_INVALID
} = __nccwpck_require__(89005)
module.exports.createServer = createServer
module.exports.compileValidateHTTPVersion = compileValidateHTTPVersion
function defaultResolveServerListeningText (address) {
return `Server listening at ${address}`
}
function createServer (options, httpHandler) {
const server = getServerInstance(options, httpHandler)
// `this` is the Fastify object
function listen (listenOptions, ...args) {
let cb = args.slice(-1).pop()
// When the variadic signature deprecation is complete, the function
// declaration should become:
// function listen (listenOptions = { port: 0, host: 'localhost' }, cb = undefined)
// Upon doing so, the `normalizeListenArgs` function is no longer needed,
// and all of this preamble to feed it correctly also no longer needed.
const firstArgType = Object.prototype.toString.call(arguments[0])
if (arguments.length === 0) {
listenOptions = normalizeListenArgs([])
} else if (arguments.length > 0 && (firstArgType !== '[object Object]' && firstArgType !== '[object Function]')) {
FSTDEP011()
listenOptions = normalizeListenArgs(Array.from(arguments))
cb = listenOptions.cb
} else if (args.length > 1) {
// `.listen(obj, a, ..., n, callback )`
FSTDEP011()
// Deal with `.listen(port, host, backlog, [cb])`
const hostPath = listenOptions.path ? [listenOptions.path] : [listenOptions.port ?? 0, listenOptions.host ?? 'localhost']
Object.assign(listenOptions, normalizeListenArgs([...hostPath, ...args]))
} else {
listenOptions.cb = cb
}
if (listenOptions.signal) {
if (typeof listenOptions.signal.on !== 'function' && typeof listenOptions.signal.addEventListener !== 'function') {
throw new FST_ERR_LISTEN_OPTIONS_INVALID('Invalid options.signal')
}
if (listenOptions.signal.aborted) {
this.close()
} else {
const onAborted = () => {
this.close()
}
listenOptions.signal.addEventListener('abort', onAborted, { once: true })
}
}
// If we have a path specified, don't default host to 'localhost' so we don't end up listening
// on both path and host
// See https://github.com/fastify/fastify/issues/4007
let host
if (listenOptions.path == null) {
host = listenOptions.host ?? 'localhost'
} else {
host = listenOptions.host
}
if (Object.prototype.hasOwnProperty.call(listenOptions, 'host') === false) {
listenOptions.host = host
}
if (host === 'localhost') {
listenOptions.cb = (err, address) => {
if (err) {
// the server did not start
cb(err, address)
return
}
multipleBindings.call(this, server, httpHandler, options, listenOptions, () => {
this[kState].listening = true
cb(null, address)
onListenHookRunner(this)
})
}
} else {
listenOptions.cb = (err, address) => {
// the server did not start
if (err) {
cb(err, address)
return
}
this[kState].listening = true
cb(null, address)
onListenHookRunner(this)
}
}
// https://github.com/nodejs/node/issues/9390
// If listening to 'localhost', listen to both 127.0.0.1 or ::1 if they are available.
// If listening to 127.0.0.1, only listen to 127.0.0.1.
// If listening to ::1, only listen to ::1.
if (cb === undefined) {
const listening = listenPromise.call(this, server, listenOptions)
/* istanbul ignore else */
return listening.then(address => {
return new Promise((resolve, reject) => {
if (host === 'localhost') {
multipleBindings.call(this, server, httpHandler, options, listenOptions, () => {
this[kState].listening = true
resolve(address)
onListenHookRunner(this)
})
} else {
resolve(address)
onListenHookRunner(this)
}
})
})
}
this.ready(listenCallback.call(this, server, listenOptions))
}
return { server, listen }
}
function multipleBindings (mainServer, httpHandler, serverOpts, listenOptions, onListen) {
// the main server is started, we need to start the secondary servers
this[kState].listening = false
// let's check if we need to bind additional addresses
dns.lookup(listenOptions.host, { all: true }, (dnsErr, addresses) => {
if (dnsErr) {
// not blocking the main server listening
// this.log.warn('dns.lookup error:', dnsErr)
onListen()
return
}
const isMainServerListening = mainServer.listening && serverOpts.serverFactory
let binding = 0
let bound = 0
if (!isMainServerListening) {
const primaryAddress = mainServer.address()
for (const adr of addresses) {
if (adr.address !== primaryAddress.address) {
binding++
const secondaryOpts = Object.assign({}, listenOptions, {
host: adr.address,
port: primaryAddress.port,
cb: (_ignoreErr) => {
bound++
/* istanbul ignore next: the else won't be taken unless listening fails */
if (!_ignoreErr) {
this[kServerBindings].push(secondaryServer)
}
if (bound === binding) {
// regardless of the error, we are done
onListen()
}
}
})
const secondaryServer = getServerInstance(serverOpts, httpHandler)
const closeSecondary = () => {
// To avoid fall into situations where the close of the
// secondary server is triggered before the preClose hook
// is done running, we better wait until the main server
// is closed.
// No new TCP connections are accepted
// We swallow any error from the secondary
// server
secondaryServer.close(() => {})
if (serverOpts.forceCloseConnections === 'idle') {
// Not needed in Node 19
secondaryServer.closeIdleConnections()
} else if (typeof secondaryServer.closeAllConnections === 'function' && serverOpts.forceCloseConnections) {
secondaryServer.closeAllConnections()
}
}
secondaryServer.on('upgrade', mainServer.emit.bind(mainServer, 'upgrade'))
mainServer.on('unref', closeSecondary)
mainServer.on('close', closeSecondary)
mainServer.on('error', closeSecondary)
this[kState].listening = false
listenCallback.call(this, secondaryServer, secondaryOpts)()
}
}
}
// no extra bindings are necessary
if (binding === 0) {
onListen()
return
}
// in test files we are using unref so we need to propagate the unref event
// to the secondary servers. It is valid only when the user is
// listening on localhost
const originUnref = mainServer.unref
/* c8 ignore next 4 */
mainServer.unref = function () {
originUnref.call(mainServer)
mainServer.emit('unref')
}
})
}
function listenCallback (server, listenOptions) {
const wrap = (err) => {
server.removeListener('error', wrap)
if (!err) {
const address = logServerAddress.call(this, server, listenOptions.listenTextResolver || defaultResolveServerListeningText)
listenOptions.cb(null, address)
} else {
this[kState].listening = false
listenOptions.cb(err, null)
}
}
return (err) => {
if (err != null) return listenOptions.cb(err)
if (this[kState].listening && this[kState].closing) {
return listenOptions.cb(new FST_ERR_REOPENED_CLOSE_SERVER(), null)
} else if (this[kState].listening) {
return listenOptions.cb(new FST_ERR_REOPENED_SERVER(), null)
}
server.once('error', wrap)
if (!this[kState].closing) {
server.listen(listenOptions, wrap)
this[kState].listening = true
}
}
}
function listenPromise (server, listenOptions) {
if (this[kState].listening && this[kState].closing) {
return Promise.reject(new FST_ERR_REOPENED_CLOSE_SERVER())
} else if (this[kState].listening) {
return Promise.reject(new FST_ERR_REOPENED_SERVER())
}
return this.ready().then(() => {
let errEventHandler
const errEvent = new Promise((resolve, reject) => {
errEventHandler = (err) => {
this[kState].listening = false
reject(err)
}
server.once('error', errEventHandler)
})
const listen = new Promise((resolve, reject) => {
server.listen(listenOptions, () => {
server.removeListener('error', errEventHandler)
resolve(logServerAddress.call(this, server, listenOptions.listenTextResolver || defaultResolveServerListeningText))
})
// we set it afterwards because listen can throw
this[kState].listening = true
})
return Promise.race([
errEvent, // e.g invalid port range error is always emitted before the server listening
listen
])
})
}
/**
* Creates a function that, based upon initial configuration, will
* verify that every incoming request conforms to allowed
* HTTP versions for the Fastify instance, e.g. a Fastify HTTP/1.1
* server will not serve HTTP/2 requests upon the result of the
* verification function.
*
* @param {object} options fastify option
* @param {function} [options.serverFactory] If present, the
* validator function will skip all checks.
* @param {boolean} [options.http2 = false] If true, the validator
* function will allow HTTP/2 requests.
* @param {object} [options.https = null] https server options
* @param {boolean} [options.https.allowHTTP1] If true and use
* with options.http2 the validator function will allow HTTP/1
* request to http2 server.
*
* @returns {function} HTTP version validator function.
*/
function compileValidateHTTPVersion (options) {
let bypass = false
// key-value map to store valid http version
const map = new Map()
if (options.serverFactory) {
// When serverFactory is passed, we cannot identify how to check http version reliably
// So, we should skip the http version check
bypass = true
}
if (options.http2) {
// HTTP2 must serve HTTP/2.0
map.set('2.0', true)
if (options.https && options.https.allowHTTP1 === true) {
// HTTP2 with HTTPS.allowHTTP1 allow fallback to HTTP/1.1 and HTTP/1.0
map.set('1.1', true)
map.set('1.0', true)
}
} else {
// HTTP must server HTTP/1.1 and HTTP/1.0
map.set('1.1', true)
map.set('1.0', true)
}
// The compiled function here placed in one of the hottest path inside fastify
// the implementation here must be as performant as possible
return function validateHTTPVersion (httpVersion) {
// `bypass` skip the check when custom server factory provided
// `httpVersion in obj` check for the valid http version we should support
return bypass || map.has(httpVersion)
}
}
function getServerInstance (options, httpHandler) {
let server = null
// node@20 do not accepts options as boolean
// we need to provide proper https option
const httpsOptions = options.https === true ? {} : options.https
if (options.serverFactory) {
server = options.serverFactory(httpHandler, options)
} else if (options.http2) {
if (typeof httpsOptions === 'object') {
server = http2().createSecureServer(httpsOptions, httpHandler)
} else {
server = http2().createServer(httpHandler)
}
server.on('session', sessionTimeout(options.http2SessionTimeout))
} else {
// this is http1
if (httpsOptions) {
server = https.createServer(httpsOptions, httpHandler)
} else {
server = http.createServer(options.http, httpHandler)
}
server.keepAliveTimeout = options.keepAliveTimeout
server.requestTimeout = options.requestTimeout
// we treat zero as null
// and null is the default setting from nodejs
// so we do not pass the option to server
if (options.maxRequestsPerSocket > 0) {
server.maxRequestsPerSocket = options.maxRequestsPerSocket
}
}
if (!options.serverFactory) {
server.setTimeout(options.connectionTimeout)
}
return server
}
function normalizeListenArgs (args) {
if (args.length === 0) {
return { port: 0, host: 'localhost' }
}
const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined
const options = { cb }
const firstArg = args[0]
const argsLength = args.length
const lastArg = args[argsLength - 1]
if (typeof firstArg === 'string' && isNaN(firstArg)) {
/* Deal with listen (pipe[, backlog]) */
options.path = firstArg
options.backlog = argsLength > 1 ? lastArg : undefined
} else {
/* Deal with listen ([port[, host[, backlog]]]) */
options.port = argsLength >= 1 && Number.isInteger(firstArg) ? firstArg : normalizePort(firstArg)
// This will listen to what localhost is.
// It can be 127.0.0.1 or ::1, depending on the operating system.
// Fixes https://github.com/fastify/fastify/issues/1022.
options.host = argsLength >= 2 && args[1] ? args[1] : 'localhost'
options.backlog = argsLength >= 3 ? args[2] : undefined
}
return options
}
function normalizePort (firstArg) {
const port = Number(firstArg)
return port >= 0 && !Number.isNaN(port) && Number.isInteger(port) ? port : 0
}
function logServerAddress (server, listenTextResolver) {
let address = server.address()
const isUnixSocket = typeof address === 'string'
/* istanbul ignore next */
if (!isUnixSocket) {
if (address.address.indexOf(':') === -1) {
address = address.address + ':' + address.port
} else {
address = '[' + address.address + ']:' + address.port
}
}
/* istanbul ignore next */
address = (isUnixSocket ? '' : ('http' + (this[kOptions].https ? 's' : '') + '://')) + address
const serverListeningText = listenTextResolver(address)
this.log.info(serverListeningText)
return address
}
function http2 () {
try {
return __nccwpck_require__(42725)
} catch (err) {
throw new FST_ERR_HTTP2_INVALID_VERSION()
}
}
function sessionTimeout (timeout) {
return function (session) {
session.setTimeout(timeout, close)
}
}
function close () {
this.close()
}
/***/ }),
/***/ 28622:
/***/ ((module) => {
"use strict";
const keys = {
kAvvioBoot: Symbol('fastify.avvioBoot'),
kChildren: Symbol('fastify.children'),
kServerBindings: Symbol('fastify.serverBindings'),
kBodyLimit: Symbol('fastify.bodyLimit'),
kRoutePrefix: Symbol('fastify.routePrefix'),
kLogLevel: Symbol('fastify.logLevel'),
kLogSerializers: Symbol('fastify.logSerializers'),
kHooks: Symbol('fastify.hooks'),
kContentTypeParser: Symbol('fastify.contentTypeParser'),
kState: Symbol('fastify.state'),
kOptions: Symbol('fastify.options'),
kDisableRequestLogging: Symbol('fastify.disableRequestLogging'),
kPluginNameChain: Symbol('fastify.pluginNameChain'),
kRouteContext: Symbol('fastify.context'),
kPublicRouteContext: Symbol('fastify.routeOptions'),
kGenReqId: Symbol('fastify.genReqId'),
// Schema
kSchemaController: Symbol('fastify.schemaController'),
kSchemaHeaders: Symbol('headers-schema'),
kSchemaParams: Symbol('params-schema'),
kSchemaQuerystring: Symbol('querystring-schema'),
kSchemaBody: Symbol('body-schema'),
kSchemaResponse: Symbol('response-schema'),
kSchemaErrorFormatter: Symbol('fastify.schemaErrorFormatter'),
kSchemaVisited: Symbol('fastify.schemas.visited'),
// Request
kRequest: Symbol('fastify.Request'),
kRequestPayloadStream: Symbol('fastify.RequestPayloadStream'),
kRequestAcceptVersion: Symbol('fastify.RequestAcceptVersion'),
kRequestCacheValidateFns: Symbol('fastify.request.cache.validateFns'),
kRequestOriginalUrl: Symbol('fastify.request.originalUrl'),
// 404
kFourOhFour: Symbol('fastify.404'),
kCanSetNotFoundHandler: Symbol('fastify.canSetNotFoundHandler'),
kFourOhFourLevelInstance: Symbol('fastify.404LogLevelInstance'),
kFourOhFourContext: Symbol('fastify.404ContextKey'),
kDefaultJsonParse: Symbol('fastify.defaultJSONParse'),
// Reply
kReply: Symbol('fastify.Reply'),
kReplySerializer: Symbol('fastify.reply.serializer'),
kReplyIsError: Symbol('fastify.reply.isError'),
kReplyHeaders: Symbol('fastify.reply.headers'),
kReplyTrailers: Symbol('fastify.reply.trailers'),
kReplyHasStatusCode: Symbol('fastify.reply.hasStatusCode'),
kReplyHijacked: Symbol('fastify.reply.hijacked'),
kReplyStartTime: Symbol('fastify.reply.startTime'),
kReplyNextErrorHandler: Symbol('fastify.reply.nextErrorHandler'),
kReplyEndTime: Symbol('fastify.reply.endTime'),
kReplyErrorHandlerCalled: Symbol('fastify.reply.errorHandlerCalled'),
kReplyIsRunningOnErrorHook: Symbol('fastify.reply.isRunningOnErrorHook'),
kReplySerializerDefault: Symbol('fastify.replySerializerDefault'),
kReplyCacheSerializeFns: Symbol('fastify.reply.cache.serializeFns'),
// This symbol is only meant to be used for fastify tests and should not be used for any other purpose
kTestInternals: Symbol('fastify.testInternals'),
kErrorHandler: Symbol('fastify.errorHandler'),
kChildLoggerFactory: Symbol('fastify.childLoggerFactory'),
kHasBeenDecorated: Symbol('fastify.hasBeenDecorated'),
kKeepAliveConnections: Symbol('fastify.keepAliveConnections'),
kRouteByFastify: Symbol('fastify.routeByFastify')
}
module.exports = keys
/***/ }),
/***/ 78365:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kSchemaHeaders: headersSchema,
kSchemaParams: paramsSchema,
kSchemaQuerystring: querystringSchema,
kSchemaBody: bodySchema,
kSchemaResponse: responseSchema
} = __nccwpck_require__(28622)
const scChecker = /^[1-5]{1}[0-9]{2}$|^[1-5]xx$|^default$/
const {
FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX
} = __nccwpck_require__(89005)
const { FSTWRN001 } = __nccwpck_require__(59283)
function compileSchemasForSerialization (context, compile) {
if (!context.schema || !context.schema.response) {
return
}
const { method, url } = context.config || {}
context[responseSchema] = Object.keys(context.schema.response)
.reduce(function (acc, statusCode) {
const schema = context.schema.response[statusCode]
statusCode = statusCode.toLowerCase()
if (!scChecker.exec(statusCode)) {
throw new FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX()
}
if (schema.content) {
const contentTypesSchemas = {}
for (const mediaName of Object.keys(schema.content)) {
const contentSchema = schema.content[mediaName].schema
contentTypesSchemas[mediaName] = compile({
schema: contentSchema,
url,
method,
httpStatus: statusCode,
contentType: mediaName
})
}
acc[statusCode] = contentTypesSchemas
} else {
acc[statusCode] = compile({
schema,
url,
method,
httpStatus: statusCode
})
}
return acc
}, {})
}
function compileSchemasForValidation (context, compile, isCustom) {
const { schema } = context
if (!schema) {
return
}
const { method, url } = context.config || {}
const headers = schema.headers
// the or part is used for backward compatibility
if (headers && (isCustom || Object.getPrototypeOf(headers) !== Object.prototype)) {
// do not mess with schema when custom validator applied, e.g. Joi, Typebox
context[headersSchema] = compile({ schema: headers, method, url, httpPart: 'headers' })
} else if (headers) {
// The header keys are case insensitive
// https://datatracker.ietf.org/doc/html/rfc2616#section-4.2
const headersSchemaLowerCase = {}
Object.keys(headers).forEach(k => { headersSchemaLowerCase[k] = headers[k] })
if (headersSchemaLowerCase.required instanceof Array) {
headersSchemaLowerCase.required = headersSchemaLowerCase.required.map(h => h.toLowerCase())
}
if (headers.properties) {
headersSchemaLowerCase.properties = {}
Object.keys(headers.properties).forEach(k => {
headersSchemaLowerCase.properties[k.toLowerCase()] = headers.properties[k]
})
}
context[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url, httpPart: 'headers' })
} else if (Object.prototype.hasOwnProperty.call(schema, 'headers')) {
FSTWRN001('headers', method, url)
}
if (schema.body) {
context[bodySchema] = compile({ schema: schema.body, method, url, httpPart: 'body' })
} else if (Object.prototype.hasOwnProperty.call(schema, 'body')) {
FSTWRN001('body', method, url)
}
if (schema.querystring) {
context[querystringSchema] = compile({ schema: schema.querystring, method, url, httpPart: 'querystring' })
} else if (Object.prototype.hasOwnProperty.call(schema, 'querystring')) {
FSTWRN001('querystring', method, url)
}
if (schema.params) {
context[paramsSchema] = compile({ schema: schema.params, method, url, httpPart: 'params' })
} else if (Object.prototype.hasOwnProperty.call(schema, 'params')) {
FSTWRN001('params', method, url)
}
}
function validateParam (validatorFunction, request, paramName) {
const isUndefined = request[paramName] === undefined
const ret = validatorFunction && validatorFunction(isUndefined ? null : request[paramName])
if (ret?.then) {
return ret
.then((res) => { return answer(res) })
.catch(err => { return err }) // return as simple error (not throw)
}
return answer(ret)
function answer (ret) {
if (ret === false) return validatorFunction.errors
if (ret && ret.error) return ret.error
if (ret && ret.value) request[paramName] = ret.value
return false
}
}
function validate (context, request, execution) {
const runExecution = execution === undefined
if (runExecution || !execution.skipParams) {
const params = validateParam(context[paramsSchema], request, 'params')
if (params) {
if (typeof params.then !== 'function') {
return wrapValidationError(params, 'params', context.schemaErrorFormatter)
} else {
return validateAsyncParams(params, context, request)
}
}
}
if (runExecution || !execution.skipBody) {
const body = validateParam(context[bodySchema], request, 'body')
if (body) {
if (typeof body.then !== 'function') {
return wrapValidationError(body, 'body', context.schemaErrorFormatter)
} else {
return validateAsyncBody(body, context, request)
}
}
}
if (runExecution || !execution.skipQuery) {
const query = validateParam(context[querystringSchema], request, 'query')
if (query) {
if (typeof query.then !== 'function') {
return wrapValidationError(query, 'querystring', context.schemaErrorFormatter)
} else {
return validateAsyncQuery(query, context, request)
}
}
}
const headers = validateParam(context[headersSchema], request, 'headers')
if (headers) {
if (typeof headers.then !== 'function') {
return wrapValidationError(headers, 'headers', context.schemaErrorFormatter)
} else {
return validateAsyncHeaders(headers, context, request)
}
}
return false
}
function validateAsyncParams (validatePromise, context, request) {
return validatePromise
.then((paramsResult) => {
if (paramsResult) {
return wrapValidationError(paramsResult, 'params', context.schemaErrorFormatter)
}
return validate(context, request, { skipParams: true })
})
}
function validateAsyncBody (validatePromise, context, request) {
return validatePromise
.then((bodyResult) => {
if (bodyResult) {
return wrapValidationError(bodyResult, 'body', context.schemaErrorFormatter)
}
return validate(context, request, { skipParams: true, skipBody: true })
})
}
function validateAsyncQuery (validatePromise, context, request) {
return validatePromise
.then((queryResult) => {
if (queryResult) {
return wrapValidationError(queryResult, 'querystring', context.schemaErrorFormatter)
}
return validate(context, request, { skipParams: true, skipBody: true, skipQuery: true })
})
}
function validateAsyncHeaders (validatePromise, context, request) {
return validatePromise
.then((headersResult) => {
if (headersResult) {
return wrapValidationError(headersResult, 'headers', context.schemaErrorFormatter)
}
return false
})
}
function wrapValidationError (result, dataVar, schemaErrorFormatter) {
if (result instanceof Error) {
result.statusCode = result.statusCode || 400
result.code = result.code || 'FST_ERR_VALIDATION'
result.validationContext = result.validationContext || dataVar
return result
}
const error = schemaErrorFormatter(result, dataVar)
error.statusCode = error.statusCode || 400
error.code = error.code || 'FST_ERR_VALIDATION'
error.validation = result
error.validationContext = dataVar
return error
}
module.exports = {
symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema },
compileSchemasForValidation,
compileSchemasForSerialization,
validate
}
/***/ }),
/***/ 59283:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { createDeprecation, createWarning } = __nccwpck_require__(2782)
const FSTDEP005 = createDeprecation({
code: 'FSTDEP005',
message: 'You are accessing the deprecated "request.connection" property. Use "request.socket" instead.'
})
const FSTDEP006 = createDeprecation({
code: 'FSTDEP006',
message: 'You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: %s'
})
const FSTDEP007 = createDeprecation({
code: 'FSTDEP007',
message: 'You are trying to set a HEAD route using "exposeHeadRoute" route flag when a sibling route is already set. See documentation for more info.'
})
const FSTDEP008 = createDeprecation({
code: 'FSTDEP008',
message: 'You are using route constraints via the route { version: "..." } option, use { constraints: { version: "..." } } option instead.'
})
const FSTDEP009 = createDeprecation({
code: 'FSTDEP009',
message: 'You are using a custom route versioning strategy via the server { versioning: "..." } option, use { constraints: { version: "..." } } option instead.'
})
const FSTDEP010 = createDeprecation({
code: 'FSTDEP010',
message: 'Modifying the "reply.sent" property is deprecated. Use the "reply.hijack()" method instead.'
})
const FSTDEP011 = createDeprecation({
code: 'FSTDEP011',
message: 'Variadic listen method is deprecated. Please use ".listen(optionsObject)" instead. The variadic signature will be removed in `fastify@5`.'
})
const FSTDEP012 = createDeprecation({
code: 'FSTDEP012',
message: 'request.context property access is deprecated. Please use "request.routeOptions.config" or "request.routeOptions.schema" instead for accessing Route settings. The "request.context" will be removed in `fastify@5`.'
})
const FSTDEP013 = createDeprecation({
code: 'FSTDEP013',
message: 'Direct return of "trailers" function is deprecated. Please use "callback" or "async-await" for return value. The support of direct return will removed in `fastify@5`.'
})
const FSTDEP014 = createDeprecation({
code: 'FSTDEP014',
message: 'You are trying to set/access the default route. This property is deprecated. Please, use setNotFoundHandler if you want to custom a 404 handler or the wildcard (*) to match all routes.'
})
const FSTDEP015 = createDeprecation({
code: 'FSTDEP015',
message: 'You are accessing the deprecated "request.routeSchema" property. Use "request.routeOptions.schema" instead. Property "req.routeSchema" will be removed in `fastify@5`.'
})
const FSTDEP016 = createDeprecation({
code: 'FSTDEP016',
message: 'You are accessing the deprecated "request.routeConfig" property. Use "request.routeOptions.config" instead. Property "req.routeConfig" will be removed in `fastify@5`.'
})
const FSTDEP017 = createDeprecation({
code: 'FSTDEP017',
message: 'You are accessing the deprecated "request.routerPath" property. Use "request.routeOptions.url" instead. Property "req.routerPath" will be removed in `fastify@5`.'
})
const FSTDEP018 = createDeprecation({
code: 'FSTDEP018',
message: 'You are accessing the deprecated "request.routerMethod" property. Use "request.routeOptions.method" instead. Property "req.routerMethod" will be removed in `fastify@5`.'
})
const FSTDEP019 = createDeprecation({
code: 'FSTDEP019',
message: 'reply.context property access is deprecated. Please use "request.routeOptions.config" or "request.routeOptions.schema" instead for accessing Route settings. The "reply.context" will be removed in `fastify@5`.'
})
const FSTDEP020 = createDeprecation({
code: 'FSTDEP020',
message: 'You are using the deprecated "reply.getResponseTime()" method. Use the "reply.elapsedTime" property instead. Method "reply.getResponseTime()" will be removed in `fastify@5`.'
})
const FSTWRN001 = createWarning({
name: 'FastifyWarning',
code: 'FSTWRN001',
message: 'The %s schema for %s: %s is missing. This may indicate the schema is not well specified.',
unlimited: true
})
const FSTWRN002 = createWarning({
name: 'FastifyWarning',
code: 'FSTWRN002',
message: 'The %s plugin being registered mixes async and callback styles, which will result in an error in `fastify@5`',
unlimited: true
})
module.exports = {
FSTDEP005,
FSTDEP006,
FSTDEP007,
FSTDEP008,
FSTDEP009,
FSTDEP010,
FSTDEP011,
FSTDEP012,
FSTDEP013,
FSTDEP014,
FSTDEP015,
FSTDEP016,
FSTDEP017,
FSTDEP018,
FSTDEP019,
FSTDEP020,
FSTWRN001,
FSTWRN002
}
/***/ }),
/***/ 20195:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const {
kReplyIsError,
kReplyHijacked
} = __nccwpck_require__(28622)
function wrapThenable (thenable, reply) {
thenable.then(function (payload) {
if (reply[kReplyHijacked] === true) {
return
}
// this is for async functions that are using reply.send directly
//
// since wrap-thenable will be called when using reply.send directly
// without actual return. the response can be sent already or
// the request may be terminated during the reply. in this situation,
// it require an extra checking of request.aborted to see whether
// the request is killed by client.
if (payload !== undefined || (reply.sent === false && reply.raw.headersSent === false && reply.request.raw.aborted === false)) {
// we use a try-catch internally to avoid adding a catch to another
// promise, increase promise perf by 10%
try {
reply.send(payload)
} catch (err) {
reply[kReplyIsError] = true
reply.send(err)
}
}
}, function (err) {
if (reply.sent === true) {
reply.log.error({ err }, 'Promise errored, but reply.sent = true was set')
return
}
reply[kReplyIsError] = true
// try-catch allow to re-throw error in error handler for async handler
try {
reply.send(err)
// The following should not happen
/* c8 ignore next 3 */
} catch (err) {
reply.send(err)
}
})
}
module.exports = wrapThenable
/***/ }),
/***/ 62438:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const assert = __nccwpck_require__(98061)
const Request = __nccwpck_require__(1664)
const Response = __nccwpck_require__(55991)
const errorMessage = 'The dispatch function has already been invoked'
const optsValidator = __nccwpck_require__(16547)
function inject (dispatchFunc, options, callback) {
if (callback === undefined) {
return new Chain(dispatchFunc, options)
} else {
return doInject(dispatchFunc, options, callback)
}
}
function makeRequest (dispatchFunc, server, req, res) {
req.once('error', function (err) {
if (this.destroyed) res.destroy(err)
})
req.once('close', function () {
if (this.destroyed && !this._error) res.destroy()
})
return req.prepare(() => dispatchFunc.call(server, req, res))
}
function doInject (dispatchFunc, options, callback) {
options = (typeof options === 'string' ? { url: options } : options)
if (options.validate !== false) {
assert(typeof dispatchFunc === 'function', 'dispatchFunc should be a function')
const isOptionValid = optsValidator(options)
if (!isOptionValid) {
throw new Error(optsValidator.errors.map(e => e.message))
}
}
const server = options.server || {}
const RequestConstructor = options.Request
? Request.CustomRequest
: Request
// Express.js detection
if (dispatchFunc.request && dispatchFunc.request.app === dispatchFunc) {
Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.request), RequestConstructor.prototype)
Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.response), Response.prototype)
}
if (typeof callback === 'function') {
const req = new RequestConstructor(options)
const res = new Response(req, callback)
return makeRequest(dispatchFunc, server, req, res)
} else {
return new Promise((resolve, reject) => {
const req = new RequestConstructor(options)
const res = new Response(req, resolve, reject)
makeRequest(dispatchFunc, server, req, res)
})
}
}
function Chain (dispatch, option) {
if (typeof option === 'string') {
this.option = { url: option }
} else {
this.option = Object.assign({}, option)
}
this.dispatch = dispatch
this._hasInvoked = false
this._promise = null
if (this.option.autoStart !== false) {
process.nextTick(() => {
if (!this._hasInvoked) {
this.end()
}
})
}
}
const httpMethods = [
'delete',
'get',
'head',
'options',
'patch',
'post',
'put',
'trace'
]
httpMethods.forEach(method => {
Chain.prototype[method] = function (url) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this.option.url = url
this.option.method = method.toUpperCase()
return this
}
})
const chainMethods = [
'body',
'cookies',
'headers',
'payload',
'query'
]
chainMethods.forEach(method => {
Chain.prototype[method] = function (value) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this.option[method] = value
return this
}
})
Chain.prototype.end = function (callback) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this._hasInvoked = true
if (typeof callback === 'function') {
doInject(this.dispatch, this.option, callback)
} else {
this._promise = doInject(this.dispatch, this.option)
return this._promise
}
}
Object.getOwnPropertyNames(Promise.prototype).forEach(method => {
if (method === 'constructor') return
Chain.prototype[method] = function (...args) {
if (!this._promise) {
if (this._hasInvoked === true) {
throw new Error(errorMessage)
}
this._hasInvoked = true
this._promise = doInject(this.dispatch, this.option)
}
return this._promise[method](...args)
}
})
function isInjection (obj) {
return (
obj instanceof Request ||
obj instanceof Response ||
(obj && obj.constructor && obj.constructor.name === '_CustomLMRRequest')
)
}
module.exports = inject
module.exports["default"] = inject
module.exports.inject = inject
module.exports.isInjection = isInjection
/***/ }),
/***/ 16547:
/***/ ((module) => {
"use strict";
// This file is autogenerated by build/build-validation.js, do not edit
/* istanbul ignore file */
/* eslint-disable */
module.exports = validate10;
module.exports["default"] = validate10;
const schema11 = {"type":"object","properties":{"url":{"oneOf":[{"type":"string"},{"type":"object","properties":{"protocol":{"type":"string"},"hostname":{"type":"string"},"pathname":{"type":"string"}},"additionalProperties":true,"required":["pathname"]}]},"path":{"oneOf":[{"type":"string"},{"type":"object","properties":{"protocol":{"type":"string"},"hostname":{"type":"string"},"pathname":{"type":"string"}},"additionalProperties":true,"required":["pathname"]}]},"cookies":{"type":"object","additionalProperties":true},"headers":{"type":"object","additionalProperties":true},"query":{"anyOf":[{"type":"object","additionalProperties":true},{"type":"string"}]},"simulate":{"type":"object","properties":{"end":{"type":"boolean"},"split":{"type":"boolean"},"error":{"type":"boolean"},"close":{"type":"boolean"}}},"authority":{"type":"string"},"remoteAddress":{"type":"string"},"method":{"type":"string","enum":["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE","acl","bind","checkout","connect","copy","delete","get","head","link","lock","m-search","merge","mkactivity","mkcalendar","mkcol","move","notify","options","patch","post","propfind","proppatch","purge","put","rebind","report","search","source","subscribe","trace","unbind","unlink","unlock","unsubscribe"]},"validate":{"type":"boolean"}},"additionalProperties":true,"oneOf":[{"required":["url"]},{"required":["path"]}]};
function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
let vErrors = null;
let errors = 0;
const _errs1 = errors;
let valid0 = false;
let passing0 = null;
const _errs2 = errors;
if(data && typeof data == "object" && !Array.isArray(data)){
let missing0;
if((data.url === undefined) && (missing0 = "url")){
const err0 = {instancePath,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"};
if(vErrors === null){
vErrors = [err0];
}
else {
vErrors.push(err0);
}
errors++;
}
}
var _valid0 = _errs2 === errors;
if(_valid0){
valid0 = true;
passing0 = 0;
}
const _errs3 = errors;
if(data && typeof data == "object" && !Array.isArray(data)){
let missing1;
if((data.path === undefined) && (missing1 = "path")){
const err1 = {instancePath,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"};
if(vErrors === null){
vErrors = [err1];
}
else {
vErrors.push(err1);
}
errors++;
}
}
var _valid0 = _errs3 === errors;
if(_valid0 && valid0){
valid0 = false;
passing0 = [passing0, 1];
}
else {
if(_valid0){
valid0 = true;
passing0 = 1;
}
}
if(!valid0){
const err2 = {instancePath,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas: passing0},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err2];
}
else {
vErrors.push(err2);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs1;
if(vErrors !== null){
if(_errs1){
vErrors.length = _errs1;
}
else {
vErrors = null;
}
}
}
if(errors === 0){
if(data && typeof data == "object" && !Array.isArray(data)){
if(data.url !== undefined){
let data0 = data.url;
const _errs5 = errors;
const _errs6 = errors;
let valid2 = false;
let passing1 = null;
const _errs7 = errors;
if(typeof data0 !== "string"){
let dataType0 = typeof data0;
let coerced0 = undefined;
if(!(coerced0 !== undefined)){
if(dataType0 == "number" || dataType0 == "boolean"){
coerced0 = "" + data0;
}
else if(data0 === null){
coerced0 = "";
}
else {
const err3 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err3];
}
else {
vErrors.push(err3);
}
errors++;
}
}
if(coerced0 !== undefined){
data0 = coerced0;
if(data !== undefined){
data["url"] = coerced0;
}
}
}
var _valid1 = _errs7 === errors;
if(_valid1){
valid2 = true;
passing1 = 0;
}
const _errs9 = errors;
if(errors === _errs9){
if(data0 && typeof data0 == "object" && !Array.isArray(data0)){
let missing2;
if((data0.pathname === undefined) && (missing2 = "pathname")){
const err4 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/1/required",keyword:"required",params:{missingProperty: missing2},message:"must have required property '"+missing2+"'"};
if(vErrors === null){
vErrors = [err4];
}
else {
vErrors.push(err4);
}
errors++;
}
else {
if(data0.protocol !== undefined){
let data1 = data0.protocol;
const _errs12 = errors;
if(typeof data1 !== "string"){
let dataType1 = typeof data1;
let coerced1 = undefined;
if(!(coerced1 !== undefined)){
if(dataType1 == "number" || dataType1 == "boolean"){
coerced1 = "" + data1;
}
else if(data1 === null){
coerced1 = "";
}
else {
const err5 = {instancePath:instancePath+"/url/protocol",schemaPath:"#/properties/url/oneOf/1/properties/protocol/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err5];
}
else {
vErrors.push(err5);
}
errors++;
}
}
if(coerced1 !== undefined){
data1 = coerced1;
if(data0 !== undefined){
data0["protocol"] = coerced1;
}
}
}
var valid3 = _errs12 === errors;
}
else {
var valid3 = true;
}
if(valid3){
if(data0.hostname !== undefined){
let data2 = data0.hostname;
const _errs14 = errors;
if(typeof data2 !== "string"){
let dataType2 = typeof data2;
let coerced2 = undefined;
if(!(coerced2 !== undefined)){
if(dataType2 == "number" || dataType2 == "boolean"){
coerced2 = "" + data2;
}
else if(data2 === null){
coerced2 = "";
}
else {
const err6 = {instancePath:instancePath+"/url/hostname",schemaPath:"#/properties/url/oneOf/1/properties/hostname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err6];
}
else {
vErrors.push(err6);
}
errors++;
}
}
if(coerced2 !== undefined){
data2 = coerced2;
if(data0 !== undefined){
data0["hostname"] = coerced2;
}
}
}
var valid3 = _errs14 === errors;
}
else {
var valid3 = true;
}
if(valid3){
if(data0.pathname !== undefined){
let data3 = data0.pathname;
const _errs16 = errors;
if(typeof data3 !== "string"){
let dataType3 = typeof data3;
let coerced3 = undefined;
if(!(coerced3 !== undefined)){
if(dataType3 == "number" || dataType3 == "boolean"){
coerced3 = "" + data3;
}
else if(data3 === null){
coerced3 = "";
}
else {
const err7 = {instancePath:instancePath+"/url/pathname",schemaPath:"#/properties/url/oneOf/1/properties/pathname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err7];
}
else {
vErrors.push(err7);
}
errors++;
}
}
if(coerced3 !== undefined){
data3 = coerced3;
if(data0 !== undefined){
data0["pathname"] = coerced3;
}
}
}
var valid3 = _errs16 === errors;
}
else {
var valid3 = true;
}
}
}
}
}
else {
const err8 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/1/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err8];
}
else {
vErrors.push(err8);
}
errors++;
}
}
var _valid1 = _errs9 === errors;
if(_valid1 && valid2){
valid2 = false;
passing1 = [passing1, 1];
}
else {
if(_valid1){
valid2 = true;
passing1 = 1;
}
}
if(!valid2){
const err9 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf",keyword:"oneOf",params:{passingSchemas: passing1},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err9];
}
else {
vErrors.push(err9);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs6;
if(vErrors !== null){
if(_errs6){
vErrors.length = _errs6;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs5 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.path !== undefined){
let data4 = data.path;
const _errs18 = errors;
const _errs19 = errors;
let valid4 = false;
let passing2 = null;
const _errs20 = errors;
if(typeof data4 !== "string"){
let dataType4 = typeof data4;
let coerced4 = undefined;
if(!(coerced4 !== undefined)){
if(dataType4 == "number" || dataType4 == "boolean"){
coerced4 = "" + data4;
}
else if(data4 === null){
coerced4 = "";
}
else {
const err10 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err10];
}
else {
vErrors.push(err10);
}
errors++;
}
}
if(coerced4 !== undefined){
data4 = coerced4;
if(data !== undefined){
data["path"] = coerced4;
}
}
}
var _valid2 = _errs20 === errors;
if(_valid2){
valid4 = true;
passing2 = 0;
}
const _errs22 = errors;
if(errors === _errs22){
if(data4 && typeof data4 == "object" && !Array.isArray(data4)){
let missing3;
if((data4.pathname === undefined) && (missing3 = "pathname")){
const err11 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/1/required",keyword:"required",params:{missingProperty: missing3},message:"must have required property '"+missing3+"'"};
if(vErrors === null){
vErrors = [err11];
}
else {
vErrors.push(err11);
}
errors++;
}
else {
if(data4.protocol !== undefined){
let data5 = data4.protocol;
const _errs25 = errors;
if(typeof data5 !== "string"){
let dataType5 = typeof data5;
let coerced5 = undefined;
if(!(coerced5 !== undefined)){
if(dataType5 == "number" || dataType5 == "boolean"){
coerced5 = "" + data5;
}
else if(data5 === null){
coerced5 = "";
}
else {
const err12 = {instancePath:instancePath+"/path/protocol",schemaPath:"#/properties/path/oneOf/1/properties/protocol/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err12];
}
else {
vErrors.push(err12);
}
errors++;
}
}
if(coerced5 !== undefined){
data5 = coerced5;
if(data4 !== undefined){
data4["protocol"] = coerced5;
}
}
}
var valid5 = _errs25 === errors;
}
else {
var valid5 = true;
}
if(valid5){
if(data4.hostname !== undefined){
let data6 = data4.hostname;
const _errs27 = errors;
if(typeof data6 !== "string"){
let dataType6 = typeof data6;
let coerced6 = undefined;
if(!(coerced6 !== undefined)){
if(dataType6 == "number" || dataType6 == "boolean"){
coerced6 = "" + data6;
}
else if(data6 === null){
coerced6 = "";
}
else {
const err13 = {instancePath:instancePath+"/path/hostname",schemaPath:"#/properties/path/oneOf/1/properties/hostname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err13];
}
else {
vErrors.push(err13);
}
errors++;
}
}
if(coerced6 !== undefined){
data6 = coerced6;
if(data4 !== undefined){
data4["hostname"] = coerced6;
}
}
}
var valid5 = _errs27 === errors;
}
else {
var valid5 = true;
}
if(valid5){
if(data4.pathname !== undefined){
let data7 = data4.pathname;
const _errs29 = errors;
if(typeof data7 !== "string"){
let dataType7 = typeof data7;
let coerced7 = undefined;
if(!(coerced7 !== undefined)){
if(dataType7 == "number" || dataType7 == "boolean"){
coerced7 = "" + data7;
}
else if(data7 === null){
coerced7 = "";
}
else {
const err14 = {instancePath:instancePath+"/path/pathname",schemaPath:"#/properties/path/oneOf/1/properties/pathname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err14];
}
else {
vErrors.push(err14);
}
errors++;
}
}
if(coerced7 !== undefined){
data7 = coerced7;
if(data4 !== undefined){
data4["pathname"] = coerced7;
}
}
}
var valid5 = _errs29 === errors;
}
else {
var valid5 = true;
}
}
}
}
}
else {
const err15 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/1/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err15];
}
else {
vErrors.push(err15);
}
errors++;
}
}
var _valid2 = _errs22 === errors;
if(_valid2 && valid4){
valid4 = false;
passing2 = [passing2, 1];
}
else {
if(_valid2){
valid4 = true;
passing2 = 1;
}
}
if(!valid4){
const err16 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf",keyword:"oneOf",params:{passingSchemas: passing2},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err16];
}
else {
vErrors.push(err16);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs19;
if(vErrors !== null){
if(_errs19){
vErrors.length = _errs19;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs18 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.cookies !== undefined){
let data8 = data.cookies;
const _errs31 = errors;
if(errors === _errs31){
if(!(data8 && typeof data8 == "object" && !Array.isArray(data8))){
validate10.errors = [{instancePath:instancePath+"/cookies",schemaPath:"#/properties/cookies/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs31 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.headers !== undefined){
let data9 = data.headers;
const _errs34 = errors;
if(errors === _errs34){
if(!(data9 && typeof data9 == "object" && !Array.isArray(data9))){
validate10.errors = [{instancePath:instancePath+"/headers",schemaPath:"#/properties/headers/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs34 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.query !== undefined){
let data10 = data.query;
const _errs37 = errors;
const _errs38 = errors;
let valid6 = false;
const _errs39 = errors;
if(errors === _errs39){
if(!(data10 && typeof data10 == "object" && !Array.isArray(data10))){
const err17 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf/0/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err17];
}
else {
vErrors.push(err17);
}
errors++;
}
}
var _valid3 = _errs39 === errors;
valid6 = valid6 || _valid3;
if(!valid6){
const _errs42 = errors;
if(typeof data10 !== "string"){
let dataType8 = typeof data10;
let coerced8 = undefined;
if(!(coerced8 !== undefined)){
if(dataType8 == "number" || dataType8 == "boolean"){
coerced8 = "" + data10;
}
else if(data10 === null){
coerced8 = "";
}
else {
const err18 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf/1/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err18];
}
else {
vErrors.push(err18);
}
errors++;
}
}
if(coerced8 !== undefined){
data10 = coerced8;
if(data !== undefined){
data["query"] = coerced8;
}
}
}
var _valid3 = _errs42 === errors;
valid6 = valid6 || _valid3;
}
if(!valid6){
const err19 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err19];
}
else {
vErrors.push(err19);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs38;
if(vErrors !== null){
if(_errs38){
vErrors.length = _errs38;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs37 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.simulate !== undefined){
let data11 = data.simulate;
const _errs44 = errors;
if(errors === _errs44){
if(data11 && typeof data11 == "object" && !Array.isArray(data11)){
if(data11.end !== undefined){
let data12 = data11.end;
const _errs46 = errors;
if(typeof data12 !== "boolean"){
let coerced9 = undefined;
if(!(coerced9 !== undefined)){
if(data12 === "false" || data12 === 0 || data12 === null){
coerced9 = false;
}
else if(data12 === "true" || data12 === 1){
coerced9 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/end",schemaPath:"#/properties/simulate/properties/end/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced9 !== undefined){
data12 = coerced9;
if(data11 !== undefined){
data11["end"] = coerced9;
}
}
}
var valid7 = _errs46 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.split !== undefined){
let data13 = data11.split;
const _errs48 = errors;
if(typeof data13 !== "boolean"){
let coerced10 = undefined;
if(!(coerced10 !== undefined)){
if(data13 === "false" || data13 === 0 || data13 === null){
coerced10 = false;
}
else if(data13 === "true" || data13 === 1){
coerced10 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/split",schemaPath:"#/properties/simulate/properties/split/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced10 !== undefined){
data13 = coerced10;
if(data11 !== undefined){
data11["split"] = coerced10;
}
}
}
var valid7 = _errs48 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.error !== undefined){
let data14 = data11.error;
const _errs50 = errors;
if(typeof data14 !== "boolean"){
let coerced11 = undefined;
if(!(coerced11 !== undefined)){
if(data14 === "false" || data14 === 0 || data14 === null){
coerced11 = false;
}
else if(data14 === "true" || data14 === 1){
coerced11 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/error",schemaPath:"#/properties/simulate/properties/error/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced11 !== undefined){
data14 = coerced11;
if(data11 !== undefined){
data11["error"] = coerced11;
}
}
}
var valid7 = _errs50 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.close !== undefined){
let data15 = data11.close;
const _errs52 = errors;
if(typeof data15 !== "boolean"){
let coerced12 = undefined;
if(!(coerced12 !== undefined)){
if(data15 === "false" || data15 === 0 || data15 === null){
coerced12 = false;
}
else if(data15 === "true" || data15 === 1){
coerced12 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/close",schemaPath:"#/properties/simulate/properties/close/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced12 !== undefined){
data15 = coerced12;
if(data11 !== undefined){
data11["close"] = coerced12;
}
}
}
var valid7 = _errs52 === errors;
}
else {
var valid7 = true;
}
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate",schemaPath:"#/properties/simulate/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs44 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.authority !== undefined){
let data16 = data.authority;
const _errs54 = errors;
if(typeof data16 !== "string"){
let dataType13 = typeof data16;
let coerced13 = undefined;
if(!(coerced13 !== undefined)){
if(dataType13 == "number" || dataType13 == "boolean"){
coerced13 = "" + data16;
}
else if(data16 === null){
coerced13 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/authority",schemaPath:"#/properties/authority/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced13 !== undefined){
data16 = coerced13;
if(data !== undefined){
data["authority"] = coerced13;
}
}
}
var valid1 = _errs54 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.remoteAddress !== undefined){
let data17 = data.remoteAddress;
const _errs56 = errors;
if(typeof data17 !== "string"){
let dataType14 = typeof data17;
let coerced14 = undefined;
if(!(coerced14 !== undefined)){
if(dataType14 == "number" || dataType14 == "boolean"){
coerced14 = "" + data17;
}
else if(data17 === null){
coerced14 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/remoteAddress",schemaPath:"#/properties/remoteAddress/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced14 !== undefined){
data17 = coerced14;
if(data !== undefined){
data["remoteAddress"] = coerced14;
}
}
}
var valid1 = _errs56 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.method !== undefined){
let data18 = data.method;
const _errs58 = errors;
if(typeof data18 !== "string"){
let dataType15 = typeof data18;
let coerced15 = undefined;
if(!(coerced15 !== undefined)){
if(dataType15 == "number" || dataType15 == "boolean"){
coerced15 = "" + data18;
}
else if(data18 === null){
coerced15 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/method",schemaPath:"#/properties/method/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced15 !== undefined){
data18 = coerced15;
if(data !== undefined){
data["method"] = coerced15;
}
}
}
if(!((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((data18 === "ACL") || (data18 === "BIND")) || (data18 === "CHECKOUT")) || (data18 === "CONNECT")) || (data18 === "COPY")) || (data18 === "DELETE")) || (data18 === "GET")) || (data18 === "HEAD")) || (data18 === "LINK")) || (data18 === "LOCK")) || (data18 === "M-SEARCH")) || (data18 === "MERGE")) || (data18 === "MKACTIVITY")) || (data18 === "MKCALENDAR")) || (data18 === "MKCOL")) || (data18 === "MOVE")) || (data18 === "NOTIFY")) || (data18 === "OPTIONS")) || (data18 === "PATCH")) || (data18 === "POST")) || (data18 === "PROPFIND")) || (data18 === "PROPPATCH")) || (data18 === "PURGE")) || (data18 === "PUT")) || (data18 === "REBIND")) || (data18 === "REPORT")) || (data18 === "SEARCH")) || (data18 === "SOURCE")) || (data18 === "SUBSCRIBE")) || (data18 === "TRACE")) || (data18 === "UNBIND")) || (data18 === "UNLINK")) || (data18 === "UNLOCK")) || (data18 === "UNSUBSCRIBE")) || (data18 === "acl")) || (data18 === "bind")) || (data18 === "checkout")) || (data18 === "connect")) || (data18 === "copy")) || (data18 === "delete")) || (data18 === "get")) || (data18 === "head")) || (data18 === "link")) || (data18 === "lock")) || (data18 === "m-search")) || (data18 === "merge")) || (data18 === "mkactivity")) || (data18 === "mkcalendar")) || (data18 === "mkcol")) || (data18 === "move")) || (data18 === "notify")) || (data18 === "options")) || (data18 === "patch")) || (data18 === "post")) || (data18 === "propfind")) || (data18 === "proppatch")) || (data18 === "purge")) || (data18 === "put")) || (data18 === "rebind")) || (data18 === "report")) || (data18 === "search")) || (data18 === "source")) || (data18 === "subscribe")) || (data18 === "trace")) || (data18 === "unbind")) || (data18 === "unlink")) || (data18 === "unlock")) || (data18 === "unsubscribe"))){
validate10.errors = [{instancePath:instancePath+"/method",schemaPath:"#/properties/method/enum",keyword:"enum",params:{allowedValues: schema11.properties.method.enum},message:"must be equal to one of the allowed values"}];
return false;
}
var valid1 = _errs58 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.validate !== undefined){
let data19 = data.validate;
const _errs60 = errors;
if(typeof data19 !== "boolean"){
let coerced16 = undefined;
if(!(coerced16 !== undefined)){
if(data19 === "false" || data19 === 0 || data19 === null){
coerced16 = false;
}
else if(data19 === "true" || data19 === 1){
coerced16 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/validate",schemaPath:"#/properties/validate/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced16 !== undefined){
data19 = coerced16;
if(data !== undefined){
data["validate"] = coerced16;
}
}
}
var valid1 = _errs60 === errors;
}
else {
var valid1 = true;
}
}
}
}
}
}
}
}
}
}
}
else {
validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
validate10.errors = vErrors;
return errors === 0;
}
/***/ }),
/***/ 7333:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { randomUUID } = __nccwpck_require__(6005)
const { Readable } = __nccwpck_require__(84492)
let textEncoder
function isFormDataLike (payload) {
return (
payload &&
typeof payload === 'object' &&
typeof payload.append === 'function' &&
typeof payload.delete === 'function' &&
typeof payload.get === 'function' &&
typeof payload.getAll === 'function' &&
typeof payload.has === 'function' &&
typeof payload.set === 'function' &&
payload[Symbol.toStringTag] === 'FormData'
)
}
/*
partial code extraction and refactoring of `undici`.
MIT License. https://github.com/nodejs/undici/blob/043d8f1a89f606b1db259fc71f4c9bc8eb2aa1e6/lib/web/fetch/LICENSE
Reference https://github.com/nodejs/undici/blob/043d8f1a89f606b1db259fc71f4c9bc8eb2aa1e6/lib/web/fetch/body.js#L102-L168
*/
function formDataToStream (formdata) {
// lazy creation of TextEncoder
textEncoder = textEncoder ?? new TextEncoder()
// we expect the function argument must be FormData
const boundary = `----formdata-${randomUUID()}`
const prefix = `--${boundary}\r\nContent-Disposition: form-data`
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
const escape = (str) =>
str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
const linebreak = new Uint8Array([13, 10]) // '\r\n'
async function * asyncIterator () {
for (const [name, value] of formdata) {
if (typeof value === 'string') {
// header
yield textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"\r\n\r\n`)
// body
yield textEncoder.encode(`${normalizeLinefeeds(value)}\r\n`)
} else {
let header = `${prefix}; name="${escape(normalizeLinefeeds(name))}"`
value.name && (header += `; filename="${escape(value.name)}"`)
header += `\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`
// header
yield textEncoder.encode(header)
// body
/* istanbul ignore else */
if (value.stream) {
yield * value.stream()
} else {
// shouldn't be here since Blob / File should provide .stream
// and FormData always convert to USVString
/* istanbul ignore next */
yield value
}
yield linebreak
}
}
// end
yield textEncoder.encode(`--${boundary}--`)
}
const stream = Readable.from(asyncIterator())
return {
stream,
contentType: `multipart/form-data; boundary=${boundary}`
}
}
module.exports.isFormDataLike = isFormDataLike
module.exports.formDataToStream = formDataToStream
/***/ }),
/***/ 93274:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { URL } = __nccwpck_require__(41041)
const BASE_URL = 'http://localhost'
/**
* Parse URL
*
* @param {(Object|String)} url
* @param {Object} [query]
* @return {URL}
*/
module.exports = function parseURL (url, query) {
if ((typeof url === 'string' || Object.prototype.toString.call(url) === '[object String]') && url.startsWith('//')) {
url = BASE_URL + url
}
const result = typeof url === 'object'
? Object.assign(new URL(BASE_URL), url)
: new URL(url, BASE_URL)
if (typeof query === 'string') {
query = new URLSearchParams(query)
for (const key of query.keys()) {
result.searchParams.delete(key)
for (const value of query.getAll(key)) {
result.searchParams.append(key, value)
}
}
} else {
const merged = Object.assign({}, url.query, query)
for (const key in merged) {
const value = merged[key]
if (Array.isArray(value)) {
result.searchParams.delete(key)
for (const param of value) {
result.searchParams.append(key, param)
}
} else {
result.searchParams.set(key, value)
}
}
}
return result
}
/***/ }),
/***/ 1664:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const { Readable, addAbortSignal } = __nccwpck_require__(84492)
const util = __nccwpck_require__(47261)
const cookie = __nccwpck_require__(93658)
const assert = __nccwpck_require__(98061)
const { createDeprecation } = __nccwpck_require__(2782)
const parseURL = __nccwpck_require__(93274)
const { isFormDataLike, formDataToStream } = __nccwpck_require__(7333)
const { EventEmitter } = __nccwpck_require__(15673)
// request.connectin deprecation https://nodejs.org/api/http.html#http_request_connection
const FST_LIGHTMYREQUEST_DEP01 = createDeprecation({ name: 'FastifyDeprecationLightMyRequest', code: 'FST_LIGHTMYREQUEST_DEP01', message: 'You are accessing "request.connection", use "request.socket" instead.' })
/**
* Get hostname:port
*
* @param {URL} parsedURL
* @return {String}
*/
function hostHeaderFromURL (parsedURL) {
return parsedURL.port
? parsedURL.host
: parsedURL.hostname + (parsedURL.protocol === 'https:' ? ':443' : ':80')
}
/**
* Mock socket object used to fake access to a socket for a request
*
* @constructor
* @param {String} remoteAddress the fake address to show consumers of the socket
*/
class MockSocket extends EventEmitter {
constructor (remoteAddress) {
super()
this.remoteAddress = remoteAddress
}
}
/**
* CustomRequest
*
* @constructor
* @param {Object} options
* @param {(Object|String)} options.url || options.path
* @param {String} [options.method='GET']
* @param {String} [options.remoteAddress]
* @param {Object} [options.cookies]
* @param {Object} [options.headers]
* @param {Object} [options.query]
* @param {Object} [options.Request]
* @param {any} [options.payload]
*/
function CustomRequest (options) {
return new _CustomLMRRequest(this)
function _CustomLMRRequest (obj) {
Request.call(obj, {
...options,
Request: undefined
})
Object.assign(this, obj)
for (const fn of Object.keys(Request.prototype)) {
this.constructor.prototype[fn] = Request.prototype[fn]
}
util.inherits(this.constructor, options.Request)
return this
}
}
/**
* Request
*
* @constructor
* @param {Object} options
* @param {(Object|String)} options.url || options.path
* @param {String} [options.method='GET']
* @param {String} [options.remoteAddress]
* @param {Object} [options.cookies]
* @param {Object} [options.headers]
* @param {Object} [options.query]
* @param {any} [options.payload]
*/
function Request (options) {
Readable.call(this, {
autoDestroy: false
})
const parsedURL = parseURL(options.url || options.path, options.query)
this.url = parsedURL.pathname + parsedURL.search
this.aborted = false
this.httpVersionMajor = 1
this.httpVersionMinor = 1
this.httpVersion = '1.1'
this.method = options.method ? options.method.toUpperCase() : 'GET'
this.headers = {}
this.rawHeaders = []
const headers = options.headers || {}
for (const field in headers) {
const fieldLowerCase = field.toLowerCase()
if (
(
fieldLowerCase === 'user-agent' ||
fieldLowerCase === 'content-type'
) && headers[field] === undefined
) {
this.headers[fieldLowerCase] = undefined
continue
}
const value = headers[field]
assert(value !== undefined, 'invalid value "undefined" for header ' + field)
this.headers[fieldLowerCase] = '' + value
}
if (('user-agent' in this.headers) === false) {
this.headers['user-agent'] = 'lightMyRequest'
}
this.headers.host = this.headers.host || options.authority || hostHeaderFromURL(parsedURL)
if (options.cookies) {
const { cookies } = options
const cookieValues = Object.keys(cookies).map(key => cookie.serialize(key, cookies[key]))
if (this.headers.cookie) {
cookieValues.unshift(this.headers.cookie)
}
this.headers.cookie = cookieValues.join('; ')
}
this.socket = new MockSocket(options.remoteAddress || '127.0.0.1')
Object.defineProperty(this, 'connection', {
get () {
FST_LIGHTMYREQUEST_DEP01()
return this.socket
},
configurable: true
})
// we keep both payload and body for compatibility reasons
let payload = options.payload || options.body || null
let payloadResume = payload && typeof payload.resume === 'function'
if (isFormDataLike(payload)) {
const stream = formDataToStream(payload)
payload = stream.stream
payloadResume = true
// we override the content-type
this.headers['content-type'] = stream.contentType
}
if (payload && typeof payload !== 'string' && !payloadResume && !Buffer.isBuffer(payload)) {
payload = JSON.stringify(payload)
if (('content-type' in this.headers) === false) {
this.headers['content-type'] = 'application/json'
}
}
// Set the content-length for the corresponding payload if none set
if (payload && !payloadResume && !Object.prototype.hasOwnProperty.call(this.headers, 'content-length')) {
this.headers['content-length'] = (Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(payload)).toString()
}
for (const header of Object.keys(this.headers)) {
this.rawHeaders.push(header, this.headers[header])
}
// Use _lightMyRequest namespace to avoid collision with Node
this._lightMyRequest = {
payload,
isDone: false,
simulate: options.simulate || {}
}
const signal = options.signal
/* istanbul ignore if */
if (signal) {
addAbortSignal(signal, this)
}
return this
}
util.inherits(Request, Readable)
util.inherits(CustomRequest, Request)
Request.prototype.prepare = function (next) {
const payload = this._lightMyRequest.payload
if (!payload || typeof payload.resume !== 'function') { // does not quack like a stream
return next()
}
const chunks = []
payload.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
payload.on('end', () => {
const payload = Buffer.concat(chunks)
this.headers['content-length'] = this.headers['content-length'] || ('' + payload.length)
this._lightMyRequest.payload = payload
return next()
})
// Force to resume the stream. Needed for Stream 1
payload.resume()
}
Request.prototype._read = function (size) {
setImmediate(() => {
if (this._lightMyRequest.isDone) {
// 'end' defaults to true
if (this._lightMyRequest.simulate.end !== false) {
this.push(null)
}
return
}
this._lightMyRequest.isDone = true
if (this._lightMyRequest.payload) {
if (this._lightMyRequest.simulate.split) {
this.push(this._lightMyRequest.payload.slice(0, 1))
this.push(this._lightMyRequest.payload.slice(1))
} else {
this.push(this._lightMyRequest.payload)
}
}
if (this._lightMyRequest.simulate.error) {
this.emit('error', new Error('Simulated'))
}
if (this._lightMyRequest.simulate.close) {
this.emit('close')
}
// 'end' defaults to true
if (this._lightMyRequest.simulate.end !== false) {
this.push(null)
}
})
}
Request.prototype.destroy = function (error) {
if (this.destroyed || this._lightMyRequest.isDone) return
this.destroyed = true
if (error) {
this._error = true
process.nextTick(() => this.emit('error', error))
}
process.nextTick(() => this.emit('close'))
}
module.exports = Request
module.exports.Request = Request
module.exports.CustomRequest = CustomRequest
/***/ }),
/***/ 55991:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const http = __nccwpck_require__(88849)
const { Writable, Readable } = __nccwpck_require__(84492)
const util = __nccwpck_require__(47261)
const setCookie = __nccwpck_require__(37303)
function Response (req, onEnd, reject) {
http.ServerResponse.call(this, req)
this._lightMyRequest = { headers: null, trailers: {}, payloadChunks: [] }
// This forces node@8 to always render the headers
this.setHeader('foo', 'bar'); this.removeHeader('foo')
this.assignSocket(getNullSocket())
this._promiseCallback = typeof reject === 'function'
let called = false
const onEndSuccess = (payload) => {
// no need to early-return if already called because this handler is bound `once`
called = true
if (this._promiseCallback) {
return process.nextTick(() => onEnd(payload))
}
process.nextTick(() => onEnd(null, payload))
}
const onEndFailure = (err) => {
if (called) return
called = true
if (this._promiseCallback) {
return process.nextTick(() => reject(err))
}
process.nextTick(() => onEnd(err, null))
}
this.once('finish', () => {
const res = generatePayload(this)
res.raw.req = req
onEndSuccess(res)
})
this.connection.once('error', onEndFailure)
this.once('error', onEndFailure)
this.once('close', onEndFailure)
}
util.inherits(Response, http.ServerResponse)
Response.prototype.setTimeout = function (msecs, callback) {
this.timeoutHandle = setTimeout(() => {
this.emit('timeout')
}, msecs)
this.on('timeout', callback)
return this
}
Response.prototype.writeHead = function () {
const result = http.ServerResponse.prototype.writeHead.apply(this, arguments)
copyHeaders(this)
return result
}
Response.prototype.write = function (data, encoding, callback) {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle)
}
http.ServerResponse.prototype.write.call(this, data, encoding, callback)
this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding))
return true
}
Response.prototype.end = function (data, encoding, callback) {
if (data) {
this.write(data, encoding)
}
http.ServerResponse.prototype.end.call(this, callback)
this.emit('finish')
// We need to emit 'close' otherwise stream.finished() would
// not pick it up on Node v16
this.destroy()
}
Response.prototype.destroy = function (error) {
if (this.destroyed) return
this.destroyed = true
if (error) {
process.nextTick(() => this.emit('error', error))
}
process.nextTick(() => this.emit('close'))
}
Response.prototype.addTrailers = function (trailers) {
for (const key in trailers) {
this._lightMyRequest.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim()
}
}
function generatePayload (response) {
// This seems only to happen when using `fastify-express` - see https://github.com/fastify/fastify-express/issues/47
/* istanbul ignore if */
if (response._lightMyRequest.headers === null) {
copyHeaders(response)
}
serializeHeaders(response)
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._lightMyRequest.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {},
get cookies () {
return setCookie.parse(this)
}
}
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._lightMyRequest.payloadChunks)
res.rawPayload = rawBuffer
// we keep both of them for compatibility reasons
res.payload = rawBuffer.toString()
res.body = res.payload
res.trailers = response._lightMyRequest.trailers
// Prepare payload parsers
res.json = function parseJsonPayload () {
return JSON.parse(res.payload)
}
// Provide stream Readable for advanced user
res.stream = function streamPayload () {
return Readable.from(response._lightMyRequest.payloadChunks)
}
return res
}
// Throws away all written data to prevent response from buffering payload
function getNullSocket () {
return new Writable({
write (chunk, encoding, callback) {
setImmediate(callback)
}
})
}
function serializeHeaders (response) {
const headers = response._lightMyRequest.headers
for (const headerName of Object.keys(headers)) {
const headerValue = headers[headerName]
if (Array.isArray(headerValue)) {
headers[headerName] = headerValue.map(value => '' + value)
} else {
headers[headerName] = '' + headerValue
}
}
}
function copyHeaders (response) {
response._lightMyRequest.headers = Object.assign({}, response.getHeaders())
// Add raw headers
;['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n')
const field = response._header.match(regex)
if (field) {
response._lightMyRequest.headers[name.toLowerCase()] = field[1]
}
})
}
module.exports = Response
/***/ }),
/***/ 5848:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const errSerializer = __nccwpck_require__(17000)
const errWithCauseSerializer = __nccwpck_require__(49763)
const reqSerializers = __nccwpck_require__(24521)
const resSerializers = __nccwpck_require__(70352)
module.exports = {
err: errSerializer,
errWithCause: errWithCauseSerializer,
mapHttpRequest: reqSerializers.mapHttpRequest,
mapHttpResponse: resSerializers.mapHttpResponse,
req: reqSerializers.reqSerializer,
res: resSerializers.resSerializer,
wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {
if (customSerializer === errSerializer) return customSerializer
return function wrapErrSerializer (err) {
return customSerializer(errSerializer(err))
}
},
wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {
if (customSerializer === reqSerializers.reqSerializer) return customSerializer
return function wrappedReqSerializer (req) {
return customSerializer(reqSerializers.reqSerializer(req))
}
},
wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {
if (customSerializer === resSerializers.resSerializer) return customSerializer
return function wrappedResSerializer (res) {
return customSerializer(resSerializers.resSerializer(res))
}
}
}
/***/ }),
/***/ 8468:
/***/ ((module) => {
"use strict";
// **************************************************************
// * Code initially copied/adapted from "pony-cause" npm module *
// * Please upstream improvements there *
// **************************************************************
const isErrorLike = (err) => {
return err && typeof err.message === 'string'
}
/**
* @param {Error|{ cause?: unknown|(()=>err)}} err
* @returns {Error|Object|undefined}
*/
const getErrorCause = (err) => {
if (!err) return
/** @type {unknown} */
// @ts-ignore
const cause = err.cause
// VError / NError style causes
if (typeof cause === 'function') {
// @ts-ignore
const causeResult = err.cause()
return isErrorLike(causeResult)
? causeResult
: undefined
} else {
return isErrorLike(cause)
? cause
: undefined
}
}
/**
* Internal method that keeps a track of which error we have already added, to avoid circular recursion
*
* @private
* @param {Error} err
* @param {Set<Error>} seen
* @returns {string}
*/
const _stackWithCauses = (err, seen) => {
if (!isErrorLike(err)) return ''
const stack = err.stack || ''
// Ensure we don't go circular or crazily deep
if (seen.has(err)) {
return stack + '\ncauses have become circular...'
}
const cause = getErrorCause(err)
if (cause) {
seen.add(err)
return (stack + '\ncaused by: ' + _stackWithCauses(cause, seen))
} else {
return stack
}
}
/**
* @param {Error} err
* @returns {string}
*/
const stackWithCauses = (err) => _stackWithCauses(err, new Set())
/**
* Internal method that keeps a track of which error we have already added, to avoid circular recursion
*
* @private
* @param {Error} err
* @param {Set<Error>} seen
* @param {boolean} [skip]
* @returns {string}
*/
const _messageWithCauses = (err, seen, skip) => {
if (!isErrorLike(err)) return ''
const message = skip ? '' : (err.message || '')
// Ensure we don't go circular or crazily deep
if (seen.has(err)) {
return message + ': ...'
}
const cause = getErrorCause(err)
if (cause) {
seen.add(err)
// @ts-ignore
const skipIfVErrorStyleCause = typeof err.cause === 'function'
return (message +
(skipIfVErrorStyleCause ? '' : ': ') +
_messageWithCauses(cause, seen, skipIfVErrorStyleCause))
} else {
return message
}
}
/**
* @param {Error} err
* @returns {string}
*/
const messageWithCauses = (err) => _messageWithCauses(err, new Set())
module.exports = {
isErrorLike,
getErrorCause,
stackWithCauses,
messageWithCauses
}
/***/ }),
/***/ 37786:
/***/ ((module) => {
"use strict";
const seen = Symbol('circular-ref-tag')
const rawSymbol = Symbol('pino-raw-err-ref')
const pinoErrProto = Object.create({}, {
type: {
enumerable: true,
writable: true,
value: undefined
},
message: {
enumerable: true,
writable: true,
value: undefined
},
stack: {
enumerable: true,
writable: true,
value: undefined
},
aggregateErrors: {
enumerable: true,
writable: true,
value: undefined
},
raw: {
enumerable: false,
get: function () {
return this[rawSymbol]
},
set: function (val) {
this[rawSymbol] = val
}
}
})
Object.defineProperty(pinoErrProto, rawSymbol, {
writable: true,
value: {}
})
module.exports = {
pinoErrProto,
pinoErrorSymbols: {
seen,
rawSymbol
}
}
/***/ }),
/***/ 49763:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports = errWithCauseSerializer
const { isErrorLike } = __nccwpck_require__(8468)
const { pinoErrProto, pinoErrorSymbols } = __nccwpck_require__(37786)
const { seen } = pinoErrorSymbols
const { toString } = Object.prototype
function errWithCauseSerializer (err) {
if (!isErrorLike(err)) {
return err
}
err[seen] = undefined // tag to prevent re-looking at this
const _err = Object.create(pinoErrProto)
_err.type = toString.call(err.constructor) === '[object Function]'
? err.constructor.name
: err.name
_err.message = err.message
_err.stack = err.stack
if (Array.isArray(err.errors)) {
_err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))
}
if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {
_err.cause = errWithCauseSerializer(err.cause)
}
for (const key in err) {
if (_err[key] === undefined) {
const val = err[key]
if (isErrorLike(val)) {
if (!Object.prototype.hasOwnProperty.call(val, seen)) {
_err[key] = errWithCauseSerializer(val)
}
} else {
_err[key] = val
}
}
}
delete err[seen] // clean up tag in case err is serialized again later
_err.raw = err
return _err
}
/***/ }),
/***/ 17000:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
module.exports = errSerializer
const { messageWithCauses, stackWithCauses, isErrorLike } = __nccwpck_require__(8468)
const { pinoErrProto, pinoErrorSymbols } = __nccwpck_require__(37786)
const { seen } = pinoErrorSymbols
const { toString } = Object.prototype
function errSerializer (err) {
if (!isErrorLike(err)) {
return err
}
err[seen] = undefined // tag to prevent re-looking at this
const _err = Object.create(pinoErrProto)
_err.type = toString.call(err.constructor) === '[object Function]'
? err.constructor.name
: err.name
_err.message = messageWithCauses(err)
_err.stack = stackWithCauses(err)
if (Array.isArray(err.errors)) {
_err.aggregateErrors = err.errors.map(err => errSerializer(err))
}
for (const key in err) {
if (_err[key] === undefined) {
const val = err[key]
if (isErrorLike(val)) {
// We append cause messages and stacks to _err, therefore skipping causes here
if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {
_err[key] = errSerializer(val)
}
} else {
_err[key] = val
}
}
}
delete err[seen] // clean up tag in case err is serialized again later
_err.raw = err
return _err
}
/***/ }),
/***/ 24521:
/***/ ((module) => {
"use strict";
module.exports = {
mapHttpRequest,
reqSerializer
}
const rawSymbol = Symbol('pino-raw-req-ref')
const pinoReqProto = Object.create({}, {
id: {
enumerable: true,
writable: true,
value: ''
},
method: {
enumerable: true,
writable: true,
value: ''
},
url: {
enumerable: true,
writable: true,
value: ''
},
query: {
enumerable: true,
writable: true,
value: ''
},
params: {
enumerable: true,
writable: true,
value: ''
},
headers: {
enumerable: true,
writable: true,
value: {}
},
remoteAddress: {
enumerable: true,
writable: true,
value: ''
},
remotePort: {
enumerable: true,
writable: true,
value: ''
},
raw: {
enumerable: false,
get: function () {
return this[rawSymbol]
},
set: function (val) {
this[rawSymbol] = val
}
}
})
Object.defineProperty(pinoReqProto, rawSymbol, {
writable: true,
value: {}
})
function reqSerializer (req) {
// req.info is for hapi compat.
const connection = req.info || req.socket
const _req = Object.create(pinoReqProto)
_req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))
_req.method = req.method
// req.originalUrl is for expressjs compat.
if (req.originalUrl) {
_req.url = req.originalUrl
} else {
const path = req.path
// path for safe hapi compat.
_req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)
}
if (req.query) {
_req.query = req.query
}
if (req.params) {
_req.params = req.params
}
_req.headers = req.headers
_req.remoteAddress = connection && connection.remoteAddress
_req.remotePort = connection && connection.remotePort
// req.raw is for hapi compat/equivalence
_req.raw = req.raw || req
return _req
}
function mapHttpRequest (req) {
return {
req: reqSerializer(req)
}
}
/***/ }),
/***/ 70352:
/***/ ((module) => {
"use strict";
module.exports = {
mapHttpResponse,
resSerializer
}
const rawSymbol = Symbol('pino-raw-res-ref')
const pinoResProto = Object.create({}, {
statusCode: {
enumerable: true,
writable: true,
value: 0
},
headers: {
enumerable: true,
writable: true,
value: ''
},
raw: {
enumerable: false,
get: function () {
return this[rawSymbol]
},
set: function (val) {
this[rawSymbol] = val
}
}
})
Object.defineProperty(pinoResProto, rawSymbol, {
writable: true,
value: {}
})
function resSerializer (res) {
const _res = Object.create(pinoResProto)
_res.statusCode = res.headersSent ? res.statusCode : null
_res.headers = res.getHeaders ? res.getHeaders() : res._headers
_res.raw = res
return _res
}
function mapHttpResponse (res) {
return {
res: resSerializer(res)
}
}
/***/ }),
/***/ 63588:
/***/ ((module) => {
"use strict";
function noOpPrepareStackTrace (_, stack) {
return stack
}
module.exports = function getCallers () {
const originalPrepare = Error.prepareStackTrace
Error.prepareStackTrace = noOpPrepareStackTrace
const stack = new Error().stack
Error.prepareStackTrace = originalPrepare
if (!Array.isArray(stack)) {
return undefined
}
const entries = stack.slice(2)
const fileNames = []
for (const entry of entries) {
if (!entry) {
continue
}
fileNames.push(entry.getFileName())
}
return fileNames
}
/***/ }),
/***/ 13064:
/***/ ((module) => {
/**
* Represents default log level values
*
* @enum {number}
*/
const DEFAULT_LEVELS = {
trace: 10,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60
}
/**
* Represents sort order direction: `ascending` or `descending`
*
* @enum {string}
*/
const SORTING_ORDER = {
ASC: 'ASC',
DESC: 'DESC'
}
module.exports = {
DEFAULT_LEVELS,
SORTING_ORDER
}
/***/ }),
/***/ 18015:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const {
lsCacheSym,
levelValSym,
useOnlyCustomLevelsSym,
streamSym,
formattersSym,
hooksSym,
levelCompSym
} = __nccwpck_require__(62232)
const { noop, genLog } = __nccwpck_require__(98433)
const { DEFAULT_LEVELS, SORTING_ORDER } = __nccwpck_require__(13064)
const levelMethods = {
fatal: (hook) => {
const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)
return function (...args) {
const stream = this[streamSym]
logFatal.call(this, ...args)
if (typeof stream.flushSync === 'function') {
try {
stream.flushSync()
} catch (e) {
// https://github.com/pinojs/pino/pull/740#discussion_r346788313
}
}
}
},
error: (hook) => genLog(DEFAULT_LEVELS.error, hook),
warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),
info: (hook) => genLog(DEFAULT_LEVELS.info, hook),
debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),
trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)
}
const nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {
o[DEFAULT_LEVELS[k]] = k
return o
}, {})
const initialLsCache = Object.keys(nums).reduce((o, k) => {
o[k] = '{"level":' + Number(k)
return o
}, {})
function genLsCache (instance) {
const formatter = instance[formattersSym].level
const { labels } = instance.levels
const cache = {}
for (const label in labels) {
const level = formatter(labels[label], Number(label))
cache[label] = JSON.stringify(level).slice(0, -1)
}
instance[lsCacheSym] = cache
return instance
}
function isStandardLevel (level, useOnlyCustomLevels) {
if (useOnlyCustomLevels) {
return false
}
switch (level) {
case 'fatal':
case 'error':
case 'warn':
case 'info':
case 'debug':
case 'trace':
return true
default:
return false
}
}
function setLevel (level) {
const { labels, values } = this.levels
if (typeof level === 'number') {
if (labels[level] === undefined) throw Error('unknown level value' + level)
level = labels[level]
}
if (values[level] === undefined) throw Error('unknown level ' + level)
const preLevelVal = this[levelValSym]
const levelVal = this[levelValSym] = values[level]
const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]
const levelComparison = this[levelCompSym]
const hook = this[hooksSym].logMethod
for (const key in values) {
if (levelComparison(values[key], levelVal) === false) {
this[key] = noop
continue
}
this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)
}
this.emit(
'level-change',
level,
levelVal,
labels[preLevelVal],
preLevelVal,
this
)
}
function getLevel (level) {
const { levels, levelVal } = this
// protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)
return (levels && levels.labels) ? levels.labels[levelVal] : ''
}
function isLevelEnabled (logLevel) {
const { values } = this.levels
const logLevelVal = values[logLevel]
return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])
}
/**
* Determine if the given `current` level is enabled by comparing it
* against the current threshold (`expected`).
*
* @param {SORTING_ORDER} direction comparison direction "ASC" or "DESC"
* @param {number} current current log level number representation
* @param {number} expected threshold value to compare with
* @returns {boolean}
*/
function compareLevel (direction, current, expected) {
if (direction === SORTING_ORDER.DESC) {
return current <= expected
}
return current >= expected
}
/**
* Create a level comparison function based on `levelComparison`
* it could a default function which compares levels either in "ascending" or "descending" order or custom comparison function
*
* @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function
* @returns Function
*/
function genLevelComparison (levelComparison) {
if (typeof levelComparison === 'string') {
return compareLevel.bind(null, levelComparison)
}
return levelComparison
}
function mappings (customLevels = null, useOnlyCustomLevels = false) {
const customNums = customLevels
/* eslint-disable */
? Object.keys(customLevels).reduce((o, k) => {
o[customLevels[k]] = k
return o
}, {})
: null
/* eslint-enable */
const labels = Object.assign(
Object.create(Object.prototype, { Infinity: { value: 'silent' } }),
useOnlyCustomLevels ? null : nums,
customNums
)
const values = Object.assign(
Object.create(Object.prototype, { silent: { value: Infinity } }),
useOnlyCustomLevels ? null : DEFAULT_LEVELS,
customLevels
)
return { labels, values }
}
function assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {
if (typeof defaultLevel === 'number') {
const values = [].concat(
Object.keys(customLevels || {}).map(key => customLevels[key]),
useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),
Infinity
)
if (!values.includes(defaultLevel)) {
throw Error(`default level:${defaultLevel} must be included in custom levels`)
}
return
}
const labels = Object.assign(
Object.create(Object.prototype, { silent: { value: Infinity } }),
useOnlyCustomLevels ? null : DEFAULT_LEVELS,
customLevels
)
if (!(defaultLevel in labels)) {
throw Error(`default level:${defaultLevel} must be included in custom levels`)
}
}
function assertNoLevelCollisions (levels, customLevels) {
const { labels, values } = levels
for (const k in customLevels) {
if (k in values) {
throw Error('levels cannot be overridden')
}
if (customLevels[k] in labels) {
throw Error('pre-existing level values cannot be used for new levels')
}
}
}
/**
* Validates whether `levelComparison` is correct
*
* @throws Error
* @param {SORTING_ORDER | Function} levelComparison - value to validate
* @returns
*/
function assertLevelComparison (levelComparison) {
if (typeof levelComparison === 'function') {
return
}
if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {
return
}
throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')
}
module.exports = {
initialLsCache,
genLsCache,
levelMethods,
getLevel,
setLevel,
isLevelEnabled,
mappings,
assertNoLevelCollisions,
assertDefaultLevelFound,
genLevelComparison,
assertLevelComparison
}
/***/ }),
/***/ 62812:
/***/ ((module) => {
"use strict";
module.exports = { version: '9.2.0' }
/***/ }),
/***/ 74411:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const metadata = Symbol.for('pino.metadata')
const { DEFAULT_LEVELS } = __nccwpck_require__(13064)
const DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info
function multistream (streamsArray, opts) {
let counter = 0
streamsArray = streamsArray || []
opts = opts || { dedupe: false }
const streamLevels = Object.create(DEFAULT_LEVELS)
streamLevels.silent = Infinity
if (opts.levels && typeof opts.levels === 'object') {
Object.keys(opts.levels).forEach(i => {
streamLevels[i] = opts.levels[i]
})
}
const res = {
write,
add,
emit,
flushSync,
end,
minLevel: 0,
streams: [],
clone,
[metadata]: true,
streamLevels
}
if (Array.isArray(streamsArray)) {
streamsArray.forEach(add, res)
} else {
add.call(res, streamsArray)
}
// clean this object up
// or it will stay allocated forever
// as it is closed on the following closures
streamsArray = null
return res
// we can exit early because the streams are ordered by level
function write (data) {
let dest
const level = this.lastLevel
const { streams } = this
// for handling situation when several streams has the same level
let recordedLevel = 0
let stream
// if dedupe set to true we send logs to the stream with the highest level
// therefore, we have to change sorting order
for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
dest = streams[i]
if (dest.level <= level) {
if (recordedLevel !== 0 && recordedLevel !== dest.level) {
break
}
stream = dest.stream
if (stream[metadata]) {
const { lastTime, lastMsg, lastObj, lastLogger } = this
stream.lastLevel = level
stream.lastTime = lastTime
stream.lastMsg = lastMsg
stream.lastObj = lastObj
stream.lastLogger = lastLogger
}
stream.write(data)
if (opts.dedupe) {
recordedLevel = dest.level
}
} else if (!opts.dedupe) {
break
}
}
}
function emit (...args) {
for (const { stream } of this.streams) {
if (typeof stream.emit === 'function') {
stream.emit(...args)
}
}
}
function flushSync () {
for (const { stream } of this.streams) {
if (typeof stream.flushSync === 'function') {
stream.flushSync()
}
}
}
function add (dest) {
if (!dest) {
return res
}
// Check that dest implements either StreamEntry or DestinationStream
const isStream = typeof dest.write === 'function' || dest.stream
const stream_ = dest.write ? dest : dest.stream
// This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()
if (!isStream) {
throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')
}
const { streams, streamLevels } = this
let level
if (typeof dest.levelVal === 'number') {
level = dest.levelVal
} else if (typeof dest.level === 'string') {
level = streamLevels[dest.level]
} else if (typeof dest.level === 'number') {
level = dest.level
} else {
level = DEFAULT_INFO_LEVEL
}
const dest_ = {
stream: stream_,
level,
levelVal: undefined,
id: counter++
}
streams.unshift(dest_)
streams.sort(compareByLevel)
this.minLevel = streams[0].level
return res
}
function end () {
for (const { stream } of this.streams) {
if (typeof stream.flushSync === 'function') {
stream.flushSync()
}
stream.end()
}
}
function clone (level) {
const streams = new Array(this.streams.length)
for (let i = 0; i < streams.length; i++) {
streams[i] = {
level,
stream: this.streams[i].stream
}
}
return {
write,
add,
minLevel: level,
streams,
clone,
emit,
flushSync,
[metadata]: true
}
}
}
function compareByLevel (a, b) {
return a.level - b.level
}
function initLoopVar (length, dedupe) {
return dedupe ? length - 1 : 0
}
function adjustLoopVar (i, dedupe) {
return dedupe ? i - 1 : i + 1
}
function checkLoopVar (i, length, dedupe) {
return dedupe ? i >= 0 : i < length
}
module.exports = multistream
/***/ }),
/***/ 43779:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const { EventEmitter } = __nccwpck_require__(82361)
const {
lsCacheSym,
levelValSym,
setLevelSym,
getLevelSym,
chindingsSym,
parsedChindingsSym,
mixinSym,
asJsonSym,
writeSym,
mixinMergeStrategySym,
timeSym,
timeSliceIndexSym,
streamSym,
serializersSym,
formattersSym,
errorKeySym,
messageKeySym,
useOnlyCustomLevelsSym,
needsMetadataGsym,
redactFmtSym,
stringifySym,
formatOptsSym,
stringifiersSym,
msgPrefixSym
} = __nccwpck_require__(62232)
const {
getLevel,
setLevel,
isLevelEnabled,
mappings,
initialLsCache,
genLsCache,
assertNoLevelCollisions
} = __nccwpck_require__(18015)
const {
asChindings,
asJson,
buildFormatters,
stringify
} = __nccwpck_require__(98433)
const {
version
} = __nccwpck_require__(62812)
const redaction = __nccwpck_require__(75159)
// note: use of class is satirical
// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127
const constructor = class Pino {}
const prototype = {
constructor,
child,
bindings,
setBindings,
flush,
isLevelEnabled,
version,
get level () { return this[getLevelSym]() },
set level (lvl) { this[setLevelSym](lvl) },
get levelVal () { return this[levelValSym] },
set levelVal (n) { throw Error('levelVal is read-only') },
[lsCacheSym]: initialLsCache,
[writeSym]: write,
[asJsonSym]: asJson,
[getLevelSym]: getLevel,
[setLevelSym]: setLevel
}
Object.setPrototypeOf(prototype, EventEmitter.prototype)
// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing
module.exports = function () {
return Object.create(prototype)
}
const resetChildingsFormatter = bindings => bindings
function child (bindings, options) {
if (!bindings) {
throw Error('missing bindings for child Pino')
}
options = options || {} // default options to empty object
const serializers = this[serializersSym]
const formatters = this[formattersSym]
const instance = Object.create(this)
if (options.hasOwnProperty('serializers') === true) {
instance[serializersSym] = Object.create(null)
for (const k in serializers) {
instance[serializersSym][k] = serializers[k]
}
const parentSymbols = Object.getOwnPropertySymbols(serializers)
/* eslint no-var: off */
for (var i = 0; i < parentSymbols.length; i++) {
const ks = parentSymbols[i]
instance[serializersSym][ks] = serializers[ks]
}
for (const bk in options.serializers) {
instance[serializersSym][bk] = options.serializers[bk]
}
const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)
for (var bi = 0; bi < bindingsSymbols.length; bi++) {
const bks = bindingsSymbols[bi]
instance[serializersSym][bks] = options.serializers[bks]
}
} else instance[serializersSym] = serializers
if (options.hasOwnProperty('formatters')) {
const { level, bindings: chindings, log } = options.formatters
instance[formattersSym] = buildFormatters(
level || formatters.level,
chindings || resetChildingsFormatter,
log || formatters.log
)
} else {
instance[formattersSym] = buildFormatters(
formatters.level,
resetChildingsFormatter,
formatters.log
)
}
if (options.hasOwnProperty('customLevels') === true) {
assertNoLevelCollisions(this.levels, options.customLevels)
instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])
genLsCache(instance)
}
// redact must place before asChindings and only replace if exist
if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {
instance.redact = options.redact // replace redact directly
const stringifiers = redaction(instance.redact, stringify)
const formatOpts = { stringify: stringifiers[redactFmtSym] }
instance[stringifySym] = stringify
instance[stringifiersSym] = stringifiers
instance[formatOptsSym] = formatOpts
}
if (typeof options.msgPrefix === 'string') {
instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix
}
instance[chindingsSym] = asChindings(instance, bindings)
const childLevel = options.level || this.level
instance[setLevelSym](childLevel)
this.onChild(instance)
return instance
}
function bindings () {
const chindings = this[chindingsSym]
const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac"
const bindingsFromJson = JSON.parse(chindingsJson)
delete bindingsFromJson.pid
delete bindingsFromJson.hostname
return bindingsFromJson
}
function setBindings (newBindings) {
const chindings = asChindings(this, newBindings)
this[chindingsSym] = chindings
delete this[parsedChindingsSym]
}
/**
* Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.
* Fields from `mergeObject` have higher priority in this strategy.
*
* @param {Object} mergeObject The object a user has supplied to the logging function.
* @param {Object} mixinObject The result of the `mixin` method.
* @return {Object}
*/
function defaultMixinMergeStrategy (mergeObject, mixinObject) {
return Object.assign(mixinObject, mergeObject)
}
function write (_obj, msg, num) {
const t = this[timeSym]()
const mixin = this[mixinSym]
const errorKey = this[errorKeySym]
const messageKey = this[messageKeySym]
const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy
let obj
if (_obj === undefined || _obj === null) {
obj = {}
} else if (_obj instanceof Error) {
obj = { [errorKey]: _obj }
if (msg === undefined) {
msg = _obj.message
}
} else {
obj = _obj
if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {
msg = _obj[errorKey].message
}
}
if (mixin) {
obj = mixinMergeStrategy(obj, mixin(obj, num, this))
}
const s = this[asJsonSym](obj, msg, num, t)
const stream = this[streamSym]
if (stream[needsMetadataGsym] === true) {
stream.lastLevel = num
stream.lastObj = obj
stream.lastMsg = msg
stream.lastTime = t.slice(this[timeSliceIndexSym])
stream.lastLogger = this // for child loggers
}
stream.write(s)
}
function noop () {}
function flush (cb) {
if (cb != null && typeof cb !== 'function') {
throw Error('callback must be a function')
}
const stream = this[streamSym]
if (typeof stream.flush === 'function') {
stream.flush(cb || noop)
} else if (cb) cb()
}
/***/ }),
/***/ 75159:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fastRedact = __nccwpck_require__(24826)
const { redactFmtSym, wildcardFirstSym } = __nccwpck_require__(62232)
const { rx, validator } = fastRedact
const validate = validator({
ERR_PATHS_MUST_BE_STRINGS: () => 'pino redacted paths must be strings',
ERR_INVALID_PATH: (s) => `pino redact paths array contains an invalid path (${s})`
})
const CENSOR = '[Redacted]'
const strict = false // TODO should this be configurable?
function redaction (opts, serialize) {
const { paths, censor } = handle(opts)
const shape = paths.reduce((o, str) => {
rx.lastIndex = 0
const first = rx.exec(str)
const next = rx.exec(str)
// ns is the top-level path segment, brackets + quoting removed.
let ns = first[1] !== undefined
? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1')
: first[0]
if (ns === '*') {
ns = wildcardFirstSym
}
// top level key:
if (next === null) {
o[ns] = null
return o
}
// path with at least two segments:
// if ns is already redacted at the top level, ignore lower level redactions
if (o[ns] === null) {
return o
}
const { index } = next
const nextPath = `${str.substr(index, str.length - 1)}`
o[ns] = o[ns] || []
// shape is a mix of paths beginning with literal values and wildcard
// paths [ "a.b.c", "*.b.z" ] should reduce to a shape of
// { "a": [ "b.c", "b.z" ], *: [ "b.z" ] }
// note: "b.z" is in both "a" and * arrays because "a" matches the wildcard.
// (* entry has wildcardFirstSym as key)
if (ns !== wildcardFirstSym && o[ns].length === 0) {
// first time ns's get all '*' redactions so far
o[ns].push(...(o[wildcardFirstSym] || []))
}
if (ns === wildcardFirstSym) {
// new * path gets added to all previously registered literal ns's.
Object.keys(o).forEach(function (k) {
if (o[k]) {
o[k].push(nextPath)
}
})
}
o[ns].push(nextPath)
return o
}, {})
// the redactor assigned to the format symbol key
// provides top level redaction for instances where
// an object is interpolated into the msg string
const result = {
[redactFmtSym]: fastRedact({ paths, censor, serialize, strict })
}
const topCensor = (...args) => {
return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)
}
return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {
// top level key:
if (shape[k] === null) {
o[k] = (value) => topCensor(value, [k])
} else {
const wrappedCensor = typeof censor === 'function'
? (value, path) => {
return censor(value, [k, ...path])
}
: censor
o[k] = fastRedact({
paths: shape[k],
censor: wrappedCensor,
serialize,
strict
})
}
return o
}, result)
}
function handle (opts) {
if (Array.isArray(opts)) {
opts = { paths: opts, censor: CENSOR }
validate(opts)
return opts
}
let { paths, censor = CENSOR, remove } = opts
if (Array.isArray(paths) === false) { throw Error('pino redact must contain an array of strings') }
if (remove === true) censor = undefined
validate({ paths, censor })
return { paths, censor }
}
module.exports = redaction
/***/ }),
/***/ 62232:
/***/ ((module) => {
"use strict";
const setLevelSym = Symbol('pino.setLevel')
const getLevelSym = Symbol('pino.getLevel')
const levelValSym = Symbol('pino.levelVal')
const levelCompSym = Symbol('pino.levelComp')
const useLevelLabelsSym = Symbol('pino.useLevelLabels')
const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')
const mixinSym = Symbol('pino.mixin')
const lsCacheSym = Symbol('pino.lsCache')
const chindingsSym = Symbol('pino.chindings')
const asJsonSym = Symbol('pino.asJson')
const writeSym = Symbol('pino.write')
const redactFmtSym = Symbol('pino.redactFmt')
const timeSym = Symbol('pino.time')
const timeSliceIndexSym = Symbol('pino.timeSliceIndex')
const streamSym = Symbol('pino.stream')
const stringifySym = Symbol('pino.stringify')
const stringifySafeSym = Symbol('pino.stringifySafe')
const stringifiersSym = Symbol('pino.stringifiers')
const endSym = Symbol('pino.end')
const formatOptsSym = Symbol('pino.formatOpts')
const messageKeySym = Symbol('pino.messageKey')
const errorKeySym = Symbol('pino.errorKey')
const nestedKeySym = Symbol('pino.nestedKey')
const nestedKeyStrSym = Symbol('pino.nestedKeyStr')
const mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')
const msgPrefixSym = Symbol('pino.msgPrefix')
const wildcardFirstSym = Symbol('pino.wildcardFirst')
// public symbols, no need to use the same pino
// version for these
const serializersSym = Symbol.for('pino.serializers')
const formattersSym = Symbol.for('pino.formatters')
const hooksSym = Symbol.for('pino.hooks')
const needsMetadataGsym = Symbol.for('pino.metadata')
module.exports = {
setLevelSym,
getLevelSym,
levelValSym,
levelCompSym,
useLevelLabelsSym,
mixinSym,
lsCacheSym,
chindingsSym,
asJsonSym,
writeSym,
serializersSym,
redactFmtSym,
timeSym,
timeSliceIndexSym,
streamSym,
stringifySym,
stringifySafeSym,
stringifiersSym,
endSym,
formatOptsSym,
messageKeySym,
errorKeySym,
nestedKeySym,
wildcardFirstSym,
needsMetadataGsym,
useOnlyCustomLevelsSym,
formattersSym,
hooksSym,
nestedKeyStrSym,
mixinMergeStrategySym,
msgPrefixSym
}
/***/ }),
/***/ 30857:
/***/ ((module) => {
"use strict";
const nullTime = () => ''
const epochTime = () => `,"time":${Date.now()}`
const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}`
const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"` // using Date.now() for testability
module.exports = { nullTime, epochTime, unixTime, isoTime }
/***/ }),
/***/ 98433:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const format = __nccwpck_require__(5933)
const { mapHttpRequest, mapHttpResponse } = __nccwpck_require__(5848)
const SonicBoom = __nccwpck_require__(330)
const onExit = __nccwpck_require__(39660)
const {
lsCacheSym,
chindingsSym,
writeSym,
serializersSym,
formatOptsSym,
endSym,
stringifiersSym,
stringifySym,
stringifySafeSym,
wildcardFirstSym,
nestedKeySym,
formattersSym,
messageKeySym,
errorKeySym,
nestedKeyStrSym,
msgPrefixSym
} = __nccwpck_require__(62232)
const { isMainThread } = __nccwpck_require__(71267)
const transport = __nccwpck_require__(96129)
function noop () {
}
function genLog (level, hook) {
if (!hook) return LOG
return function hookWrappedLog (...args) {
hook.call(this, args, LOG, level)
}
function LOG (o, ...n) {
if (typeof o === 'object') {
let msg = o
if (o !== null) {
if (o.method && o.headers && o.socket) {
o = mapHttpRequest(o)
} else if (typeof o.setHeader === 'function') {
o = mapHttpResponse(o)
}
}
let formatParams
if (msg === null && n.length === 0) {
formatParams = [null]
} else {
msg = n.shift()
formatParams = n
}
// We do not use a coercive check for `msg` as it is
// measurably slower than the explicit checks.
if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {
msg = this[msgPrefixSym] + msg
}
this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)
} else {
let msg = o === undefined ? n.shift() : o
// We do not use a coercive check for `msg` as it is
// measurably slower than the explicit checks.
if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {
msg = this[msgPrefixSym] + msg
}
this[writeSym](null, format(msg, n, this[formatOptsSym]), level)
}
}
}
// magically escape strings for json
// relying on their charCodeAt
// everything below 32 needs JSON.stringify()
// 34 and 92 happens all the time, so we
// have a fast case for them
function asString (str) {
let result = ''
let last = 0
let found = false
let point = 255
const l = str.length
if (l > 100) {
return JSON.stringify(str)
}
for (var i = 0; i < l && point >= 32; i++) {
point = str.charCodeAt(i)
if (point === 34 || point === 92) {
result += str.slice(last, i) + '\\'
last = i
found = true
}
}
if (!found) {
result = str
} else {
result += str.slice(last)
}
return point < 32 ? JSON.stringify(str) : '"' + result + '"'
}
function asJson (obj, msg, num, time) {
const stringify = this[stringifySym]
const stringifySafe = this[stringifySafeSym]
const stringifiers = this[stringifiersSym]
const end = this[endSym]
const chindings = this[chindingsSym]
const serializers = this[serializersSym]
const formatters = this[formattersSym]
const messageKey = this[messageKeySym]
const errorKey = this[errorKeySym]
let data = this[lsCacheSym][num] + time
// we need the child bindings added to the output first so instance logged
// objects can take precedence when JSON.parse-ing the resulting log line
data = data + chindings
let value
if (formatters.log) {
obj = formatters.log(obj)
}
const wildcardStringifier = stringifiers[wildcardFirstSym]
let propStr = ''
for (const key in obj) {
value = obj[key]
if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {
if (serializers[key]) {
value = serializers[key](value)
} else if (key === errorKey && serializers.err) {
value = serializers.err(value)
}
const stringifier = stringifiers[key] || wildcardStringifier
switch (typeof value) {
case 'undefined':
case 'function':
continue
case 'number':
/* eslint no-fallthrough: "off" */
if (Number.isFinite(value) === false) {
value = null
}
// this case explicitly falls through to the next one
case 'boolean':
if (stringifier) value = stringifier(value)
break
case 'string':
value = (stringifier || asString)(value)
break
default:
value = (stringifier || stringify)(value, stringifySafe)
}
if (value === undefined) continue
const strKey = asString(key)
propStr += ',' + strKey + ':' + value
}
}
let msgStr = ''
if (msg !== undefined) {
value = serializers[messageKey] ? serializers[messageKey](msg) : msg
const stringifier = stringifiers[messageKey] || wildcardStringifier
switch (typeof value) {
case 'function':
break
case 'number':
/* eslint no-fallthrough: "off" */
if (Number.isFinite(value) === false) {
value = null
}
// this case explicitly falls through to the next one
case 'boolean':
if (stringifier) value = stringifier(value)
msgStr = ',"' + messageKey + '":' + value
break
case 'string':
value = (stringifier || asString)(value)
msgStr = ',"' + messageKey + '":' + value
break
default:
value = (stringifier || stringify)(value, stringifySafe)
msgStr = ',"' + messageKey + '":' + value
}
}
if (this[nestedKeySym] && propStr) {
// place all the obj properties under the specified key
// the nested key is already formatted from the constructor
return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end
} else {
return data + propStr + msgStr + end
}
}
function asChindings (instance, bindings) {
let value
let data = instance[chindingsSym]
const stringify = instance[stringifySym]
const stringifySafe = instance[stringifySafeSym]
const stringifiers = instance[stringifiersSym]
const wildcardStringifier = stringifiers[wildcardFirstSym]
const serializers = instance[serializersSym]
const formatter = instance[formattersSym].bindings
bindings = formatter(bindings)
for (const key in bindings) {
value = bindings[key]
const valid = key !== 'level' &&
key !== 'serializers' &&
key !== 'formatters' &&
key !== 'customLevels' &&
bindings.hasOwnProperty(key) &&
value !== undefined
if (valid === true) {
value = serializers[key] ? serializers[key](value) : value
value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)
if (value === undefined) continue
data += ',"' + key + '":' + value
}
}
return data
}
function hasBeenTampered (stream) {
return stream.write !== stream.constructor.prototype.write
}
const hasNodeCodeCoverage = process.env.NODE_V8_COVERAGE || process.env.V8_COVERAGE
function buildSafeSonicBoom (opts) {
const stream = new SonicBoom(opts)
stream.on('error', filterBrokenPipe)
// If we are sync: false, we must flush on exit
// We must disable this if there is node code coverage due to
// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308.
if (!hasNodeCodeCoverage && !opts.sync && isMainThread) {
onExit.register(stream, autoEnd)
stream.on('close', function () {
onExit.unregister(stream)
})
}
return stream
function filterBrokenPipe (err) {
// Impossible to replicate across all operating systems
/* istanbul ignore next */
if (err.code === 'EPIPE') {
// If we get EPIPE, we should stop logging here
// however we have no control to the consumer of
// SonicBoom, so we just overwrite the write method
stream.write = noop
stream.end = noop
stream.flushSync = noop
stream.destroy = noop
return
}
stream.removeListener('error', filterBrokenPipe)
stream.emit('error', err)
}
}
function autoEnd (stream, eventName) {
// This check is needed only on some platforms
/* istanbul ignore next */
if (stream.destroyed) {
return
}
if (eventName === 'beforeExit') {
// We still have an event loop, let's use it
stream.flush()
stream.on('drain', function () {
stream.end()
})
} else {
// For some reason istanbul is not detecting this, but it's there
/* istanbul ignore next */
// We do not have an event loop, so flush synchronously
stream.flushSync()
}
}
function createArgsNormalizer (defaultOptions) {
return function normalizeArgs (instance, caller, opts = {}, stream) {
// support stream as a string
if (typeof opts === 'string') {
stream = buildSafeSonicBoom({ dest: opts })
opts = {}
} else if (typeof stream === 'string') {
if (opts && opts.transport) {
throw Error('only one of option.transport or stream can be specified')
}
stream = buildSafeSonicBoom({ dest: stream })
} else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {
stream = opts
opts = {}
} else if (opts.transport) {
if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {
throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')
}
if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {
throw Error('option.transport.targets do not allow custom level formatters')
}
let customLevels
if (opts.customLevels) {
customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)
}
stream = transport({ caller, ...opts.transport, levels: customLevels })
}
opts = Object.assign({}, defaultOptions, opts)
opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)
opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)
if (opts.prettyPrint) {
throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')
}
const { enabled, onChild } = opts
if (enabled === false) opts.level = 'silent'
if (!onChild) opts.onChild = noop
if (!stream) {
if (!hasBeenTampered(process.stdout)) {
// If process.stdout.fd is undefined, it means that we are running
// in a worker thread. Let's assume we are logging to file descriptor 1.
stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })
} else {
stream = process.stdout
}
}
return { opts, stream }
}
}
function stringify (obj, stringifySafeFn) {
try {
return JSON.stringify(obj)
} catch (_) {
try {
const stringify = stringifySafeFn || this[stringifySafeSym]
return stringify(obj)
} catch (_) {
return '"[unable to serialize, circular reference is too complex to analyze]"'
}
}
}
function buildFormatters (level, bindings, log) {
return {
level,
bindings,
log
}
}
/**
* Convert a string integer file descriptor to a proper native integer
* file descriptor.
*
* @param {string} destination The file descriptor string to attempt to convert.
*
* @returns {Number}
*/
function normalizeDestFileDescriptor (destination) {
const fd = Number(destination)
if (typeof destination === 'string' && Number.isFinite(fd)) {
return fd
}
// destination could be undefined if we are in a worker
if (destination === undefined) {
// This is stdout in UNIX systems
return 1
}
return destination
}
module.exports = {
noop,
buildSafeSonicBoom,
asChindings,
asJson,
genLog,
createArgsNormalizer,
stringify,
buildFormatters,
normalizeDestFileDescriptor
}
/***/ }),
/***/ 96129:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { createRequire } = __nccwpck_require__(98188)
const getCallers = __nccwpck_require__(63588)
const { join, isAbsolute, sep } = __nccwpck_require__(71017)
const sleep = __nccwpck_require__(86950)
const onExit = __nccwpck_require__(39660)
const ThreadStream = __nccwpck_require__(78366)
function setupOnExit (stream) {
// This is leak free, it does not leave event handlers
onExit.register(stream, autoEnd)
onExit.registerBeforeExit(stream, flush)
stream.on('close', function () {
onExit.unregister(stream)
})
}
function buildStream (filename, workerData, workerOpts) {
const stream = new ThreadStream({
filename,
workerData,
workerOpts
})
stream.on('ready', onReady)
stream.on('close', function () {
process.removeListener('exit', onExit)
})
process.on('exit', onExit)
function onReady () {
process.removeListener('exit', onExit)
stream.unref()
if (workerOpts.autoEnd !== false) {
setupOnExit(stream)
}
}
function onExit () {
/* istanbul ignore next */
if (stream.closed) {
return
}
stream.flushSync()
// Apparently there is a very sporadic race condition
// that in certain OS would prevent the messages to be flushed
// because the thread might not have been created still.
// Unfortunately we need to sleep(100) in this case.
sleep(100)
stream.end()
}
return stream
}
function autoEnd (stream) {
stream.ref()
stream.flushSync()
stream.end()
stream.once('close', function () {
stream.unref()
})
}
function flush (stream) {
stream.flushSync()
}
function transport (fullOptions) {
const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers() } = fullOptions
const options = {
...fullOptions.options
}
// Backwards compatibility
const callers = typeof caller === 'string' ? [caller] : caller
// This will be eventually modified by bundlers
const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}
let target = fullOptions.target
if (target && targets) {
throw new Error('only one of target or targets can be specified')
}
if (targets) {
target = bundlerOverrides['pino-worker'] || __nccwpck_require__.ab + "worker.js"
options.targets = targets.filter(dest => dest.target).map((dest) => {
return {
...dest,
target: fixTarget(dest.target)
}
})
options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {
return dest.pipeline.map((t) => {
return {
...t,
level: dest.level, // duplicate the pipeline `level` property defined in the upper level
target: fixTarget(t.target)
}
})
})
} else if (pipeline) {
target = bundlerOverrides['pino-worker'] || __nccwpck_require__.ab + "worker.js"
options.pipelines = [pipeline.map((dest) => {
return {
...dest,
target: fixTarget(dest.target)
}
})]
}
if (levels) {
options.levels = levels
}
if (dedupe) {
options.dedupe = dedupe
}
options.pinoWillSendConfig = true
return buildStream(fixTarget(target), options, worker)
function fixTarget (origin) {
origin = bundlerOverrides[origin] || origin
if (isAbsolute(origin) || origin.indexOf('file://') === 0) {
return origin
}
if (origin === 'pino/file') {
return __nccwpck_require__.ab + "file.js"
}
let fixTarget
for (const filePath of callers) {
try {
const context = filePath === 'node:repl'
? process.cwd() + sep
: filePath
fixTarget = createRequire(context).resolve(origin)
break
} catch (err) {
// Silent catch
continue
}
}
if (!fixTarget) {
throw new Error(`unable to determine transport target for "${origin}"`)
}
return fixTarget
}
}
module.exports = transport
/***/ }),
/***/ 78085:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint no-prototype-builtins: 0 */
const os = __nccwpck_require__(22037)
const stdSerializers = __nccwpck_require__(5848)
const caller = __nccwpck_require__(63588)
const redaction = __nccwpck_require__(75159)
const time = __nccwpck_require__(30857)
const proto = __nccwpck_require__(43779)
const symbols = __nccwpck_require__(62232)
const { configure } = __nccwpck_require__(37560)
const { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = __nccwpck_require__(18015)
const { DEFAULT_LEVELS, SORTING_ORDER } = __nccwpck_require__(13064)
const {
createArgsNormalizer,
asChindings,
buildSafeSonicBoom,
buildFormatters,
stringify,
normalizeDestFileDescriptor,
noop
} = __nccwpck_require__(98433)
const { version } = __nccwpck_require__(62812)
const {
chindingsSym,
redactFmtSym,
serializersSym,
timeSym,
timeSliceIndexSym,
streamSym,
stringifySym,
stringifySafeSym,
stringifiersSym,
setLevelSym,
endSym,
formatOptsSym,
messageKeySym,
errorKeySym,
nestedKeySym,
mixinSym,
levelCompSym,
useOnlyCustomLevelsSym,
formattersSym,
hooksSym,
nestedKeyStrSym,
mixinMergeStrategySym,
msgPrefixSym
} = symbols
const { epochTime, nullTime } = time
const { pid } = process
const hostname = os.hostname()
const defaultErrorSerializer = stdSerializers.err
const defaultOptions = {
level: 'info',
levelComparison: SORTING_ORDER.ASC,
levels: DEFAULT_LEVELS,
messageKey: 'msg',
errorKey: 'err',
nestedKey: null,
enabled: true,
base: { pid, hostname },
serializers: Object.assign(Object.create(null), {
err: defaultErrorSerializer
}),
formatters: Object.assign(Object.create(null), {
bindings (bindings) {
return bindings
},
level (label, number) {
return { level: number }
}
}),
hooks: {
logMethod: undefined
},
timestamp: epochTime,
name: undefined,
redact: null,
customLevels: null,
useOnlyCustomLevels: false,
depthLimit: 5,
edgeLimit: 100
}
const normalize = createArgsNormalizer(defaultOptions)
const serializers = Object.assign(Object.create(null), stdSerializers)
function pino (...args) {
const instance = {}
const { opts, stream } = normalize(instance, caller(), ...args)
const {
redact,
crlf,
serializers,
timestamp,
messageKey,
errorKey,
nestedKey,
base,
name,
level,
customLevels,
levelComparison,
mixin,
mixinMergeStrategy,
useOnlyCustomLevels,
formatters,
hooks,
depthLimit,
edgeLimit,
onChild,
msgPrefix
} = opts
const stringifySafe = configure({
maximumDepth: depthLimit,
maximumBreadth: edgeLimit
})
const allFormatters = buildFormatters(
formatters.level,
formatters.bindings,
formatters.log
)
const stringifyFn = stringify.bind({
[stringifySafeSym]: stringifySafe
})
const stringifiers = redact ? redaction(redact, stringifyFn) : {}
const formatOpts = redact
? { stringify: stringifiers[redactFmtSym] }
: { stringify: stringifyFn }
const end = '}' + (crlf ? '\r\n' : '\n')
const coreChindings = asChindings.bind(null, {
[chindingsSym]: '',
[serializersSym]: serializers,
[stringifiersSym]: stringifiers,
[stringifySym]: stringify,
[stringifySafeSym]: stringifySafe,
[formattersSym]: allFormatters
})
let chindings = ''
if (base !== null) {
if (name === undefined) {
chindings = coreChindings(base)
} else {
chindings = coreChindings(Object.assign({}, base, { name }))
}
}
const time = (timestamp instanceof Function)
? timestamp
: (timestamp ? epochTime : nullTime)
const timeSliceIndex = time().indexOf(':') + 1
if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')
if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`)
if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`)
assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)
const levels = mappings(customLevels, useOnlyCustomLevels)
if (typeof stream.emit === 'function') {
stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })
}
assertLevelComparison(levelComparison)
const levelCompFunc = genLevelComparison(levelComparison)
Object.assign(instance, {
levels,
[levelCompSym]: levelCompFunc,
[useOnlyCustomLevelsSym]: useOnlyCustomLevels,
[streamSym]: stream,
[timeSym]: time,
[timeSliceIndexSym]: timeSliceIndex,
[stringifySym]: stringify,
[stringifySafeSym]: stringifySafe,
[stringifiersSym]: stringifiers,
[endSym]: end,
[formatOptsSym]: formatOpts,
[messageKeySym]: messageKey,
[errorKeySym]: errorKey,
[nestedKeySym]: nestedKey,
// protect against injection
[nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',
[serializersSym]: serializers,
[mixinSym]: mixin,
[mixinMergeStrategySym]: mixinMergeStrategy,
[chindingsSym]: chindings,
[formattersSym]: allFormatters,
[hooksSym]: hooks,
silent: noop,
onChild,
[msgPrefixSym]: msgPrefix
})
Object.setPrototypeOf(instance, proto())
genLsCache(instance)
instance[setLevelSym](level)
return instance
}
module.exports = pino
module.exports.destination = (dest = process.stdout.fd) => {
if (typeof dest === 'object') {
dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)
return buildSafeSonicBoom(dest)
} else {
return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })
}
}
module.exports.transport = __nccwpck_require__(96129)
module.exports.multistream = __nccwpck_require__(74411)
module.exports.levels = mappings()
module.exports.stdSerializers = serializers
module.exports.stdTimeFunctions = Object.assign({}, time)
module.exports.symbols = symbols
module.exports.version = version
// Enables default and name export with TypeScript and Babel
module.exports["default"] = pino
module.exports.pino = pino
/***/ }),
/***/ 2782:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const { format } = __nccwpck_require__(47261)
/**
* @namespace processWarning
*/
/**
* Represents a warning item with details.
* @typedef {Function} WarningItem
* @param {*} [a] Possible message interpolation value.
* @param {*} [b] Possible message interpolation value.
* @param {*} [c] Possible message interpolation value.
* @property {string} name - The name of the warning.
* @property {string} code - The code associated with the warning.
* @property {string} message - The warning message.
* @property {boolean} emitted - Indicates if the warning has been emitted.
* @property {function} format - Formats the warning message.
*/
/**
* Options for creating a process warning.
* @typedef {Object} ProcessWarningOptions
* @property {string} name - The name of the warning.
* @property {string} code - The code associated with the warning.
* @property {string} message - The warning message.
* @property {boolean} [unlimited=false] - If true, allows unlimited emissions of the warning.
*/
/**
* Represents the process warning functionality.
* @typedef {Object} ProcessWarning
* @property {function} createWarning - Creates a warning item.
* @property {function} createDeprecation - Creates a deprecation warning item.
*/
/**
* Creates a deprecation warning item.
* @function
* @memberof processWarning
* @param {ProcessWarningOptions} params - Options for creating the warning.
* @returns {WarningItem} The created deprecation warning item.
*/
function createDeprecation (params) {
return createWarning({ ...params, name: 'DeprecationWarning' })
}
/**
* Creates a warning item.
* @function
* @memberof processWarning
* @param {ProcessWarningOptions} params - Options for creating the warning.
* @returns {WarningItem} The created warning item.
* @throws {Error} Throws an error if name, code, or message is empty, or if opts.unlimited is not a boolean.
*/
function createWarning ({ name, code, message, unlimited = false } = {}) {
if (!name) throw new Error('Warning name must not be empty')
if (!code) throw new Error('Warning code must not be empty')
if (!message) throw new Error('Warning message must not be empty')
if (typeof unlimited !== 'boolean') throw new Error('Warning opts.unlimited must be a boolean')
code = code.toUpperCase()
let warningContainer = {
[name]: function (a, b, c) {
if (warning.emitted === true && warning.unlimited !== true) {
return
}
warning.emitted = true
process.emitWarning(warning.format(a, b, c), warning.name, warning.code)
}
}
if (unlimited) {
warningContainer = {
[name]: function (a, b, c) {
warning.emitted = true
process.emitWarning(warning.format(a, b, c), warning.name, warning.code)
}
}
}
const warning = warningContainer[name]
warning.emitted = false
warning.message = message
warning.unlimited = unlimited
warning.code = code
/**
* Formats the warning message.
* @param {*} [a] Possible message interpolation value.
* @param {*} [b] Possible message interpolation value.
* @param {*} [c] Possible message interpolation value.
* @returns {string} The formatted warning message.
*/
warning.format = function (a, b, c) {
let formatted
if (a && b && c) {
formatted = format(message, a, b, c)
} else if (a && b) {
formatted = format(message, a, b)
} else if (a) {
formatted = format(message, a)
} else {
formatted = message
}
return formatted
}
return warning
}
/**
* Module exports containing the process warning functionality.
* @namespace
* @property {function} createWarning - Creates a warning item.
* @property {function} createDeprecation - Creates a deprecation warning item.
* @property {ProcessWarning} processWarning - Represents the process warning functionality.
*/
const out = { createWarning, createDeprecation }
module.exports = out
module.exports["default"] = out
module.exports.processWarning = out
/***/ }),
/***/ 330:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fs = __nccwpck_require__(57147)
const EventEmitter = __nccwpck_require__(82361)
const inherits = (__nccwpck_require__(73837).inherits)
const path = __nccwpck_require__(71017)
const sleep = __nccwpck_require__(86950)
const BUSY_WRITE_TIMEOUT = 100
const kEmptyBuffer = Buffer.allocUnsafe(0)
// 16 KB. Don't write more than docker buffer size.
// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13
const MAX_WRITE = 16 * 1024
const kContentModeBuffer = 'buffer'
const kContentModeUtf8 = 'utf8'
function openFile (file, sonic) {
sonic._opening = true
sonic._writing = true
sonic._asyncDrainScheduled = false
// NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false
// for sync mode, there is no way to add a listener that will receive these
function fileOpened (err, fd) {
if (err) {
sonic._reopening = false
sonic._writing = false
sonic._opening = false
if (sonic.sync) {
process.nextTick(() => {
if (sonic.listenerCount('error') > 0) {
sonic.emit('error', err)
}
})
} else {
sonic.emit('error', err)
}
return
}
const reopening = sonic._reopening
sonic.fd = fd
sonic.file = file
sonic._reopening = false
sonic._opening = false
sonic._writing = false
if (sonic.sync) {
process.nextTick(() => sonic.emit('ready'))
} else {
sonic.emit('ready')
}
if (sonic.destroyed) {
return
}
// start
if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {
sonic._actualWrite()
} else if (reopening) {
process.nextTick(() => sonic.emit('drain'))
}
}
const flags = sonic.append ? 'a' : 'w'
const mode = sonic.mode
if (sonic.sync) {
try {
if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })
const fd = fs.openSync(file, flags, mode)
fileOpened(null, fd)
} catch (err) {
fileOpened(err)
throw err
}
} else if (sonic.mkdir) {
fs.mkdir(path.dirname(file), { recursive: true }, (err) => {
if (err) return fileOpened(err)
fs.open(file, flags, mode, fileOpened)
})
} else {
fs.open(file, flags, mode, fileOpened)
}
}
function SonicBoom (opts) {
if (!(this instanceof SonicBoom)) {
return new SonicBoom(opts)
}
let { fd, dest, minLength, maxLength, maxWrite, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}
fd = fd || dest
this._len = 0
this.fd = -1
this._bufs = []
this._lens = []
this._writing = false
this._ending = false
this._reopening = false
this._asyncDrainScheduled = false
this._flushPending = false
this._hwm = Math.max(minLength || 0, 16387)
this.file = null
this.destroyed = false
this.minLength = minLength || 0
this.maxLength = maxLength || 0
this.maxWrite = maxWrite || MAX_WRITE
this.sync = sync || false
this.writable = true
this._fsync = fsync || false
this.append = append || false
this.mode = mode
this.retryEAGAIN = retryEAGAIN || (() => true)
this.mkdir = mkdir || false
let fsWriteSync
let fsWrite
if (contentMode === kContentModeBuffer) {
this._writingBuf = kEmptyBuffer
this.write = writeBuffer
this.flush = flushBuffer
this.flushSync = flushBufferSync
this._actualWrite = actualWriteBuffer
fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)
fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)
} else if (contentMode === undefined || contentMode === kContentModeUtf8) {
this._writingBuf = ''
this.write = write
this.flush = flush
this.flushSync = flushSync
this._actualWrite = actualWrite
fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')
fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)
} else {
throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`)
}
if (typeof fd === 'number') {
this.fd = fd
process.nextTick(() => this.emit('ready'))
} else if (typeof fd === 'string') {
openFile(fd, this)
} else {
throw new Error('SonicBoom supports only file descriptors and files')
}
if (this.minLength >= this.maxWrite) {
throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)
}
this.release = (err, n) => {
if (err) {
if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {
if (this.sync) {
// This error code should not happen in sync mode, because it is
// not using the underlining operating system asynchronous functions.
// However it happens, and so we handle it.
// Ref: https://github.com/pinojs/pino/issues/783
try {
sleep(BUSY_WRITE_TIMEOUT)
this.release(undefined, 0)
} catch (err) {
this.release(err)
}
} else {
// Let's give the destination some time to process the chunk.
setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)
}
} else {
this._writing = false
this.emit('error', err)
}
return
}
this.emit('write', n)
const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)
this._len = releasedBufObj.len
this._writingBuf = releasedBufObj.writingBuf
if (this._writingBuf.length) {
if (!this.sync) {
fsWrite()
return
}
try {
do {
const n = fsWriteSync()
const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)
this._len = releasedBufObj.len
this._writingBuf = releasedBufObj.writingBuf
} while (this._writingBuf.length)
} catch (err) {
this.release(err)
return
}
}
if (this._fsync) {
fs.fsyncSync(this.fd)
}
const len = this._len
if (this._reopening) {
this._writing = false
this._reopening = false
this.reopen()
} else if (len > this.minLength) {
this._actualWrite()
} else if (this._ending) {
if (len > 0) {
this._actualWrite()
} else {
this._writing = false
actualClose(this)
}
} else {
this._writing = false
if (this.sync) {
if (!this._asyncDrainScheduled) {
this._asyncDrainScheduled = true
process.nextTick(emitDrain, this)
}
} else {
this.emit('drain')
}
}
}
this.on('newListener', function (name) {
if (name === 'drain') {
this._asyncDrainScheduled = false
}
})
}
/**
* Release the writingBuf after fs.write n bytes data
* @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.
* @param {number} len - currently buffer length, usually be instance._len.
* @param {number} n - number of bytes fs already written
* @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length
*/
function releaseWritingBuf (writingBuf, len, n) {
// if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character
if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {
// Since the fs.write callback parameter `n` means how many bytes the passed of string
// We calculate the original string length for avoiding the multi-byte character issue
n = Buffer.from(writingBuf).subarray(0, n).toString().length
}
len = Math.max(len - n, 0)
writingBuf = writingBuf.slice(n)
return { writingBuf, len }
}
function emitDrain (sonic) {
const hasListeners = sonic.listenerCount('drain') > 0
if (!hasListeners) return
sonic._asyncDrainScheduled = false
sonic.emit('drain')
}
inherits(SonicBoom, EventEmitter)
function mergeBuf (bufs, len) {
if (bufs.length === 0) {
return kEmptyBuffer
}
if (bufs.length === 1) {
return bufs[0]
}
return Buffer.concat(bufs, len)
}
function write (data) {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
const len = this._len + data.length
const bufs = this._bufs
if (this.maxLength && len > this.maxLength) {
this.emit('drop', data)
return this._len < this._hwm
}
if (
bufs.length === 0 ||
bufs[bufs.length - 1].length + data.length > this.maxWrite
) {
bufs.push('' + data)
} else {
bufs[bufs.length - 1] += data
}
this._len = len
if (!this._writing && this._len >= this.minLength) {
this._actualWrite()
}
return this._len < this._hwm
}
function writeBuffer (data) {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
const len = this._len + data.length
const bufs = this._bufs
const lens = this._lens
if (this.maxLength && len > this.maxLength) {
this.emit('drop', data)
return this._len < this._hwm
}
if (
bufs.length === 0 ||
lens[lens.length - 1] + data.length > this.maxWrite
) {
bufs.push([data])
lens.push(data.length)
} else {
bufs[bufs.length - 1].push(data)
lens[lens.length - 1] += data.length
}
this._len = len
if (!this._writing && this._len >= this.minLength) {
this._actualWrite()
}
return this._len < this._hwm
}
function callFlushCallbackOnDrain (cb) {
this._flushPending = true
const onDrain = () => {
// only if _fsync is false to avoid double fsync
if (!this._fsync) {
fs.fsync(this.fd, (err) => {
this._flushPending = false
cb(err)
})
} else {
this._flushPending = false
cb()
}
this.off('error', onError)
}
const onError = (err) => {
this._flushPending = false
cb(err)
this.off('drain', onDrain)
}
this.once('drain', onDrain)
this.once('error', onError)
}
function flush (cb) {
if (cb != null && typeof cb !== 'function') {
throw new Error('flush cb must be a function')
}
if (this.destroyed) {
const error = new Error('SonicBoom destroyed')
if (cb) {
cb(error)
return
}
throw error
}
if (this.minLength <= 0) {
cb?.()
return
}
if (cb) {
callFlushCallbackOnDrain.call(this, cb)
}
if (this._writing) {
return
}
if (this._bufs.length === 0) {
this._bufs.push('')
}
this._actualWrite()
}
function flushBuffer (cb) {
if (cb != null && typeof cb !== 'function') {
throw new Error('flush cb must be a function')
}
if (this.destroyed) {
const error = new Error('SonicBoom destroyed')
if (cb) {
cb(error)
return
}
throw error
}
if (this.minLength <= 0) {
cb?.()
return
}
if (cb) {
callFlushCallbackOnDrain.call(this, cb)
}
if (this._writing) {
return
}
if (this._bufs.length === 0) {
this._bufs.push([])
this._lens.push(0)
}
this._actualWrite()
}
SonicBoom.prototype.reopen = function (file) {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
if (this._opening) {
this.once('ready', () => {
this.reopen(file)
})
return
}
if (this._ending) {
return
}
if (!this.file) {
throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')
}
if (file) {
this.file = file
}
this._reopening = true
if (this._writing) {
return
}
const fd = this.fd
this.once('ready', () => {
if (fd !== this.fd) {
fs.close(fd, (err) => {
if (err) {
return this.emit('error', err)
}
})
}
})
openFile(this.file, this)
}
SonicBoom.prototype.end = function () {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
if (this._opening) {
this.once('ready', () => {
this.end()
})
return
}
if (this._ending) {
return
}
this._ending = true
if (this._writing) {
return
}
if (this._len > 0 && this.fd >= 0) {
this._actualWrite()
} else {
actualClose(this)
}
}
function flushSync () {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
if (this.fd < 0) {
throw new Error('sonic boom is not ready yet')
}
if (!this._writing && this._writingBuf.length > 0) {
this._bufs.unshift(this._writingBuf)
this._writingBuf = ''
}
let buf = ''
while (this._bufs.length || buf) {
if (buf.length <= 0) {
buf = this._bufs[0]
}
try {
const n = fs.writeSync(this.fd, buf, 'utf8')
const releasedBufObj = releaseWritingBuf(buf, this._len, n)
buf = releasedBufObj.writingBuf
this._len = releasedBufObj.len
if (buf.length <= 0) {
this._bufs.shift()
}
} catch (err) {
const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'
if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
throw err
}
sleep(BUSY_WRITE_TIMEOUT)
}
}
try {
fs.fsyncSync(this.fd)
} catch {
// Skip the error. The fd might not support fsync.
}
}
function flushBufferSync () {
if (this.destroyed) {
throw new Error('SonicBoom destroyed')
}
if (this.fd < 0) {
throw new Error('sonic boom is not ready yet')
}
if (!this._writing && this._writingBuf.length > 0) {
this._bufs.unshift([this._writingBuf])
this._writingBuf = kEmptyBuffer
}
let buf = kEmptyBuffer
while (this._bufs.length || buf.length) {
if (buf.length <= 0) {
buf = mergeBuf(this._bufs[0], this._lens[0])
}
try {
const n = fs.writeSync(this.fd, buf)
buf = buf.subarray(n)
this._len = Math.max(this._len - n, 0)
if (buf.length <= 0) {
this._bufs.shift()
this._lens.shift()
}
} catch (err) {
const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'
if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
throw err
}
sleep(BUSY_WRITE_TIMEOUT)
}
}
}
SonicBoom.prototype.destroy = function () {
if (this.destroyed) {
return
}
actualClose(this)
}
function actualWrite () {
const release = this.release
this._writing = true
this._writingBuf = this._writingBuf || this._bufs.shift() || ''
if (this.sync) {
try {
const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')
release(null, written)
} catch (err) {
release(err)
}
} else {
fs.write(this.fd, this._writingBuf, 'utf8', release)
}
}
function actualWriteBuffer () {
const release = this.release
this._writing = true
this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())
if (this.sync) {
try {
const written = fs.writeSync(this.fd, this._writingBuf)
release(null, written)
} catch (err) {
release(err)
}
} else {
fs.write(this.fd, this._writingBuf, release)
}
}
function actualClose (sonic) {
if (sonic.fd === -1) {
sonic.once('ready', actualClose.bind(null, sonic))
return
}
sonic.destroyed = true
sonic._bufs = []
sonic._lens = []
fs.fsync(sonic.fd, closeWrapped)
function closeWrapped () {
// We skip errors in fsync
if (sonic.fd !== 1 && sonic.fd !== 2) {
fs.close(sonic.fd, done)
} else {
done()
}
}
function done (err) {
if (err) {
sonic.emit('error', err)
return
}
if (sonic._ending && !sonic._writing) {
sonic.emit('finish')
}
sonic.emit('close')
}
}
/**
* These export configurations enable JS and TS developers
* to consumer SonicBoom in whatever way best suits their needs.
* Some examples of supported import syntax includes:
* - `const SonicBoom = require('SonicBoom')`
* - `const { SonicBoom } = require('SonicBoom')`
* - `import * as SonicBoom from 'SonicBoom'`
* - `import { SonicBoom } from 'SonicBoom'`
* - `import SonicBoom from 'SonicBoom'`
*/
SonicBoom.SonicBoom = SonicBoom
SonicBoom.default = SonicBoom
module.exports = SonicBoom
/***/ }),
/***/ 88757:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// Axios v1.7.2 Copyright (c) 2024 Matt Zabriskie and contributors
const FormData$1 = __nccwpck_require__(64334);
const url = __nccwpck_require__(57310);
const proxyFromEnv = __nccwpck_require__(63329);
const http = __nccwpck_require__(13685);
const https = __nccwpck_require__(95687);
const util = __nccwpck_require__(73837);
const followRedirects = __nccwpck_require__(67707);
const zlib = __nccwpck_require__(59796);
const stream = __nccwpck_require__(12781);
const events = __nccwpck_require__(82361);
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1);
const url__default = /*#__PURE__*/_interopDefaultLegacy(url);
const http__default = /*#__PURE__*/_interopDefaultLegacy(http);
const https__default = /*#__PURE__*/_interopDefaultLegacy(https);
const util__default = /*#__PURE__*/_interopDefaultLegacy(util);
const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects);
const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream);
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const {toString} = Object.prototype;
const {getPrototypeOf} = Object;
const kindOf = (cache => thing => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type
};
const typeOfTest = type => thing => typeof thing === type;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const {isArray} = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = thing => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = (val) => {
if (kindOf(val) !== 'object') {
return false;
}
const prototype = getPrototypeOf(val);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject(val) && isFunction(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
const isFormData = (thing) => {
let kind;
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) || (
isFunction(thing.append) && (
(kind = kindOf(thing)) === 'formdata' ||
// detect form-data instance
(kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
)
)
)
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => str.trim ?
str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Boolean} [allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, {allOwnKeys = false} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
const {caseless} = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result, key) || key;
if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
result[targetKey] = merge(result[targetKey], val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else {
result[targetKey] = val;
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Boolean} [allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, {allOwnKeys});
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, 'super', {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = (TypedArray => {
// eslint-disable-next-line func-names
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[Symbol.iterator];
const iterator = generator.call(obj);
let result;
while ((result = iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
return false;
}
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error('Can not rewrite read-only method \'' + name + '\'');
};
}
});
};
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach(value => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
const DIGIT = '0123456789';
const ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = '';
const {length} = alphabet;
while (size--) {
str += alphabet[Math.random() * length|0];
}
return str;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
}
const toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if(!('toJSON' in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = undefined;
return target;
}
}
return source;
};
return visit(obj, 0);
};
const isAsyncFn = kindOfTest('AsyncFunction');
const isThenable = (thing) =>
thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
const utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
ALPHABET,
generateString,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable
};
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error()).stack;
}
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils$1.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils$1.toJSONObject(this.config),
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
const prototype$1 = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED',
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(code => {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype$1);
utils$1.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData__default["default"] || FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
}
return value;
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (value && !path && typeof value === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = JSON.stringify(value);
} else if (
(utils$1.isArray(value) && isFlatArray(value)) ||
((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
)) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
if (utils$1.isUndefined(value)) return;
if (stack.indexOf(value) !== -1) {
throw Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
);
if (result === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode$1);
} : encode$1;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
* URI encoded counterparts
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?object} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
const _encode = options && options.encode || encode;
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils$1.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
const InterceptorManager$1 = InterceptorManager;
const transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
const URLSearchParams = url__default["default"].URLSearchParams;
const platform$1 = {
isNode: true,
classes: {
URLSearchParams,
FormData: FormData__default["default"],
Blob: typeof Blob !== 'undefined' && Blob || null
},
protocols: [ 'http', 'https', 'file', 'data' ]
};
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv = (
(product) => {
return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0
})(typeof navigator !== 'undefined' && navigator.product);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
const origin = hasBrowserEnv && window.location.href || 'http://localhost';
const utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
origin: origin
});
const platform = {
...utils,
...platform$1
};
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
visitor: function(value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!target[name] || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils$1.isArrayBuffer(data) ||
utils$1.isBuffer(data) ||
utils$1.isStream(data) ||
utils$1.isFile(data) ||
utils$1.isBlob(data) ||
utils$1.isReadableStream(data)
) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType ) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': undefined
}
}
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
defaults.headers[method] = {};
});
const defaults$1 = defaults;
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet([
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
const parseHeaders = rawHeaders => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = utils$1.findKey(self, lHeader);
if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isHeaders(header)) {
for (const [key, value] of header.entries()) {
setHeader(value, key, rewrite);
}
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils$1.forEach(this, (value, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils$1.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
}
}
});
utils$1.freezeMethods(AxiosHeaders);
const AxiosHeaders$1 = AxiosHeaders;
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults$1;
const context = response || config;
const headers = AxiosHeaders$1.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
function CanceledError(message, config, request) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
}
utils$1.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
}
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
const VERSION = "1.7.2";
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
}
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
*
* @param {String} uri
* @param {?Boolean} asBlob
* @param {?Object} options
* @param {?Function} options.Blob
*
* @returns {Buffer|Blob}
*/
function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
}
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
const mime = match[1];
const isBase64 = match[2];
const body = match[3];
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
if (asBlob) {
if (!_Blob) {
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
}
return new _Blob([buffer], {type: mime});
}
return buffer;
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
const threshold = 1000 / freq;
let timer = null;
return function throttled() {
const force = this === true;
const now = Date.now();
if (force || now - timestamp > threshold) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timestamp = now;
return fn.apply(null, arguments);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
return fn.apply(null, arguments);
}, threshold - (now - timestamp));
}
};
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream__default["default"].Transform{
constructor(options) {
options = utils$1.toFlatObject(options, {
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15
}, null, (prop, source) => {
return !utils$1.isUndefined(source[prop]);
});
super({
readableHighWaterMark: options.chunkSize
});
const self = this;
const internals = this[kInternals] = {
length: options.length,
timeWindow: options.timeWindow,
ticksRate: options.ticksRate,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
this.on('newListener', event => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
let bytesNotified = 0;
internals.updateProgress = throttle(function throttledHandler() {
const totalBytes = internals.length;
const bytesTransferred = internals.bytesSeen;
const progressBytes = bytesTransferred - bytesNotified;
if (!progressBytes || self.destroyed) return;
const rate = _speedometer(progressBytes);
bytesNotified = bytesTransferred;
process.nextTick(() => {
self.emit('progress', {
loaded: bytesTransferred,
total: totalBytes,
progress: totalBytes ? (bytesTransferred / totalBytes) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && totalBytes && bytesTransferred <= totalBytes ?
(totalBytes - bytesTransferred) / rate : undefined,
lengthComputable: totalBytes != null
});
});
}, internals.ticksRate);
const onFinish = () => {
internals.updateProgress.call(true);
};
this.once('end', onFinish);
this.once('error', onFinish);
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const self = this;
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = (maxRate / divider);
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
function pushChunk(_chunk, _callback) {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
if (internals.isCaptured) {
internals.updateProgress();
}
if (self.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
}
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(_chunk, chunkRemainder ? () => {
process.nextTick(_callback, null, chunkRemainder);
} : _callback);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
setLength(length) {
this[kInternals].length = +length;
return this;
}
}
const AxiosTransformStream$1 = AxiosTransformStream;
const {asyncIterator} = Symbol;
const readBlob = async function* (blob) {
if (blob.stream) {
yield* blob.stream();
} else if (blob.arrayBuffer) {
yield await blob.arrayBuffer();
} else if (blob[asyncIterator]) {
yield* blob[asyncIterator]();
} else {
yield blob;
}
};
const readBlob$1 = readBlob;
const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_';
const textEncoder = new util.TextEncoder();
const CRLF = '\r\n';
const CRLF_BYTES = textEncoder.encode(CRLF);
const CRLF_BYTES_COUNT = 2;
class FormDataPart {
constructor(name, value) {
const {escapeName} = this.constructor;
const isStringValue = utils$1.isString(value);
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''
}${CRLF}`;
if (isStringValue) {
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
}
this.headers = textEncoder.encode(headers + CRLF);
this.contentLength = isStringValue ? value.byteLength : value.size;
this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
this.name = name;
this.value = value;
}
async *encode(){
yield this.headers;
const {value} = this;
if(utils$1.isTypedArray(value)) {
yield value;
} else {
yield* readBlob$1(value);
}
yield CRLF_BYTES;
}
static escapeName(name) {
return String(name).replace(/[\r\n"]/g, (match) => ({
'\r' : '%0D',
'\n' : '%0A',
'"' : '%22',
}[match]));
}
}
const formDataToStream = (form, headersHandler, options) => {
const {
tag = 'form-data-boundary',
size = 25,
boundary = tag + '-' + utils$1.generateString(size, BOUNDARY_ALPHABET)
} = options || {};
if(!utils$1.isFormData(form)) {
throw TypeError('FormData instance required');
}
if (boundary.length < 1 || boundary.length > 70) {
throw Error('boundary must be 10-70 characters long')
}
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF);
let contentLength = footerBytes.byteLength;
const parts = Array.from(form.entries()).map(([name, value]) => {
const part = new FormDataPart(name, value);
contentLength += part.size;
return part;
});
contentLength += boundaryBytes.byteLength * parts.length;
contentLength = utils$1.toFiniteNumber(contentLength);
const computedHeaders = {
'Content-Type': `multipart/form-data; boundary=${boundary}`
};
if (Number.isFinite(contentLength)) {
computedHeaders['Content-Length'] = contentLength;
}
headersHandler && headersHandler(computedHeaders);
return stream.Readable.from((async function *() {
for(const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
yield footerBytes;
})());
};
const formDataToStream$1 = formDataToStream;
class ZlibHeaderTransformStream extends stream__default["default"].Transform {
__transform(chunk, encoding, callback) {
this.push(chunk);
callback();
}
_transform(chunk, encoding, callback) {
if (chunk.length !== 0) {
this._transform = this.__transform;
// Add Default Compression headers if no zlib headers are present
if (chunk[0] !== 120) { // Hex: 78
const header = Buffer.alloc(2);
header[0] = 120; // Hex: 78
header[1] = 156; // Hex: 9C
this.push(header, encoding);
}
}
this.__transform(chunk, encoding, callback);
}
}
const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream;
const callbackify = (fn, reducer) => {
return utils$1.isAsyncFn(fn) ? function (...args) {
const cb = args.pop();
fn.apply(this, args).then((value) => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
}
}, cb);
} : fn;
};
const callbackify$1 = callbackify;
const zlibOptions = {
flush: zlib__default["default"].constants.Z_SYNC_FLUSH,
finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
};
const brotliOptions = {
flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH
};
const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress);
const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"];
const isHttps = /https:?/;
const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
/**
* If the proxy or config beforeRedirects functions are defined, call them with the options
* object.
*
* @param {Object<string, any>} options - The options object that was passed to the request.
*
* @returns {Object<string, any>}
*/
function dispatchBeforeRedirect(options, responseDetails) {
if (options.beforeRedirects.proxy) {
options.beforeRedirects.proxy(options);
}
if (options.beforeRedirects.config) {
options.beforeRedirects.config(options, responseDetails);
}
}
/**
* If the proxy or config afterRedirects functions are defined, call them with the options
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} configProxy configuration from Axios options object
* @param {string} location
*
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location) {
let proxy = configProxy;
if (!proxy && proxy !== false) {
const proxyUrl = proxyFromEnv.getProxyForUrl(location);
if (proxyUrl) {
proxy = new URL(proxyUrl);
}
}
if (proxy) {
// Basic proxy authorization
if (proxy.username) {
proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
}
if (proxy.auth) {
// Support proxy auth object form
if (proxy.auth.username || proxy.auth.password) {
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
}
const base64 = Buffer
.from(proxy.auth, 'utf8')
.toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
const proxyHost = proxy.hostname || proxy.host;
options.hostname = proxyHost;
// Replace 'host' since options is not a URL object
options.host = proxyHost;
options.port = proxy.port;
options.path = location;
if (proxy.protocol) {
options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
}
}
options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
// Configure proxy for redirected request, passing the original config proxy to apply
// the exact same logic as if the redirected request was performed by axios directly.
setProxy(redirectOptions, configProxy, redirectOptions.href);
};
}
const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
// temporary hotfix
const wrapAsync = (asyncExecutor) => {
return new Promise((resolve, reject) => {
let onDone;
let isDone;
const done = (value, isRejected) => {
if (isDone) return;
isDone = true;
onDone && onDone(value, isRejected);
};
const _resolve = (value) => {
done(value);
resolve(value);
};
const _reject = (reason) => {
done(reason, true);
reject(reason);
};
asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
})
};
const resolveFamily = ({address, family}) => {
if (!utils$1.isString(address)) {
throw TypeError('address must be a string');
}
return ({
address,
family: family || (address.indexOf('.') < 0 ? 6 : 4)
});
};
const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family});
/*eslint consistent-return:0*/
const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
let {data, lookup, family} = config;
const {responseType, responseEncoding} = config;
const method = config.method.toUpperCase();
let isDone;
let rejected = false;
let req;
if (lookup) {
const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]);
// hotfix to support opt.all option which is required for node 20.x
lookup = (hostname, opt, cb) => {
_lookup(hostname, opt, (err, arg0, arg1) => {
if (err) {
return cb(err);
}
const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
});
};
}
// temporary internal emitter until the AxiosRequest class will be implemented
const emitter = new events.EventEmitter();
const onFinished = () => {
if (config.cancelToken) {
config.cancelToken.unsubscribe(abort);
}
if (config.signal) {
config.signal.removeEventListener('abort', abort);
}
emitter.removeAllListeners();
};
onDone((value, isRejected) => {
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
}
});
function abort(reason) {
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
}
emitter.once('abort', reject);
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
// Parse url
const fullPath = buildFullPath(config.baseURL, config.url);
const parsed = new URL(fullPath, 'http://localhost');
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config
});
}
try {
convertedData = fromDataURI(config.url, responseType === 'blob', {
Blob: config.env && config.env.Blob
});
} catch (err) {
throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
}
if (responseType === 'text') {
convertedData = convertedData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
convertedData = utils$1.stripBOM(convertedData);
}
} else if (responseType === 'stream') {
convertedData = stream__default["default"].Readable.from(convertedData);
}
return settle(resolve, reject, {
data: convertedData,
status: 200,
statusText: 'OK',
headers: new AxiosHeaders$1(),
config
});
}
if (supportedProtocols.indexOf(protocol) === -1) {
return reject(new AxiosError(
'Unsupported protocol ' + protocol,
AxiosError.ERR_BAD_REQUEST,
config
));
}
const headers = AxiosHeaders$1.from(config.headers).normalize();
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
// User-Agent is specified; handle case where no UA header is desired
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const onDownloadProgress = config.onDownloadProgress;
const onUploadProgress = config.onUploadProgress;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for spec compliant FormData objects
if (utils$1.isSpecCompliantForm(data)) {
const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
data = formDataToStream$1(data, (formHeaders) => {
headers.set(formHeaders);
}, {
tag: `axios-${VERSION}-boundary`,
boundary: userBoundary && userBoundary[1] || undefined
});
// support for https://www.npmjs.com/package/form-data api
} else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) {
headers.set(data.getHeaders());
if (!headers.hasContentLength()) {
try {
const knownLength = await util__default["default"].promisify(data.getLength).call(data);
Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
/*eslint no-empty:0*/
} catch (e) {
}
}
} else if (utils$1.isBlob(data)) {
data.size && headers.setContentType(data.type || 'application/octet-stream');
headers.setContentLength(data.size || 0);
data = stream__default["default"].Readable.from(readBlob$1(data));
} else if (data && !utils$1.isStream(data)) {
if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
data = Buffer.from(new Uint8Array(data));
} else if (utils$1.isString(data)) {
data = Buffer.from(data, 'utf-8');
} else {
return reject(new AxiosError(
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
AxiosError.ERR_BAD_REQUEST,
config
));
}
// Add Content-Length header if data exists
headers.setContentLength(data.length, false);
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
return reject(new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config
));
}
}
const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
if (utils$1.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils$1.isStream(data)) {
data = stream__default["default"].Readable.from(data, {objectMode: false});
}
data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({
length: contentLength,
maxRate: utils$1.toFiniteNumber(maxUploadRate)
})], utils$1.noop);
onUploadProgress && data.on('progress', progress => {
onUploadProgress(Object.assign(progress, {
upload: true
}));
});
}
// HTTP basic authentication
let auth = undefined;
if (config.auth) {
const username = config.auth.username || '';
const password = config.auth.password || '';
auth = username + ':' + password;
}
if (!auth && parsed.username) {
const urlUsername = parsed.username;
const urlPassword = parsed.password;
auth = urlUsername + ':' + urlPassword;
}
auth && headers.delete('authorization');
let path;
try {
path = buildURL(
parsed.pathname + parsed.search,
config.params,
config.paramsSerializer
).replace(/^\?/, '');
} catch (err) {
const customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
return reject(customErr);
}
headers.set(
'Accept-Encoding',
'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
);
const options = {
path,
method: method,
headers: headers.toJSON(),
agents: { http: config.httpAgent, https: config.httpsAgent },
auth,
protocol,
family,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: {}
};
// cacheable-lookup integration hotfix
!utils$1.isUndefined(lookup) && (options.lookup = lookup);
if (config.socketPath) {
options.socketPath = config.socketPath;
} else {
options.hostname = parsed.hostname;
options.port = parsed.port;
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
let transport;
const isHttpsRequest = isHttps.test(options.protocol);
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
if (config.transport) {
transport = config.transport;
} else if (config.maxRedirects === 0) {
transport = isHttpsRequest ? https__default["default"] : http__default["default"];
} else {
if (config.maxRedirects) {
options.maxRedirects = config.maxRedirects;
}
if (config.beforeRedirect) {
options.beforeRedirects.config = config.beforeRedirect;
}
transport = isHttpsRequest ? httpsFollow : httpFollow;
}
if (config.maxBodyLength > -1) {
options.maxBodyLength = config.maxBodyLength;
} else {
// follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
options.maxBodyLength = Infinity;
}
if (config.insecureHTTPParser) {
options.insecureHTTPParser = config.insecureHTTPParser;
}
// Create the request
req = transport.request(options, function handleResponse(res) {
if (req.destroyed) return;
const streams = [res];
const responseLength = +res.headers['content-length'];
if (onDownloadProgress) {
const transformStream = new AxiosTransformStream$1({
length: utils$1.toFiniteNumber(responseLength),
maxRate: utils$1.toFiniteNumber(maxDownloadRate)
});
onDownloadProgress && transformStream.on('progress', progress => {
onDownloadProgress(Object.assign(progress, {
download: true
}));
});
streams.push(transformStream);
}
// decompress the response body transparently if required
let responseStream = res;
// return the last request in case of redirects
const lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (config.decompress !== false && res.headers['content-encoding']) {
// if no content, but headers still say that it is encoded,
// remove the header not confuse downstream operations
if (method === 'HEAD' || res.statusCode === 204) {
delete res.headers['content-encoding'];
}
switch ((res.headers['content-encoding'] || '').toLowerCase()) {
/*eslint default-case:0*/
case 'gzip':
case 'x-gzip':
case 'compress':
case 'x-compress':
// add the unzipper to the body stream processing pipeline
streams.push(zlib__default["default"].createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'deflate':
streams.push(new ZlibHeaderTransformStream$1());
// add the unzipper to the body stream processing pipeline
streams.push(zlib__default["default"].createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions));
delete res.headers['content-encoding'];
}
}
}
responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0];
const offListeners = stream__default["default"].finished(responseStream, () => {
offListeners();
onFinished();
});
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: new AxiosHeaders$1(res.headers),
config,
request: lastRequest
};
if (responseType === 'stream') {
response.data = responseStream;
settle(resolve, reject, response);
} else {
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
// make sure the content length is not over the maxContentLength if specified
if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
// stream.destroy() emit aborted event before calling reject() on Node.js v16
rejected = true;
responseStream.destroy();
reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
}
});
responseStream.on('aborted', function handlerStreamAborted() {
if (rejected) {
return;
}
const err = new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
);
responseStream.destroy(err);
reject(err);
});
responseStream.on('error', function handleStreamError(err) {
if (req.destroyed) return;
reject(AxiosError.from(err, null, config, lastRequest));
});
responseStream.on('end', function handleStreamEnd() {
try {
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
responseData = utils$1.stripBOM(responseData);
}
}
response.data = responseData;
} catch (err) {
return reject(AxiosError.from(err, null, config, response.request, response));
}
settle(resolve, reject, response);
});
}
emitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
emitter.once('abort', err => {
reject(err);
req.destroy(err);
});
// Handle errors
req.on('error', function handleRequestError(err) {
// @todo remove
// if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
reject(AxiosError.from(err, null, config, req));
});
// set tcp keep alive to prevent drop connection by peer
req.on('socket', function handleRequestSocket(socket) {
// default interval of sending ack packet is 1 minute
socket.setKeepAlive(true, 1000 * 60);
});
// Handle request timeout
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
const timeout = parseInt(config.timeout, 10);
if (Number.isNaN(timeout)) {
reject(new AxiosError(
'error trying to parse `config.timeout` to int',
AxiosError.ERR_BAD_OPTION_VALUE,
config,
req
));
return;
}
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
// And then these socket which be hang up will devouring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, function handleRequestTimeout() {
if (isDone) return;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
req
));
abort();
});
}
// Send the request
if (utils$1.isStream(data)) {
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', err => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
data.pipe(req);
} else {
req.end(data);
}
});
};
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle(e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null
};
data[isDownloadStream ? 'download' : 'upload'] = true;
listener(data);
}, freq);
};
const isURLSameOrigin = platform.hasStandardBrowserEnv ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
const msie = /(msie|trident)/i.test(navigator.userAgent);
const urlParsingNode = document.createElement('a');
let originURL;
/**
* Parse a URL to discover its components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
let href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})();
const cookies = platform.hasStandardBrowserEnv ?
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + '=' + encodeURIComponent(value)];
utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
utils$1.isString(path) && cookie.push('path=' + path);
utils$1.isString(domain) && cookie.push('domain=' + domain);
secure === true && cookie.push('secure');
document.cookie = cookie.join('; ');
},
read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove(name) {
this.write(name, '', Date.now() - 86400000);
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({caseless}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
}
const resolveConfig = (config) => {
const newConfig = mergeConfig({}, config);
let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
newConfig.headers = headers = AxiosHeaders$1.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
// HTTP basic authentication
if (auth) {
headers.set('Authorization', 'Basic ' +
btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
);
}
let contentType;
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
headers.setContentType(undefined); // Let the browser set it
} else if ((contentType = headers.getContentType()) !== false) {
// fix semicolon duplication issue for ReactNative FormData implementation
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
// Add xsrf header
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
};
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
const xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
let {responseType} = _config;
let onCanceled;
function done() {
if (_config.cancelToken) {
_config.cancelToken.unsubscribe(onCanceled);
}
if (_config.signal) {
_config.signal.removeEventListener('abort', onCanceled);
}
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders$1.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, _config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, _config, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
_config,
request));
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (typeof _config.onDownloadProgress === 'function') {
request.addEventListener('progress', progressEventReducer(_config.onDownloadProgress, true));
}
// Not all browsers support upload events
if (typeof _config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', progressEventReducer(_config.onUploadProgress));
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
let controller = new AbortController();
let aborted;
const onabort = function (cancel) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = cancel instanceof Error ? cancel : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
let timer = timeout && setTimeout(() => {
onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach(signal => {
signal &&
(signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
});
signals = null;
}
};
signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));
const {signal} = controller;
signal.unsubscribe = unsubscribe;
return [signal, () => {
timer && clearTimeout(timer);
timer = null;
}];
};
const composeSignals$1 = composeSignals;
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize, encode) {
for await (const chunk of iterable) {
yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize);
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
const iterator = readBytes(stream, chunkSize, encode);
let bytes = 0;
return new ReadableStream({
type: 'bytes',
async pull(controller) {
const {done, value} = await iterator.next();
if (done) {
controller.close();
onFinish();
return;
}
let len = value.byteLength;
onProgress && onProgress(bytes += len);
controller.enqueue(new Uint8Array(value));
},
cancel(reason) {
onFinish(reason);
return iterator.return();
}
}, {
highWaterMark: 2
})
};
const fetchProgressDecorator = (total, fn) => {
const lengthComputable = total != null;
return (loaded) => setTimeout(() => fn({
lengthComputable,
total,
loaded
}));
};
const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
// used only inside the fetch adapter
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
async (str) => new Uint8Array(await new Response(str).arrayBuffer())
);
const supportsRequestStream = isReadableStreamSupported && (() => {
let duplexAccessed = false;
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
return duplexAccessed && !hasContentType;
})();
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const supportsResponseStream = isReadableStreamSupported && !!(()=> {
try {
return utils$1.isReadableStream(new Response('').body);
} catch(err) {
// return undefined
}
})();
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && (((res) => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
!resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
(_, config) => {
throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
});
});
})(new Response));
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if(utils$1.isBlob(body)) {
return body.size;
}
if(utils$1.isSpecCompliantForm(body)) {
return (await new Request(body).arrayBuffer()).byteLength;
}
if(utils$1.isArrayBufferView(body)) {
return body.byteLength;
}
if(utils$1.isURLSearchParams(body)) {
body = body + '';
}
if(utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
const fetchAdapter = isFetchSupported && (async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions
} = resolveConfig(config);
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?
composeSignals$1([signal, cancelToken], timeout) : [];
let finished, request;
const onFinish = () => {
!finished && setTimeout(() => {
composedSignal && composedSignal.unsubscribe();
});
finished = true;
};
let requestContentLength;
try {
if (
onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
(requestContentLength = await resolveBodyLength(headers, data)) !== 0
) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: "half"
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator(
requestContentLength,
progressEventReducer(onUploadProgress)
), null, encodeText);
}
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'cors' : 'omit';
}
request = new Request(url, {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
withCredentials
});
let response = await fetch(request);
const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {
const options = {};
['status', 'statusText', 'headers'].forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator(
responseContentLength,
progressEventReducer(onDownloadProgress, true)
), isStreamResponse && onFinish, encodeText),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
!isStreamResponse && onFinish();
stopTimeout && stopTimeout();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders$1.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
})
} catch (err) {
onFinish();
if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
throw Object.assign(
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
{
cause: err.cause || err
}
)
}
throw AxiosError.from(err, err && err.code, config, request);
}
});
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: fetchAdapter
};
utils$1.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
Object.defineProperty(fn, 'name', {value});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
}
});
const renderReason = (reason) => `- ${reason}`;
const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
const adapters = {
getAdapter: (adapters) => {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
const {length} = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons)
.map(([id, state]) => `adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length ?
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
'ERR_NOT_SUPPORT'
);
}
return adapter;
},
adapters: knownAdapters
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders$1.from(config.headers);
// Transform request data
config.data = transformData.call(
config,
config.transformRequest
);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
config.transformResponse,
response
);
response.headers = AxiosHeaders$1.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
const validator = schema[opt];
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
const validator = {
assertOptions,
validators: validators$1
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager$1(),
response: new InterceptorManager$1()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy;
Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
// slice off the Error: ... line
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
err.stack += '\n' + stack;
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const {transitional, paramsSerializer, headers} = config;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
}
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils$1.merge(
headers.common,
headers[config.method]
);
headers && utils$1.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url,
data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
const Axios$1 = Axios;
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then(cancel => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
}
const CancelToken$1 = CancelToken;
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils$1.isObject(payload) && (payload.isAxiosError === true);
}
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
const HttpStatusCode$1 = HttpStatusCode;
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios$1(defaultConfig);
const instance = bind(Axios$1.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
// Copy context to instance
utils$1.extend(instance, context, null, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults$1);
// Expose Axios class to allow class inheritance
axios.Axios = Axios$1;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
module.exports = axios;
//# sourceMappingURL=axios.cjs.map
/***/ }),
/***/ 76420:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/**
* toad-cache
*
* @copyright 2024 Igor Savin <kibertoad@gmail.com>
* @license MIT
* @version 3.7.0
*/
class FifoMap {
constructor(max = 1000, ttlInMsecs = 0) {
if (isNaN(max) || max < 0) {
throw new Error('Invalid max value')
}
if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
throw new Error('Invalid ttl value')
}
this.first = null;
this.items = new Map();
this.last = null;
this.max = max;
this.ttl = ttlInMsecs;
}
get size() {
return this.items.size
}
clear() {
this.items = new Map();
this.first = null;
this.last = null;
}
delete(key) {
if (this.items.has(key)) {
const deletedItem = this.items.get(key);
this.items.delete(key);
if (deletedItem.prev !== null) {
deletedItem.prev.next = deletedItem.next;
}
if (deletedItem.next !== null) {
deletedItem.next.prev = deletedItem.prev;
}
if (this.first === deletedItem) {
this.first = deletedItem.next;
}
if (this.last === deletedItem) {
this.last = deletedItem.prev;
}
}
}
deleteMany(keys) {
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
evict() {
if (this.size > 0) {
const item = this.first;
this.items.delete(item.key);
if (this.size === 0) {
this.first = null;
this.last = null;
} else {
this.first = item.next;
this.first.prev = null;
}
}
}
expiresAt(key) {
if (this.items.has(key)) {
return this.items.get(key).expiry
}
}
get(key) {
if (this.items.has(key)) {
const item = this.items.get(key);
if (this.ttl > 0 && item.expiry <= Date.now()) {
this.delete(key);
return
}
return item.value
}
}
getMany(keys) {
const result = [];
for (var i = 0; i < keys.length; i++) {
result.push(this.get(keys[i]));
}
return result
}
keys() {
return this.items.keys()
}
set(key, value) {
// Replace existing item
if (this.items.has(key)) {
const item = this.items.get(key);
item.value = value;
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
return
}
// Add new item
if (this.max > 0 && this.size === this.max) {
this.evict();
}
const item = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
this.items.set(key, item);
if (this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
}
class LruMap {
constructor(max = 1000, ttlInMsecs = 0) {
if (isNaN(max) || max < 0) {
throw new Error('Invalid max value')
}
if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
throw new Error('Invalid ttl value')
}
this.first = null;
this.items = new Map();
this.last = null;
this.max = max;
this.ttl = ttlInMsecs;
}
get size() {
return this.items.size
}
bumpLru(item) {
if (this.last === item) {
return // Item is already the last one, no need to bump
}
const last = this.last;
const next = item.next;
const prev = item.prev;
if (this.first === item) {
this.first = next;
}
item.next = null;
item.prev = last;
last.next = item;
if (prev !== null) {
prev.next = next;
}
if (next !== null) {
next.prev = prev;
}
this.last = item;
}
clear() {
this.items = new Map();
this.first = null;
this.last = null;
}
delete(key) {
if (this.items.has(key)) {
const item = this.items.get(key);
this.items.delete(key);
if (item.prev !== null) {
item.prev.next = item.next;
}
if (item.next !== null) {
item.next.prev = item.prev;
}
if (this.first === item) {
this.first = item.next;
}
if (this.last === item) {
this.last = item.prev;
}
}
}
deleteMany(keys) {
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
evict() {
if (this.size > 0) {
const item = this.first;
this.items.delete(item.key);
if (this.size === 0) {
this.first = null;
this.last = null;
} else {
this.first = item.next;
this.first.prev = null;
}
}
}
expiresAt(key) {
if (this.items.has(key)) {
return this.items.get(key).expiry
}
}
get(key) {
if (this.items.has(key)) {
const item = this.items.get(key);
// Item has already expired
if (this.ttl > 0 && item.expiry <= Date.now()) {
this.delete(key);
return
}
// Item is still fresh
this.bumpLru(item);
return item.value
}
}
getMany(keys) {
const result = [];
for (var i = 0; i < keys.length; i++) {
result.push(this.get(keys[i]));
}
return result
}
keys() {
return this.items.keys()
}
set(key, value) {
// Replace existing item
if (this.items.has(key)) {
const item = this.items.get(key);
item.value = value;
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
if (this.last !== item) {
this.bumpLru(item);
}
return
}
// Add new item
if (this.max > 0 && this.size === this.max) {
this.evict();
}
const item = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
this.items.set(key, item);
if (this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
}
class LruObject {
constructor(max = 1000, ttlInMsecs = 0) {
if (isNaN(max) || max < 0) {
throw new Error('Invalid max value')
}
if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
throw new Error('Invalid ttl value')
}
this.first = null;
this.items = Object.create(null);
this.last = null;
this.size = 0;
this.max = max;
this.ttl = ttlInMsecs;
}
bumpLru(item) {
if (this.last === item) {
return // Item is already the last one, no need to bump
}
const last = this.last;
const next = item.next;
const prev = item.prev;
if (this.first === item) {
this.first = next;
}
item.next = null;
item.prev = last;
last.next = item;
if (prev !== null) {
prev.next = next;
}
if (next !== null) {
next.prev = prev;
}
this.last = item;
}
clear() {
this.items = Object.create(null);
this.first = null;
this.last = null;
this.size = 0;
}
delete(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
delete this.items[key];
this.size--;
if (item.prev !== null) {
item.prev.next = item.next;
}
if (item.next !== null) {
item.next.prev = item.prev;
}
if (this.first === item) {
this.first = item.next;
}
if (this.last === item) {
this.last = item.prev;
}
}
}
deleteMany(keys) {
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
evict() {
if (this.size > 0) {
const item = this.first;
delete this.items[item.key];
if (--this.size === 0) {
this.first = null;
this.last = null;
} else {
this.first = item.next;
this.first.prev = null;
}
}
}
expiresAt(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
return this.items[key].expiry
}
}
get(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
// Item has already expired
if (this.ttl > 0 && item.expiry <= Date.now()) {
this.delete(key);
return
}
// Item is still fresh
this.bumpLru(item);
return item.value
}
}
getMany(keys) {
const result = [];
for (var i = 0; i < keys.length; i++) {
result.push(this.get(keys[i]));
}
return result
}
keys() {
return Object.keys(this.items)
}
set(key, value) {
// Replace existing item
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
item.value = value;
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
if (this.last !== item) {
this.bumpLru(item);
}
return
}
// Add new item
if (this.max > 0 && this.size === this.max) {
this.evict();
}
const item = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
this.items[key] = item;
if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
}
class HitStatisticsRecord {
constructor() {
this.records = {};
}
initForCache(cacheId, currentTimeStamp) {
this.records[cacheId] = {
[currentTimeStamp]: {
cacheSize: 0,
hits: 0,
falsyHits: 0,
emptyHits: 0,
misses: 0,
expirations: 0,
evictions: 0,
invalidateOne: 0,
invalidateAll: 0,
sets: 0,
},
};
}
resetForCache(cacheId) {
for (let key of Object.keys(this.records[cacheId])) {
this.records[cacheId][key] = {
cacheSize: 0,
hits: 0,
falsyHits: 0,
emptyHits: 0,
misses: 0,
expirations: 0,
evictions: 0,
invalidateOne: 0,
invalidateAll: 0,
sets: 0,
};
}
}
getStatistics() {
return this.records
}
}
/**
*
* @param {Date} date
* @returns {string}
*/
function getTimestamp(date) {
return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
.getDate()
.toString()
.padStart(2, '0')}`
}
class HitStatistics {
constructor(cacheId, statisticTtlInHours, globalStatisticsRecord) {
this.cacheId = cacheId;
this.statisticTtlInHours = statisticTtlInHours;
this.collectionStart = new Date();
this.currentTimeStamp = getTimestamp(this.collectionStart);
this.records = globalStatisticsRecord || new HitStatisticsRecord();
this.records.initForCache(this.cacheId, this.currentTimeStamp);
}
get currentRecord() {
// safety net
/* c8 ignore next 14 */
if (!this.records.records[this.cacheId][this.currentTimeStamp]) {
this.records.records[this.cacheId][this.currentTimeStamp] = {
cacheSize: 0,
hits: 0,
falsyHits: 0,
emptyHits: 0,
misses: 0,
expirations: 0,
evictions: 0,
sets: 0,
invalidateOne: 0,
invalidateAll: 0,
};
}
return this.records.records[this.cacheId][this.currentTimeStamp]
}
hoursPassed() {
return (Date.now() - this.collectionStart) / 1000 / 60 / 60
}
addHit() {
this.archiveIfNeeded();
this.currentRecord.hits++;
}
addFalsyHit() {
this.archiveIfNeeded();
this.currentRecord.falsyHits++;
}
addEmptyHit() {
this.archiveIfNeeded();
this.currentRecord.emptyHits++;
}
addMiss() {
this.archiveIfNeeded();
this.currentRecord.misses++;
}
addEviction() {
this.archiveIfNeeded();
this.currentRecord.evictions++;
}
setCacheSize(currentSize) {
this.archiveIfNeeded();
this.currentRecord.cacheSize = currentSize;
}
addExpiration() {
this.archiveIfNeeded();
this.currentRecord.expirations++;
}
addSet() {
this.archiveIfNeeded();
this.currentRecord.sets++;
}
addInvalidateOne() {
this.archiveIfNeeded();
this.currentRecord.invalidateOne++;
}
addInvalidateAll() {
this.archiveIfNeeded();
this.currentRecord.invalidateAll++;
}
getStatistics() {
return this.records.getStatistics()
}
archiveIfNeeded() {
if (this.hoursPassed() >= this.statisticTtlInHours) {
this.collectionStart = new Date();
this.currentTimeStamp = getTimestamp(this.collectionStart);
this.records.initForCache(this.cacheId, this.currentTimeStamp);
}
}
}
class LruObjectHitStatistics extends LruObject {
constructor(max, ttlInMsecs, cacheId, globalStatisticsRecord, statisticTtlInHours) {
super(max || 1000, ttlInMsecs || 0);
if (!cacheId) {
throw new Error('Cache id is mandatory')
}
this.hitStatistics = new HitStatistics(
cacheId,
statisticTtlInHours !== undefined ? statisticTtlInHours : 24,
globalStatisticsRecord,
);
}
getStatistics() {
return this.hitStatistics.getStatistics()
}
set(key, value) {
super.set(key, value);
this.hitStatistics.addSet();
this.hitStatistics.setCacheSize(this.size);
}
evict() {
super.evict();
this.hitStatistics.addEviction();
this.hitStatistics.setCacheSize(this.size);
}
delete(key, isExpiration = false) {
super.delete(key);
if (!isExpiration) {
this.hitStatistics.addInvalidateOne();
}
this.hitStatistics.setCacheSize(this.size);
}
clear() {
super.clear();
this.hitStatistics.addInvalidateAll();
this.hitStatistics.setCacheSize(this.size);
}
get(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
// Item has already expired
if (this.ttl > 0 && item.expiry <= Date.now()) {
this.delete(key, true);
this.hitStatistics.addExpiration();
return
}
// Item is still fresh
this.bumpLru(item);
if (!item.value) {
this.hitStatistics.addFalsyHit();
}
if (item.value === undefined || item.value === null || item.value === '') {
this.hitStatistics.addEmptyHit();
}
this.hitStatistics.addHit();
return item.value
}
this.hitStatistics.addMiss();
}
}
class FifoObject {
constructor(max = 1000, ttlInMsecs = 0) {
if (isNaN(max) || max < 0) {
throw new Error('Invalid max value')
}
if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
throw new Error('Invalid ttl value')
}
this.first = null;
this.items = Object.create(null);
this.last = null;
this.size = 0;
this.max = max;
this.ttl = ttlInMsecs;
}
clear() {
this.items = Object.create(null);
this.first = null;
this.last = null;
this.size = 0;
}
delete(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const deletedItem = this.items[key];
delete this.items[key];
this.size--;
if (deletedItem.prev !== null) {
deletedItem.prev.next = deletedItem.next;
}
if (deletedItem.next !== null) {
deletedItem.next.prev = deletedItem.prev;
}
if (this.first === deletedItem) {
this.first = deletedItem.next;
}
if (this.last === deletedItem) {
this.last = deletedItem.prev;
}
}
}
deleteMany(keys) {
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
evict() {
if (this.size > 0) {
const item = this.first;
delete this.items[item.key];
if (--this.size === 0) {
this.first = null;
this.last = null;
} else {
this.first = item.next;
this.first.prev = null;
}
}
}
expiresAt(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
return this.items[key].expiry
}
}
get(key) {
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
if (this.ttl > 0 && item.expiry <= Date.now()) {
this.delete(key);
return
}
return item.value
}
}
getMany(keys) {
const result = [];
for (var i = 0; i < keys.length; i++) {
result.push(this.get(keys[i]));
}
return result
}
keys() {
return Object.keys(this.items)
}
set(key, value) {
// Replace existing item
if (Object.prototype.hasOwnProperty.call(this.items, key)) {
const item = this.items[key];
item.value = value;
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
return
}
// Add new item
if (this.max > 0 && this.size === this.max) {
this.evict();
}
const item = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
this.items[key] = item;
if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
}
exports.Fifo = FifoObject;
exports.FifoMap = FifoMap;
exports.FifoObject = FifoObject;
exports.HitStatisticsRecord = HitStatisticsRecord;
exports.Lru = LruObject;
exports.LruHitStatistics = LruObjectHitStatistics;
exports.LruMap = LruMap;
exports.LruObject = LruObject;
exports.LruObjectHitStatistics = LruObjectHitStatistics;
/***/ }),
/***/ 24624:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}');
/***/ }),
/***/ 90686:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}');
/***/ }),
/***/ 87099:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}');
/***/ }),
/***/ 90074:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}');
/***/ }),
/***/ 26338:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}');
/***/ }),
/***/ 62570:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}');
/***/ }),
/***/ 77045:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"name":"joi","description":"Object schema validation","version":"17.13.1","repository":"git://github.com/hapijs/joi","main":"lib/index.js","types":"lib/index.d.ts","browser":"dist/joi-browser.min.js","files":["lib/**/*","dist/*"],"keywords":["schema","validation"],"dependencies":{"@hapi/hoek":"^9.3.0","@hapi/topo":"^5.1.0","@sideway/address":"^4.1.5","@sideway/formula":"^3.0.1","@sideway/pinpoint":"^2.0.0"},"devDependencies":{"@hapi/bourne":"2.x.x","@hapi/code":"8.x.x","@hapi/joi-legacy-test":"npm:@hapi/joi@15.x.x","@hapi/lab":"^25.1.3","@types/node":"^14.18.63","typescript":"4.3.x"},"scripts":{"prepublishOnly":"cd browser && npm install && npm run build","test":"lab -t 100 -a @hapi/code -L -Y","test-cov-html":"lab -r html -o coverage.html -a @hapi/code"},"license":"BSD-3-Clause"}');
/***/ }),
/***/ 53765:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"application/1d-interleaved-parityfec":{"source":"iana"},"application/3gpdash-qoe-report+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/3gpp-ims+xml":{"source":"iana","compressible":true},"application/3gpphal+json":{"source":"iana","compressible":true},"application/3gpphalforms+json":{"source":"iana","compressible":true},"application/a2l":{"source":"iana"},"application/ace+cbor":{"source":"iana"},"application/activemessage":{"source":"iana"},"application/activity+json":{"source":"iana","compressible":true},"application/alto-costmap+json":{"source":"iana","compressible":true},"application/alto-costmapfilter+json":{"source":"iana","compressible":true},"application/alto-directory+json":{"source":"iana","compressible":true},"application/alto-endpointcost+json":{"source":"iana","compressible":true},"application/alto-endpointcostparams+json":{"source":"iana","compressible":true},"application/alto-endpointprop+json":{"source":"iana","compressible":true},"application/alto-endpointpropparams+json":{"source":"iana","compressible":true},"application/alto-error+json":{"source":"iana","compressible":true},"application/alto-networkmap+json":{"source":"iana","compressible":true},"application/alto-networkmapfilter+json":{"source":"iana","compressible":true},"application/alto-updatestreamcontrol+json":{"source":"iana","compressible":true},"application/alto-updatestreamparams+json":{"source":"iana","compressible":true},"application/aml":{"source":"iana"},"application/andrew-inset":{"source":"iana","extensions":["ez"]},"application/applefile":{"source":"iana"},"application/applixware":{"source":"apache","extensions":["aw"]},"application/at+jwt":{"source":"iana"},"application/atf":{"source":"iana"},"application/atfx":{"source":"iana"},"application/atom+xml":{"source":"iana","compressible":true,"extensions":["atom"]},"application/atomcat+xml":{"source":"iana","compressible":true,"extensions":["atomcat"]},"application/atomdeleted+xml":{"source":"iana","compressible":true,"extensions":["atomdeleted"]},"application/atomicmail":{"source":"iana"},"application/atomsvc+xml":{"source":"iana","compressible":true,"extensions":["atomsvc"]},"application/atsc-dwd+xml":{"source":"iana","compressible":true,"extensions":["dwd"]},"application/atsc-dynamic-event-message":{"source":"iana"},"application/atsc-held+xml":{"source":"iana","compressible":true,"extensions":["held"]},"application/atsc-rdt+json":{"source":"iana","compressible":true},"application/atsc-rsat+xml":{"source":"iana","compressible":true,"extensions":["rsat"]},"application/atxml":{"source":"iana"},"application/auth-policy+xml":{"source":"iana","compressible":true},"application/bacnet-xdd+zip":{"source":"iana","compressible":false},"application/batch-smtp":{"source":"iana"},"application/bdoc":{"compressible":false,"extensions":["bdoc"]},"application/beep+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/calendar+json":{"source":"iana","compressible":true},"application/calendar+xml":{"source":"iana","compressible":true,"extensions":["xcs"]},"application/call-completion":{"source":"iana"},"application/cals-1840":{"source":"iana"},"application/captive+json":{"source":"iana","compressible":true},"application/cbor":{"source":"iana"},"application/cbor-seq":{"source":"iana"},"application/cccex":{"source":"iana"},"application/ccmp+xml":{"source":"iana","compressible":true},"application/ccxml+xml":{"source":"iana","compressible":true,"extensions":["ccxml"]},"application/cdfx+xml":{"source":"iana","compressible":true,"extensions":["cdfx"]},"application/cdmi-capability":{"source":"iana","extensions":["cdmia"]},"application/cdmi-container":{"source":"iana","extensions":["cdmic"]},"application/cdmi-domain":{"source":"iana","extensions":["cdmid"]},"application/cdmi-object":{"source":"iana","extensions":["cdmio"]},"application/cdmi-queue":{"source":"iana","extensions":["cdmiq"]},"application/cdni":{"source":"iana"},"application/cea":{"source":"iana"},"application/cea-2018+xml":{"source":"iana","compressible":true},"application/cellml+xml":{"source":"iana","compressible":true},"application/cfw":{"source":"iana"},"application/city+json":{"source":"iana","compressible":true},"application/clr":{"source":"iana"},"application/clue+xml":{"source":"iana","compressible":true},"application/clue_info+xml":{"source":"iana","compressible":true},"application/cms":{"source":"iana"},"application/cnrp+xml":{"source":"iana","compressible":true},"application/coap-group+json":{"source":"iana","compressible":true},"application/coap-payload":{"source":"iana"},"application/commonground":{"source":"iana"},"application/conference-info+xml":{"source":"iana","compressible":true},"application/cose":{"source":"iana"},"application/cose-key":{"source":"iana"},"application/cose-key-set":{"source":"iana"},"application/cpl+xml":{"source":"iana","compressible":true,"extensions":["cpl"]},"application/csrattrs":{"source":"iana"},"application/csta+xml":{"source":"iana","compressible":true},"application/cstadata+xml":{"source":"iana","compressible":true},"application/csvm+json":{"source":"iana","compressible":true},"application/cu-seeme":{"source":"apache","extensions":["cu"]},"application/cwt":{"source":"iana"},"application/cybercash":{"source":"iana"},"application/dart":{"compressible":true},"application/dash+xml":{"source":"iana","compressible":true,"extensions":["mpd"]},"application/dash-patch+xml":{"source":"iana","compressible":true,"extensions":["mpp"]},"application/dashdelta":{"source":"iana"},"application/davmount+xml":{"source":"iana","compressible":true,"extensions":["davmount"]},"application/dca-rft":{"source":"iana"},"application/dcd":{"source":"iana"},"application/dec-dx":{"source":"iana"},"application/dialog-info+xml":{"source":"iana","compressible":true},"application/dicom":{"source":"iana"},"application/dicom+json":{"source":"iana","compressible":true},"application/dicom+xml":{"source":"iana","compressible":true},"application/dii":{"source":"iana"},"application/dit":{"source":"iana"},"application/dns":{"source":"iana"},"application/dns+json":{"source":"iana","compressible":true},"application/dns-message":{"source":"iana"},"application/docbook+xml":{"source":"apache","compressible":true,"extensions":["dbk"]},"application/dots+cbor":{"source":"iana"},"application/dskpp+xml":{"source":"iana","compressible":true},"application/dssc+der":{"source":"iana","extensions":["dssc"]},"application/dssc+xml":{"source":"iana","compressible":true,"extensions":["xdssc"]},"application/dvcs":{"source":"iana"},"application/ecmascript":{"source":"iana","compressible":true,"extensions":["es","ecma"]},"application/edi-consent":{"source":"iana"},"application/edi-x12":{"source":"iana","compressible":false},"application/edifact":{"source":"iana","compressible":false},"application/efi":{"source":"iana"},"application/elm+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/elm+xml":{"source":"iana","compressible":true},"application/emergencycalldata.cap+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/emergencycalldata.comment+xml":{"source":"iana","compressible":true},"application/emergencycalldata.control+xml":{"source":"iana","compressible":true},"application/emergencycalldata.deviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.ecall.msd":{"source":"iana"},"application/emergencycalldata.providerinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.serviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.subscriberinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.veds+xml":{"source":"iana","compressible":true},"application/emma+xml":{"source":"iana","compressible":true,"extensions":["emma"]},"application/emotionml+xml":{"source":"iana","compressible":true,"extensions":["emotionml"]},"application/encaprtp":{"source":"iana"},"application/epp+xml":{"source":"iana","compressible":true},"application/epub+zip":{"source":"iana","compressible":false,"extensions":["epub"]},"application/eshop":{"source":"iana"},"application/exi":{"source":"iana","extensions":["exi"]},"application/expect-ct-report+json":{"source":"iana","compressible":true},"application/express":{"source":"iana","extensions":["exp"]},"application/fastinfoset":{"source":"iana"},"application/fastsoap":{"source":"iana"},"application/fdt+xml":{"source":"iana","compressible":true,"extensions":["fdt"]},"application/fhir+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/fhir+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/fido.trusted-apps+json":{"compressible":true},"application/fits":{"source":"iana"},"application/flexfec":{"source":"iana"},"application/font-sfnt":{"source":"iana"},"application/font-tdpfr":{"source":"iana","extensions":["pfr"]},"application/font-woff":{"source":"iana","compressible":false},"application/framework-attributes+xml":{"source":"iana","compressible":true},"application/geo+json":{"source":"iana","compressible":true,"extensions":["geojson"]},"application/geo+json-seq":{"source":"iana"},"application/geopackage+sqlite3":{"source":"iana"},"application/geoxacml+xml":{"source":"iana","compressible":true},"application/gltf-buffer":{"source":"iana"},"application/gml+xml":{"source":"iana","compressible":true,"extensions":["gml"]},"application/gpx+xml":{"source":"apache","compressible":true,"extensions":["gpx"]},"application/gxf":{"source":"apache","extensions":["gxf"]},"application/gzip":{"source":"iana","compressible":false,"extensions":["gz"]},"application/h224":{"source":"iana"},"application/held+xml":{"source":"iana","compressible":true},"application/hjson":{"extensions":["hjson"]},"application/http":{"source":"iana"},"application/hyperstudio":{"source":"iana","extensions":["stk"]},"application/ibe-key-request+xml":{"source":"iana","compressible":true},"application/ibe-pkg-reply+xml":{"source":"iana","compressible":true},"application/ibe-pp-data":{"source":"iana"},"application/iges":{"source":"iana"},"application/im-iscomposing+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/index":{"source":"iana"},"application/index.cmd":{"source":"iana"},"application/index.obj":{"source":"iana"},"application/index.response":{"source":"iana"},"application/index.vnd":{"source":"iana"},"application/inkml+xml":{"source":"iana","compressible":true,"extensions":["ink","inkml"]},"application/iotp":{"source":"iana"},"application/ipfix":{"source":"iana","extensions":["ipfix"]},"application/ipp":{"source":"iana"},"application/isup":{"source":"iana"},"application/its+xml":{"source":"iana","compressible":true,"extensions":["its"]},"application/java-archive":{"source":"apache","compressible":false,"extensions":["jar","war","ear"]},"application/java-serialized-object":{"source":"apache","compressible":false,"extensions":["ser"]},"application/java-vm":{"source":"apache","compressible":false,"extensions":["class"]},"application/javascript":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},"application/jf2feed+json":{"source":"iana","compressible":true},"application/jose":{"source":"iana"},"application/jose+json":{"source":"iana","compressible":true},"application/jrd+json":{"source":"iana","compressible":true},"application/jscalendar+json":{"source":"iana","compressible":true},"application/json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},"application/json-patch+json":{"source":"iana","compressible":true},"application/json-seq":{"source":"iana"},"application/json5":{"extensions":["json5"]},"application/jsonml+json":{"source":"apache","compressible":true,"extensions":["jsonml"]},"application/jwk+json":{"source":"iana","compressible":true},"application/jwk-set+json":{"source":"iana","compressible":true},"application/jwt":{"source":"iana"},"application/kpml-request+xml":{"source":"iana","compressible":true},"application/kpml-response+xml":{"source":"iana","compressible":true},"application/ld+json":{"source":"iana","compressible":true,"extensions":["jsonld"]},"application/lgr+xml":{"source":"iana","compressible":true,"extensions":["lgr"]},"application/link-format":{"source":"iana"},"application/load-control+xml":{"source":"iana","compressible":true},"application/lost+xml":{"source":"iana","compressible":true,"extensions":["lostxml"]},"application/lostsync+xml":{"source":"iana","compressible":true},"application/lpf+zip":{"source":"iana","compressible":false},"application/lxf":{"source":"iana"},"application/mac-binhex40":{"source":"iana","extensions":["hqx"]},"application/mac-compactpro":{"source":"apache","extensions":["cpt"]},"application/macwriteii":{"source":"iana"},"application/mads+xml":{"source":"iana","compressible":true,"extensions":["mads"]},"application/manifest+json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},"application/marc":{"source":"iana","extensions":["mrc"]},"application/marcxml+xml":{"source":"iana","compressible":true,"extensions":["mrcx"]},"application/mathematica":{"source":"iana","extensions":["ma","nb","mb"]},"application/mathml+xml":{"source":"iana","compressible":true,"extensions":["mathml"]},"application/mathml-content+xml":{"source":"iana","compressible":true},"application/mathml-presentation+xml":{"source":"iana","compressible":true},"application/mbms-associated-procedure-description+xml":{"source":"iana","compressible":true},"application/mbms-deregister+xml":{"source":"iana","compressible":true},"application/mbms-envelope+xml":{"source":"iana","compressible":true},"application/mbms-msk+xml":{"source":"iana","compressible":true},"application/mbms-msk-response+xml":{"source":"iana","compressible":true},"application/mbms-protection-description+xml":{"source":"iana","compressible":true},"application/mbms-reception-report+xml":{"source":"iana","compressible":true},"application/mbms-register+xml":{"source":"iana","compressible":true},"application/mbms-register-response+xml":{"source":"iana","compressible":true},"application/mbms-schedule+xml":{"source":"iana","compressible":true},"application/mbms-user-service-description+xml":{"source":"iana","compressible":true},"application/mbox":{"source":"iana","extensions":["mbox"]},"application/media-policy-dataset+xml":{"source":"iana","compressible":true,"extensions":["mpf"]},"application/media_control+xml":{"source":"iana","compressible":true},"application/mediaservercontrol+xml":{"source":"iana","compressible":true,"extensions":["mscml"]},"application/merge-patch+json":{"source":"iana","compressible":true},"application/metalink+xml":{"source":"apache","compressible":true,"extensions":["metalink"]},"application/metalink4+xml":{"source":"iana","compressible":true,"extensions":["meta4"]},"application/mets+xml":{"source":"iana","compressible":true,"extensions":["mets"]},"application/mf4":{"source":"iana"},"application/mikey":{"source":"iana"},"application/mipc":{"source":"iana"},"application/missing-blocks+cbor-seq":{"source":"iana"},"application/mmt-aei+xml":{"source":"iana","compressible":true,"extensions":["maei"]},"application/mmt-usd+xml":{"source":"iana","compressible":true,"extensions":["musd"]},"application/mods+xml":{"source":"iana","compressible":true,"extensions":["mods"]},"application/moss-keys":{"source":"iana"},"application/moss-signature":{"source":"iana"},"application/mosskey-data":{"source":"iana"},"application/mosskey-request":{"source":"iana"},"application/mp21":{"source":"iana","extensions":["m21","mp21"]},"application/mp4":{"source":"iana","extensions":["mp4s","m4p"]},"application/mpeg4-generic":{"source":"iana"},"application/mpeg4-iod":{"source":"iana"},"application/mpeg4-iod-xmt":{"source":"iana"},"application/mrb-consumer+xml":{"source":"iana","compressible":true},"application/mrb-publish+xml":{"source":"iana","compressible":true},"application/msc-ivr+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msc-mixer+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msword":{"source":"iana","compressible":false,"extensions":["doc","dot"]},"application/mud+json":{"source":"iana","compressible":true},"application/multipart-core":{"source":"iana"},"application/mxf":{"source":"iana","extensions":["mxf"]},"application/n-quads":{"source":"iana","extensions":["nq"]},"application/n-triples":{"source":"iana","extensions":["nt"]},"application/nasdata":{"source":"iana"},"application/news-checkgroups":{"source":"iana","charset":"US-ASCII"},"application/news-groupinfo":{"source":"iana","charset":"US-ASCII"},"application/news-transmission":{"source":"iana"},"application/nlsml+xml":{"source":"iana","compressible":true},"application/node":{"source":"iana","extensions":["cjs"]},"application/nss":{"source":"iana"},"application/oauth-authz-req+jwt":{"source":"iana"},"application/oblivious-dns-message":{"source":"iana"},"application/ocsp-request":{"source":"iana"},"application/ocsp-response":{"source":"iana"},"application/octet-stream":{"source":"iana","compressible":false,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{"source":"iana","extensions":["oda"]},"application/odm+xml":{"source":"iana","compressible":true},"application/odx":{"source":"iana"},"application/oebps-package+xml":{"source":"iana","compressible":true,"extensions":["opf"]},"application/ogg":{"source":"iana","compressible":false,"extensions":["ogx"]},"application/omdoc+xml":{"source":"apache","compressible":true,"extensions":["omdoc"]},"application/onenote":{"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{"source":"iana","compressible":true},"application/oscore":{"source":"iana"},"application/oxps":{"source":"iana","extensions":["oxps"]},"application/p21":{"source":"iana"},"application/p21+zip":{"source":"iana","compressible":false},"application/p2p-overlay+xml":{"source":"iana","compressible":true,"extensions":["relo"]},"application/parityfec":{"source":"iana"},"application/passport":{"source":"iana"},"application/patch-ops-error+xml":{"source":"iana","compressible":true,"extensions":["xer"]},"application/pdf":{"source":"iana","compressible":false,"extensions":["pdf"]},"application/pdx":{"source":"iana"},"application/pem-certificate-chain":{"source":"iana"},"application/pgp-encrypted":{"source":"iana","compressible":false,"extensions":["pgp"]},"application/pgp-keys":{"source":"iana","extensions":["asc"]},"application/pgp-signature":{"source":"iana","extensions":["asc","sig"]},"application/pics-rules":{"source":"apache","extensions":["prf"]},"application/pidf+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pidf-diff+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pkcs10":{"source":"iana","extensions":["p10"]},"application/pkcs12":{"source":"iana"},"application/pkcs7-mime":{"source":"iana","extensions":["p7m","p7c"]},"application/pkcs7-signature":{"source":"iana","extensions":["p7s"]},"application/pkcs8":{"source":"iana","extensions":["p8"]},"application/pkcs8-encrypted":{"source":"iana"},"application/pkix-attr-cert":{"source":"iana","extensions":["ac"]},"application/pkix-cert":{"source":"iana","extensions":["cer"]},"application/pkix-crl":{"source":"iana","extensions":["crl"]},"application/pkix-pkipath":{"source":"iana","extensions":["pkipath"]},"application/pkixcmp":{"source":"iana","extensions":["pki"]},"application/pls+xml":{"source":"iana","compressible":true,"extensions":["pls"]},"application/poc-settings+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/postscript":{"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},"application/ppsp-tracker+json":{"source":"iana","compressible":true},"application/problem+json":{"source":"iana","compressible":true},"application/problem+xml":{"source":"iana","compressible":true},"application/provenance+xml":{"source":"iana","compressible":true,"extensions":["provx"]},"application/prs.alvestrand.titrax-sheet":{"source":"iana"},"application/prs.cww":{"source":"iana","extensions":["cww"]},"application/prs.cyn":{"source":"iana","charset":"7-BIT"},"application/prs.hpub+zip":{"source":"iana","compressible":false},"application/prs.nprend":{"source":"iana"},"application/prs.plucker":{"source":"iana"},"application/prs.rdf-xml-crypt":{"source":"iana"},"application/prs.xsf+xml":{"source":"iana","compressible":true},"application/pskc+xml":{"source":"iana","compressible":true,"extensions":["pskcxml"]},"application/pvd+json":{"source":"iana","compressible":true},"application/qsig":{"source":"iana"},"application/raml+yaml":{"compressible":true,"extensions":["raml"]},"application/raptorfec":{"source":"iana"},"application/rdap+json":{"source":"iana","compressible":true},"application/rdf+xml":{"source":"iana","compressible":true,"extensions":["rdf","owl"]},"application/reginfo+xml":{"source":"iana","compressible":true,"extensions":["rif"]},"application/relax-ng-compact-syntax":{"source":"iana","extensions":["rnc"]},"application/remote-printing":{"source":"iana"},"application/reputon+json":{"source":"iana","compressible":true},"application/resource-lists+xml":{"source":"iana","compressible":true,"extensions":["rl"]},"application/resource-lists-diff+xml":{"source":"iana","compressible":true,"extensions":["rld"]},"application/rfc+xml":{"source":"iana","compressible":true},"application/riscos":{"source":"iana"},"application/rlmi+xml":{"source":"iana","compressible":true},"application/rls-services+xml":{"source":"iana","compressible":true,"extensions":["rs"]},"application/route-apd+xml":{"source":"iana","compressible":true,"extensions":["rapd"]},"application/route-s-tsid+xml":{"source":"iana","compressible":true,"extensions":["sls"]},"application/route-usd+xml":{"source":"iana","compressible":true,"extensions":["rusd"]},"application/rpki-ghostbusters":{"source":"iana","extensions":["gbr"]},"application/rpki-manifest":{"source":"iana","extensions":["mft"]},"application/rpki-publication":{"source":"iana"},"application/rpki-roa":{"source":"iana","extensions":["roa"]},"application/rpki-updown":{"source":"iana"},"application/rsd+xml":{"source":"apache","compressible":true,"extensions":["rsd"]},"application/rss+xml":{"source":"apache","compressible":true,"extensions":["rss"]},"application/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"application/rtploopback":{"source":"iana"},"application/rtx":{"source":"iana"},"application/samlassertion+xml":{"source":"iana","compressible":true},"application/samlmetadata+xml":{"source":"iana","compressible":true},"application/sarif+json":{"source":"iana","compressible":true},"application/sarif-external-properties+json":{"source":"iana","compressible":true},"application/sbe":{"source":"iana"},"application/sbml+xml":{"source":"iana","compressible":true,"extensions":["sbml"]},"application/scaip+xml":{"source":"iana","compressible":true},"application/scim+json":{"source":"iana","compressible":true},"application/scvp-cv-request":{"source":"iana","extensions":["scq"]},"application/scvp-cv-response":{"source":"iana","extensions":["scs"]},"application/scvp-vp-request":{"source":"iana","extensions":["spq"]},"application/scvp-vp-response":{"source":"iana","extensions":["spp"]},"application/sdp":{"source":"iana","extensions":["sdp"]},"application/secevent+jwt":{"source":"iana"},"application/senml+cbor":{"source":"iana"},"application/senml+json":{"source":"iana","compressible":true},"application/senml+xml":{"source":"iana","compressible":true,"extensions":["senmlx"]},"application/senml-etch+cbor":{"source":"iana"},"application/senml-etch+json":{"source":"iana","compressible":true},"application/senml-exi":{"source":"iana"},"application/sensml+cbor":{"source":"iana"},"application/sensml+json":{"source":"iana","compressible":true},"application/sensml+xml":{"source":"iana","compressible":true,"extensions":["sensmlx"]},"application/sensml-exi":{"source":"iana"},"application/sep+xml":{"source":"iana","compressible":true},"application/sep-exi":{"source":"iana"},"application/session-info":{"source":"iana"},"application/set-payment":{"source":"iana"},"application/set-payment-initiation":{"source":"iana","extensions":["setpay"]},"application/set-registration":{"source":"iana"},"application/set-registration-initiation":{"source":"iana","extensions":["setreg"]},"application/sgml":{"source":"iana"},"application/sgml-open-catalog":{"source":"iana"},"application/shf+xml":{"source":"iana","compressible":true,"extensions":["shf"]},"application/sieve":{"source":"iana","extensions":["siv","sieve"]},"application/simple-filter+xml":{"source":"iana","compressible":true},"application/simple-message-summary":{"source":"iana"},"application/simplesymbolcontainer":{"source":"iana"},"application/sipc":{"source":"iana"},"application/slate":{"source":"iana"},"application/smil":{"source":"iana"},"application/smil+xml":{"source":"iana","compressible":true,"extensions":["smi","smil"]},"application/smpte336m":{"source":"iana"},"application/soap+fastinfoset":{"source":"iana"},"application/soap+xml":{"source":"iana","compressible":true},"application/sparql-query":{"source":"iana","extensions":["rq"]},"application/sparql-results+xml":{"source":"iana","compressible":true,"extensions":["srx"]},"application/spdx+json":{"source":"iana","compressible":true},"application/spirits-event+xml":{"source":"iana","compressible":true},"application/sql":{"source":"iana"},"application/srgs":{"source":"iana","extensions":["gram"]},"application/srgs+xml":{"source":"iana","compressible":true,"extensions":["grxml"]},"application/sru+xml":{"source":"iana","compressible":true,"extensions":["sru"]},"application/ssdl+xml":{"source":"apache","compressible":true,"extensions":["ssdl"]},"application/ssml+xml":{"source":"iana","compressible":true,"extensions":["ssml"]},"application/stix+json":{"source":"iana","compressible":true},"application/swid+xml":{"source":"iana","compressible":true,"extensions":["swidtag"]},"application/tamp-apex-update":{"source":"iana"},"application/tamp-apex-update-confirm":{"source":"iana"},"application/tamp-community-update":{"source":"iana"},"application/tamp-community-update-confirm":{"source":"iana"},"application/tamp-error":{"source":"iana"},"application/tamp-sequence-adjust":{"source":"iana"},"application/tamp-sequence-adjust-confirm":{"source":"iana"},"application/tamp-status-query":{"source":"iana"},"application/tamp-status-response":{"source":"iana"},"application/tamp-update":{"source":"iana"},"application/tamp-update-confirm":{"source":"iana"},"application/tar":{"compressible":true},"application/taxii+json":{"source":"iana","compressible":true},"application/td+json":{"source":"iana","compressible":true},"application/tei+xml":{"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},"application/tetra_isi":{"source":"iana"},"application/thraud+xml":{"source":"iana","compressible":true,"extensions":["tfi"]},"application/timestamp-query":{"source":"iana"},"application/timestamp-reply":{"source":"iana"},"application/timestamped-data":{"source":"iana","extensions":["tsd"]},"application/tlsrpt+gzip":{"source":"iana"},"application/tlsrpt+json":{"source":"iana","compressible":true},"application/tnauthlist":{"source":"iana"},"application/token-introspection+jwt":{"source":"iana"},"application/toml":{"compressible":true,"extensions":["toml"]},"application/trickle-ice-sdpfrag":{"source":"iana"},"application/trig":{"source":"iana","extensions":["trig"]},"application/ttml+xml":{"source":"iana","compressible":true,"extensions":["ttml"]},"application/tve-trigger":{"source":"iana"},"application/tzif":{"source":"iana"},"application/tzif-leap":{"source":"iana"},"application/ubjson":{"compressible":false,"extensions":["ubj"]},"application/ulpfec":{"source":"iana"},"application/urc-grpsheet+xml":{"source":"iana","compressible":true},"application/urc-ressheet+xml":{"source":"iana","compressible":true,"extensions":["rsheet"]},"application/urc-targetdesc+xml":{"source":"iana","compressible":true,"extensions":["td"]},"application/urc-uisocketdesc+xml":{"source":"iana","compressible":true},"application/vcard+json":{"source":"iana","compressible":true},"application/vcard+xml":{"source":"iana","compressible":true},"application/vemmi":{"source":"iana"},"application/vividence.scriptfile":{"source":"apache"},"application/vnd.1000minds.decision-model+xml":{"source":"iana","compressible":true,"extensions":["1km"]},"application/vnd.3gpp-prose+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-prose-pc3ch+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-v2x-local-service-information":{"source":"iana"},"application/vnd.3gpp.5gnas":{"source":"iana"},"application/vnd.3gpp.access-transfer-events+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.bsf+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gmop+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gtpc":{"source":"iana"},"application/vnd.3gpp.interworking-data":{"source":"iana"},"application/vnd.3gpp.lpp":{"source":"iana"},"application/vnd.3gpp.mc-signalling-ear":{"source":"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-payload":{"source":"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-signalling":{"source":"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-floor-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-signed+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-init-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-transmission-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mid-call+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ngap":{"source":"iana"},"application/vnd.3gpp.pfcp":{"source":"iana"},"application/vnd.3gpp.pic-bw-large":{"source":"iana","extensions":["plb"]},"application/vnd.3gpp.pic-bw-small":{"source":"iana","extensions":["psb"]},"application/vnd.3gpp.pic-bw-var":{"source":"iana","extensions":["pvb"]},"application/vnd.3gpp.s1ap":{"source":"iana"},"application/vnd.3gpp.sms":{"source":"iana"},"application/vnd.3gpp.sms+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-ext+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.state-and-event-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ussd+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.bcmcsinfo+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.sms":{"source":"iana"},"application/vnd.3gpp2.tcap":{"source":"iana","extensions":["tcap"]},"application/vnd.3lightssoftware.imagescal":{"source":"iana"},"application/vnd.3m.post-it-notes":{"source":"iana","extensions":["pwn"]},"application/vnd.accpac.simply.aso":{"source":"iana","extensions":["aso"]},"application/vnd.accpac.simply.imp":{"source":"iana","extensions":["imp"]},"application/vnd.acucobol":{"source":"iana","extensions":["acu"]},"application/vnd.acucorp":{"source":"iana","extensions":["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{"source":"apache","compressible":false,"extensions":["air"]},"application/vnd.adobe.flash.movie":{"source":"iana"},"application/vnd.adobe.formscentral.fcdt":{"source":"iana","extensions":["fcdt"]},"application/vnd.adobe.fxp":{"source":"iana","extensions":["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{"source":"iana"},"application/vnd.adobe.xdp+xml":{"source":"iana","compressible":true,"extensions":["xdp"]},"application/vnd.adobe.xfdf":{"source":"iana","extensions":["xfdf"]},"application/vnd.aether.imp":{"source":"iana"},"application/vnd.afpc.afplinedata":{"source":"iana"},"application/vnd.afpc.afplinedata-pagedef":{"source":"iana"},"application/vnd.afpc.cmoca-cmresource":{"source":"iana"},"application/vnd.afpc.foca-charset":{"source":"iana"},"application/vnd.afpc.foca-codedfont":{"source":"iana"},"application/vnd.afpc.foca-codepage":{"source":"iana"},"application/vnd.afpc.modca":{"source":"iana"},"application/vnd.afpc.modca-cmtable":{"source":"iana"},"application/vnd.afpc.modca-formdef":{"source":"iana"},"application/vnd.afpc.modca-mediummap":{"source":"iana"},"application/vnd.afpc.modca-objectcontainer":{"source":"iana"},"application/vnd.afpc.modca-overlay":{"source":"iana"},"application/vnd.afpc.modca-pagesegment":{"source":"iana"},"application/vnd.age":{"source":"iana","extensions":["age"]},"application/vnd.ah-barcode":{"source":"iana"},"application/vnd.ahead.space":{"source":"iana","extensions":["ahead"]},"application/vnd.airzip.filesecure.azf":{"source":"iana","extensions":["azf"]},"application/vnd.airzip.filesecure.azs":{"source":"iana","extensions":["azs"]},"application/vnd.amadeus+json":{"source":"iana","compressible":true},"application/vnd.amazon.ebook":{"source":"apache","extensions":["azw"]},"application/vnd.amazon.mobi8-ebook":{"source":"iana"},"application/vnd.americandynamics.acc":{"source":"iana","extensions":["acc"]},"application/vnd.amiga.ami":{"source":"iana","extensions":["ami"]},"application/vnd.amundsen.maze+xml":{"source":"iana","compressible":true},"application/vnd.android.ota":{"source":"iana"},"application/vnd.android.package-archive":{"source":"apache","compressible":false,"extensions":["apk"]},"application/vnd.anki":{"source":"iana"},"application/vnd.anser-web-certificate-issue-initiation":{"source":"iana","extensions":["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{"source":"apache","extensions":["fti"]},"application/vnd.antix.game-component":{"source":"iana","extensions":["atx"]},"application/vnd.apache.arrow.file":{"source":"iana"},"application/vnd.apache.arrow.stream":{"source":"iana"},"application/vnd.apache.thrift.binary":{"source":"iana"},"application/vnd.apache.thrift.compact":{"source":"iana"},"application/vnd.apache.thrift.json":{"source":"iana"},"application/vnd.api+json":{"source":"iana","compressible":true},"application/vnd.aplextor.warrp+json":{"source":"iana","compressible":true},"application/vnd.apothekende.reservation+json":{"source":"iana","compressible":true},"application/vnd.apple.installer+xml":{"source":"iana","compressible":true,"extensions":["mpkg"]},"application/vnd.apple.keynote":{"source":"iana","extensions":["key"]},"application/vnd.apple.mpegurl":{"source":"iana","extensions":["m3u8"]},"application/vnd.apple.numbers":{"source":"iana","extensions":["numbers"]},"application/vnd.apple.pages":{"source":"iana","extensions":["pages"]},"application/vnd.apple.pkpass":{"compressible":false,"extensions":["pkpass"]},"application/vnd.arastra.swi":{"source":"iana"},"application/vnd.aristanetworks.swi":{"source":"iana","extensions":["swi"]},"application/vnd.artisan+json":{"source":"iana","compressible":true},"application/vnd.artsquare":{"source":"iana"},"application/vnd.astraea-software.iota":{"source":"iana","extensions":["iota"]},"application/vnd.audiograph":{"source":"iana","extensions":["aep"]},"application/vnd.autopackage":{"source":"iana"},"application/vnd.avalon+json":{"source":"iana","compressible":true},"application/vnd.avistar+xml":{"source":"iana","compressible":true},"application/vnd.balsamiq.bmml+xml":{"source":"iana","compressible":true,"extensions":["bmml"]},"application/vnd.balsamiq.bmpr":{"source":"iana"},"application/vnd.banana-accounting":{"source":"iana"},"application/vnd.bbf.usp.error":{"source":"iana"},"application/vnd.bbf.usp.msg":{"source":"iana"},"application/vnd.bbf.usp.msg+json":{"source":"iana","compressible":true},"application/vnd.bekitzur-stech+json":{"source":"iana","compressible":true},"application/vnd.bint.med-content":{"source":"iana"},"application/vnd.biopax.rdf+xml":{"source":"iana","compressible":true},"application/vnd.blink-idb-value-wrapper":{"source":"iana"},"application/vnd.blueice.multipass":{"source":"iana","extensions":["mpm"]},"application/vnd.bluetooth.ep.oob":{"source":"iana"},"application/vnd.bluetooth.le.oob":{"source":"iana"},"application/vnd.bmi":{"source":"iana","extensions":["bmi"]},"application/vnd.bpf":{"source":"iana"},"application/vnd.bpf3":{"source":"iana"},"application/vnd.businessobjects":{"source":"iana","extensions":["rep"]},"application/vnd.byu.uapi+json":{"source":"iana","compressible":true},"application/vnd.cab-jscript":{"source":"iana"},"application/vnd.canon-cpdl":{"source":"iana"},"application/vnd.canon-lips":{"source":"iana"},"application/vnd.capasystems-pg+json":{"source":"iana","compressible":true},"application/vnd.cendio.thinlinc.clientconf":{"source":"iana"},"application/vnd.century-systems.tcp_stream":{"source":"iana"},"application/vnd.chemdraw+xml":{"source":"iana","compressible":true,"extensions":["cdxml"]},"application/vnd.chess-pgn":{"source":"iana"},"application/vnd.chipnuts.karaoke-mmd":{"source":"iana","extensions":["mmd"]},"application/vnd.ciedi":{"source":"iana"},"application/vnd.cinderella":{"source":"iana","extensions":["cdy"]},"application/vnd.cirpack.isdn-ext":{"source":"iana"},"application/vnd.citationstyles.style+xml":{"source":"iana","compressible":true,"extensions":["csl"]},"application/vnd.claymore":{"source":"iana","extensions":["cla"]},"application/vnd.cloanto.rp9":{"source":"iana","extensions":["rp9"]},"application/vnd.clonk.c4group":{"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{"source":"iana","extensions":["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{"source":"iana","extensions":["c11amz"]},"application/vnd.coffeescript":{"source":"iana"},"application/vnd.collabio.xodocuments.document":{"source":"iana"},"application/vnd.collabio.xodocuments.document-template":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation-template":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{"source":"iana"},"application/vnd.collection+json":{"source":"iana","compressible":true},"application/vnd.collection.doc+json":{"source":"iana","compressible":true},"application/vnd.collection.next+json":{"source":"iana","compressible":true},"application/vnd.comicbook+zip":{"source":"iana","compressible":false},"application/vnd.comicbook-rar":{"source":"iana"},"application/vnd.commerce-battelle":{"source":"iana"},"application/vnd.commonspace":{"source":"iana","extensions":["csp"]},"application/vnd.contact.cmsg":{"source":"iana","extensions":["cdbcmsg"]},"application/vnd.coreos.ignition+json":{"source":"iana","compressible":true},"application/vnd.cosmocaller":{"source":"iana","extensions":["cmc"]},"application/vnd.crick.clicker":{"source":"iana","extensions":["clkx"]},"application/vnd.crick.clicker.keyboard":{"source":"iana","extensions":["clkk"]},"application/vnd.crick.clicker.palette":{"source":"iana","extensions":["clkp"]},"application/vnd.crick.clicker.template":{"source":"iana","extensions":["clkt"]},"application/vnd.crick.clicker.wordbank":{"source":"iana","extensions":["clkw"]},"application/vnd.criticaltools.wbs+xml":{"source":"iana","compressible":true,"extensions":["wbs"]},"application/vnd.cryptii.pipe+json":{"source":"iana","compressible":true},"application/vnd.crypto-shade-file":{"source":"iana"},"application/vnd.cryptomator.encrypted":{"source":"iana"},"application/vnd.cryptomator.vault":{"source":"iana"},"application/vnd.ctc-posml":{"source":"iana","extensions":["pml"]},"application/vnd.ctct.ws+xml":{"source":"iana","compressible":true},"application/vnd.cups-pdf":{"source":"iana"},"application/vnd.cups-postscript":{"source":"iana"},"application/vnd.cups-ppd":{"source":"iana","extensions":["ppd"]},"application/vnd.cups-raster":{"source":"iana"},"application/vnd.cups-raw":{"source":"iana"},"application/vnd.curl":{"source":"iana"},"application/vnd.curl.car":{"source":"apache","extensions":["car"]},"application/vnd.curl.pcurl":{"source":"apache","extensions":["pcurl"]},"application/vnd.cyan.dean.root+xml":{"source":"iana","compressible":true},"application/vnd.cybank":{"source":"iana"},"application/vnd.cyclonedx+json":{"source":"iana","compressible":true},"application/vnd.cyclonedx+xml":{"source":"iana","compressible":true},"application/vnd.d2l.coursepackage1p0+zip":{"source":"iana","compressible":false},"application/vnd.d3m-dataset":{"source":"iana"},"application/vnd.d3m-problem":{"source":"iana"},"application/vnd.dart":{"source":"iana","compressible":true,"extensions":["dart"]},"application/vnd.data-vision.rdz":{"source":"iana","extensions":["rdz"]},"application/vnd.datapackage+json":{"source":"iana","compressible":true},"application/vnd.dataresource+json":{"source":"iana","compressible":true},"application/vnd.dbf":{"source":"iana","extensions":["dbf"]},"application/vnd.debian.binary-package":{"source":"iana"},"application/vnd.dece.data":{"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},"application/vnd.dece.unspecified":{"source":"iana","extensions":["uvx","uvvx"]},"application/vnd.dece.zip":{"source":"iana","extensions":["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{"source":"iana","extensions":["fe_launch"]},"application/vnd.desmume.movie":{"source":"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{"source":"iana"},"application/vnd.dm.delegation+xml":{"source":"iana","compressible":true},"application/vnd.dna":{"source":"iana","extensions":["dna"]},"application/vnd.document+json":{"source":"iana","compressible":true},"application/vnd.dolby.mlp":{"source":"apache","extensions":["mlp"]},"application/vnd.dolby.mobile.1":{"source":"iana"},"application/vnd.dolby.mobile.2":{"source":"iana"},"application/vnd.doremir.scorecloud-binary-document":{"source":"iana"},"application/vnd.dpgraph":{"source":"iana","extensions":["dpg"]},"application/vnd.dreamfactory":{"source":"iana","extensions":["dfac"]},"application/vnd.drive+json":{"source":"iana","compressible":true},"application/vnd.ds-keypoint":{"source":"apache","extensions":["kpxx"]},"application/vnd.dtg.local":{"source":"iana"},"application/vnd.dtg.local.flash":{"source":"iana"},"application/vnd.dtg.local.html":{"source":"iana"},"application/vnd.dvb.ait":{"source":"iana","extensions":["ait"]},"application/vnd.dvb.dvbisl+xml":{"source":"iana","compressible":true},"application/vnd.dvb.dvbj":{"source":"iana"},"application/vnd.dvb.esgcontainer":{"source":"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess2":{"source":"iana"},"application/vnd.dvb.ipdcesgpdd":{"source":"iana"},"application/vnd.dvb.ipdcroaming":{"source":"iana"},"application/vnd.dvb.iptv.alfec-base":{"source":"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{"source":"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-container+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-generic+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-msglist+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-request+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-response+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-init+xml":{"source":"iana","compressible":true},"application/vnd.dvb.pfr":{"source":"iana"},"application/vnd.dvb.service":{"source":"iana","extensions":["svc"]},"application/vnd.dxr":{"source":"iana"},"application/vnd.dynageo":{"source":"iana","extensions":["geo"]},"application/vnd.dzr":{"source":"iana"},"application/vnd.easykaraoke.cdgdownload":{"source":"iana"},"application/vnd.ecdis-update":{"source":"iana"},"application/vnd.ecip.rlp":{"source":"iana"},"application/vnd.eclipse.ditto+json":{"source":"iana","compressible":true},"application/vnd.ecowin.chart":{"source":"iana","extensions":["mag"]},"application/vnd.ecowin.filerequest":{"source":"iana"},"application/vnd.ecowin.fileupdate":{"source":"iana"},"application/vnd.ecowin.series":{"source":"iana"},"application/vnd.ecowin.seriesrequest":{"source":"iana"},"application/vnd.ecowin.seriesupdate":{"source":"iana"},"application/vnd.efi.img":{"source":"iana"},"application/vnd.efi.iso":{"source":"iana"},"application/vnd.emclient.accessrequest+xml":{"source":"iana","compressible":true},"application/vnd.enliven":{"source":"iana","extensions":["nml"]},"application/vnd.enphase.envoy":{"source":"iana"},"application/vnd.eprints.data+xml":{"source":"iana","compressible":true},"application/vnd.epson.esf":{"source":"iana","extensions":["esf"]},"application/vnd.epson.msf":{"source":"iana","extensions":["msf"]},"application/vnd.epson.quickanime":{"source":"iana","extensions":["qam"]},"application/vnd.epson.salt":{"source":"iana","extensions":["slt"]},"application/vnd.epson.ssf":{"source":"iana","extensions":["ssf"]},"application/vnd.ericsson.quickcall":{"source":"iana"},"application/vnd.espass-espass+zip":{"source":"iana","compressible":false},"application/vnd.eszigno3+xml":{"source":"iana","compressible":true,"extensions":["es3","et3"]},"application/vnd.etsi.aoc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.asic-e+zip":{"source":"iana","compressible":false},"application/vnd.etsi.asic-s+zip":{"source":"iana","compressible":false},"application/vnd.etsi.cug+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvcommand+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-bc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-cod+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-npvr+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvservice+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsync+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvueprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mcid+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mheg5":{"source":"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{"source":"iana","compressible":true},"application/vnd.etsi.pstn+xml":{"source":"iana","compressible":true},"application/vnd.etsi.sci+xml":{"source":"iana","compressible":true},"application/vnd.etsi.simservs+xml":{"source":"iana","compressible":true},"application/vnd.etsi.timestamp-token":{"source":"iana"},"application/vnd.etsi.tsl+xml":{"source":"iana","compressible":true},"application/vnd.etsi.tsl.der":{"source":"iana"},"application/vnd.eu.kasparian.car+json":{"source":"iana","compressible":true},"application/vnd.eudora.data":{"source":"iana"},"application/vnd.evolv.ecig.profile":{"source":"iana"},"application/vnd.evolv.ecig.settings":{"source":"iana"},"application/vnd.evolv.ecig.theme":{"source":"iana"},"application/vnd.exstream-empower+zip":{"source":"iana","compressible":false},"application/vnd.exstream-package":{"source":"iana"},"application/vnd.ezpix-album":{"source":"iana","extensions":["ez2"]},"application/vnd.ezpix-package":{"source":"iana","extensions":["ez3"]},"application/vnd.f-secure.mobile":{"source":"iana"},"application/vnd.familysearch.gedcom+zip":{"source":"iana","compressible":false},"application/vnd.fastcopy-disk-image":{"source":"iana"},"application/vnd.fdf":{"source":"iana","extensions":["fdf"]},"application/vnd.fdsn.mseed":{"source":"iana","extensions":["mseed"]},"application/vnd.fdsn.seed":{"source":"iana","extensions":["seed","dataless"]},"application/vnd.ffsns":{"source":"iana"},"application/vnd.ficlab.flb+zip":{"source":"iana","compressible":false},"application/vnd.filmit.zfc":{"source":"iana"},"application/vnd.fints":{"source":"iana"},"application/vnd.firemonkeys.cloudcell":{"source":"iana"},"application/vnd.flographit":{"source":"iana","extensions":["gph"]},"application/vnd.fluxtime.clip":{"source":"iana","extensions":["ftc"]},"application/vnd.font-fontforge-sfd":{"source":"iana"},"application/vnd.framemaker":{"source":"iana","extensions":["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{"source":"iana","extensions":["fnc"]},"application/vnd.frogans.ltf":{"source":"iana","extensions":["ltf"]},"application/vnd.fsc.weblaunch":{"source":"iana","extensions":["fsc"]},"application/vnd.fujifilm.fb.docuworks":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.container":{"source":"iana"},"application/vnd.fujifilm.fb.jfi+xml":{"source":"iana","compressible":true},"application/vnd.fujitsu.oasys":{"source":"iana","extensions":["oas"]},"application/vnd.fujitsu.oasys2":{"source":"iana","extensions":["oa2"]},"application/vnd.fujitsu.oasys3":{"source":"iana","extensions":["oa3"]},"application/vnd.fujitsu.oasysgp":{"source":"iana","extensions":["fg5"]},"application/vnd.fujitsu.oasysprs":{"source":"iana","extensions":["bh2"]},"application/vnd.fujixerox.art-ex":{"source":"iana"},"application/vnd.fujixerox.art4":{"source":"iana"},"application/vnd.fujixerox.ddd":{"source":"iana","extensions":["ddd"]},"application/vnd.fujixerox.docuworks":{"source":"iana","extensions":["xdw"]},"application/vnd.fujixerox.docuworks.binder":{"source":"iana","extensions":["xbd"]},"application/vnd.fujixerox.docuworks.container":{"source":"iana"},"application/vnd.fujixerox.hbpl":{"source":"iana"},"application/vnd.fut-misnet":{"source":"iana"},"application/vnd.futoin+cbor":{"source":"iana"},"application/vnd.futoin+json":{"source":"iana","compressible":true},"application/vnd.fuzzysheet":{"source":"iana","extensions":["fzs"]},"application/vnd.genomatix.tuxedo":{"source":"iana","extensions":["txd"]},"application/vnd.gentics.grd+json":{"source":"iana","compressible":true},"application/vnd.geo+json":{"source":"iana","compressible":true},"application/vnd.geocube+xml":{"source":"iana","compressible":true},"application/vnd.geogebra.file":{"source":"iana","extensions":["ggb"]},"application/vnd.geogebra.slides":{"source":"iana"},"application/vnd.geogebra.tool":{"source":"iana","extensions":["ggt"]},"application/vnd.geometry-explorer":{"source":"iana","extensions":["gex","gre"]},"application/vnd.geonext":{"source":"iana","extensions":["gxt"]},"application/vnd.geoplan":{"source":"iana","extensions":["g2w"]},"application/vnd.geospace":{"source":"iana","extensions":["g3w"]},"application/vnd.gerber":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt-response":{"source":"iana"},"application/vnd.gmx":{"source":"iana","extensions":["gmx"]},"application/vnd.google-apps.document":{"compressible":false,"extensions":["gdoc"]},"application/vnd.google-apps.presentation":{"compressible":false,"extensions":["gslides"]},"application/vnd.google-apps.spreadsheet":{"compressible":false,"extensions":["gsheet"]},"application/vnd.google-earth.kml+xml":{"source":"iana","compressible":true,"extensions":["kml"]},"application/vnd.google-earth.kmz":{"source":"iana","compressible":false,"extensions":["kmz"]},"application/vnd.gov.sk.e-form+xml":{"source":"iana","compressible":true},"application/vnd.gov.sk.e-form+zip":{"source":"iana","compressible":false},"application/vnd.gov.sk.xmldatacontainer+xml":{"source":"iana","compressible":true},"application/vnd.grafeq":{"source":"iana","extensions":["gqf","gqs"]},"application/vnd.gridmp":{"source":"iana"},"application/vnd.groove-account":{"source":"iana","extensions":["gac"]},"application/vnd.groove-help":{"source":"iana","extensions":["ghf"]},"application/vnd.groove-identity-message":{"source":"iana","extensions":["gim"]},"application/vnd.groove-injector":{"source":"iana","extensions":["grv"]},"application/vnd.groove-tool-message":{"source":"iana","extensions":["gtm"]},"application/vnd.groove-tool-template":{"source":"iana","extensions":["tpl"]},"application/vnd.groove-vcard":{"source":"iana","extensions":["vcg"]},"application/vnd.hal+json":{"source":"iana","compressible":true},"application/vnd.hal+xml":{"source":"iana","compressible":true,"extensions":["hal"]},"application/vnd.handheld-entertainment+xml":{"source":"iana","compressible":true,"extensions":["zmm"]},"application/vnd.hbci":{"source":"iana","extensions":["hbci"]},"application/vnd.hc+json":{"source":"iana","compressible":true},"application/vnd.hcl-bireports":{"source":"iana"},"application/vnd.hdt":{"source":"iana"},"application/vnd.heroku+json":{"source":"iana","compressible":true},"application/vnd.hhe.lesson-player":{"source":"iana","extensions":["les"]},"application/vnd.hl7cda+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hl7v2+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hp-hpgl":{"source":"iana","extensions":["hpgl"]},"application/vnd.hp-hpid":{"source":"iana","extensions":["hpid"]},"application/vnd.hp-hps":{"source":"iana","extensions":["hps"]},"application/vnd.hp-jlyt":{"source":"iana","extensions":["jlt"]},"application/vnd.hp-pcl":{"source":"iana","extensions":["pcl"]},"application/vnd.hp-pclxl":{"source":"iana","extensions":["pclxl"]},"application/vnd.httphone":{"source":"iana"},"application/vnd.hydrostatix.sof-data":{"source":"iana","extensions":["sfd-hdstx"]},"application/vnd.hyper+json":{"source":"iana","compressible":true},"application/vnd.hyper-item+json":{"source":"iana","compressible":true},"application/vnd.hyperdrive+json":{"source":"iana","compressible":true},"application/vnd.hzn-3d-crossword":{"source":"iana"},"application/vnd.ibm.afplinedata":{"source":"iana"},"application/vnd.ibm.electronic-media":{"source":"iana"},"application/vnd.ibm.minipay":{"source":"iana","extensions":["mpy"]},"application/vnd.ibm.modcap":{"source":"iana","extensions":["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{"source":"iana","extensions":["irm"]},"application/vnd.ibm.secure-container":{"source":"iana","extensions":["sc"]},"application/vnd.iccprofile":{"source":"iana","extensions":["icc","icm"]},"application/vnd.ieee.1905":{"source":"iana"},"application/vnd.igloader":{"source":"iana","extensions":["igl"]},"application/vnd.imagemeter.folder+zip":{"source":"iana","compressible":false},"application/vnd.imagemeter.image+zip":{"source":"iana","compressible":false},"application/vnd.immervision-ivp":{"source":"iana","extensions":["ivp"]},"application/vnd.immervision-ivu":{"source":"iana","extensions":["ivu"]},"application/vnd.ims.imsccv1p1":{"source":"iana"},"application/vnd.ims.imsccv1p2":{"source":"iana"},"application/vnd.ims.imsccv1p3":{"source":"iana"},"application/vnd.ims.lis.v2.result+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy.id+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings.simple+json":{"source":"iana","compressible":true},"application/vnd.informedcontrol.rms+xml":{"source":"iana","compressible":true},"application/vnd.informix-visionary":{"source":"iana"},"application/vnd.infotech.project":{"source":"iana"},"application/vnd.infotech.project+xml":{"source":"iana","compressible":true},"application/vnd.innopath.wamp.notification":{"source":"iana"},"application/vnd.insors.igm":{"source":"iana","extensions":["igm"]},"application/vnd.intercon.formnet":{"source":"iana","extensions":["xpw","xpx"]},"application/vnd.intergeo":{"source":"iana","extensions":["i2g"]},"application/vnd.intertrust.digibox":{"source":"iana"},"application/vnd.intertrust.nncp":{"source":"iana"},"application/vnd.intu.qbo":{"source":"iana","extensions":["qbo"]},"application/vnd.intu.qfx":{"source":"iana","extensions":["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.conceptitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.knowledgeitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsmessage+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.packageitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.planningitem+xml":{"source":"iana","compressible":true},"application/vnd.ipunplugged.rcprofile":{"source":"iana","extensions":["rcprofile"]},"application/vnd.irepository.package+xml":{"source":"iana","compressible":true,"extensions":["irp"]},"application/vnd.is-xpr":{"source":"iana","extensions":["xpr"]},"application/vnd.isac.fcs":{"source":"iana","extensions":["fcs"]},"application/vnd.iso11783-10+zip":{"source":"iana","compressible":false},"application/vnd.jam":{"source":"iana","extensions":["jam"]},"application/vnd.japannet-directory-service":{"source":"iana"},"application/vnd.japannet-jpnstore-wakeup":{"source":"iana"},"application/vnd.japannet-payment-wakeup":{"source":"iana"},"application/vnd.japannet-registration":{"source":"iana"},"application/vnd.japannet-registration-wakeup":{"source":"iana"},"application/vnd.japannet-setstore-wakeup":{"source":"iana"},"application/vnd.japannet-verification":{"source":"iana"},"application/vnd.japannet-verification-wakeup":{"source":"iana"},"application/vnd.jcp.javame.midlet-rms":{"source":"iana","extensions":["rms"]},"application/vnd.jisp":{"source":"iana","extensions":["jisp"]},"application/vnd.joost.joda-archive":{"source":"iana","extensions":["joda"]},"application/vnd.jsk.isdn-ngn":{"source":"iana"},"application/vnd.kahootz":{"source":"iana","extensions":["ktz","ktr"]},"application/vnd.kde.karbon":{"source":"iana","extensions":["karbon"]},"application/vnd.kde.kchart":{"source":"iana","extensions":["chrt"]},"application/vnd.kde.kformula":{"source":"iana","extensions":["kfo"]},"application/vnd.kde.kivio":{"source":"iana","extensions":["flw"]},"application/vnd.kde.kontour":{"source":"iana","extensions":["kon"]},"application/vnd.kde.kpresenter":{"source":"iana","extensions":["kpr","kpt"]},"application/vnd.kde.kspread":{"source":"iana","extensions":["ksp"]},"application/vnd.kde.kword":{"source":"iana","extensions":["kwd","kwt"]},"application/vnd.kenameaapp":{"source":"iana","extensions":["htke"]},"application/vnd.kidspiration":{"source":"iana","extensions":["kia"]},"application/vnd.kinar":{"source":"iana","extensions":["kne","knp"]},"application/vnd.koan":{"source":"iana","extensions":["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{"source":"iana","extensions":["sse"]},"application/vnd.las":{"source":"iana"},"application/vnd.las.las+json":{"source":"iana","compressible":true},"application/vnd.las.las+xml":{"source":"iana","compressible":true,"extensions":["lasxml"]},"application/vnd.laszip":{"source":"iana"},"application/vnd.leap+json":{"source":"iana","compressible":true},"application/vnd.liberty-request+xml":{"source":"iana","compressible":true},"application/vnd.llamagraphics.life-balance.desktop":{"source":"iana","extensions":["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{"source":"iana","compressible":true,"extensions":["lbe"]},"application/vnd.logipipe.circuit+zip":{"source":"iana","compressible":false},"application/vnd.loom":{"source":"iana"},"application/vnd.lotus-1-2-3":{"source":"iana","extensions":["123"]},"application/vnd.lotus-approach":{"source":"iana","extensions":["apr"]},"application/vnd.lotus-freelance":{"source":"iana","extensions":["pre"]},"application/vnd.lotus-notes":{"source":"iana","extensions":["nsf"]},"application/vnd.lotus-organizer":{"source":"iana","extensions":["org"]},"application/vnd.lotus-screencam":{"source":"iana","extensions":["scm"]},"application/vnd.lotus-wordpro":{"source":"iana","extensions":["lwp"]},"application/vnd.macports.portpkg":{"source":"iana","extensions":["portpkg"]},"application/vnd.mapbox-vector-tile":{"source":"iana","extensions":["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.conftoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.license+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.mdcf":{"source":"iana"},"application/vnd.mason+json":{"source":"iana","compressible":true},"application/vnd.maxar.archive.3tz+zip":{"source":"iana","compressible":false},"application/vnd.maxmind.maxmind-db":{"source":"iana"},"application/vnd.mcd":{"source":"iana","extensions":["mcd"]},"application/vnd.medcalcdata":{"source":"iana","extensions":["mc1"]},"application/vnd.mediastation.cdkey":{"source":"iana","extensions":["cdkey"]},"application/vnd.meridian-slingshot":{"source":"iana"},"application/vnd.mfer":{"source":"iana","extensions":["mwf"]},"application/vnd.mfmp":{"source":"iana","extensions":["mfm"]},"application/vnd.micro+json":{"source":"iana","compressible":true},"application/vnd.micrografx.flo":{"source":"iana","extensions":["flo"]},"application/vnd.micrografx.igx":{"source":"iana","extensions":["igx"]},"application/vnd.microsoft.portable-executable":{"source":"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{"source":"iana"},"application/vnd.miele+json":{"source":"iana","compressible":true},"application/vnd.mif":{"source":"iana","extensions":["mif"]},"application/vnd.minisoft-hp3000-save":{"source":"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{"source":"iana"},"application/vnd.mobius.daf":{"source":"iana","extensions":["daf"]},"application/vnd.mobius.dis":{"source":"iana","extensions":["dis"]},"application/vnd.mobius.mbk":{"source":"iana","extensions":["mbk"]},"application/vnd.mobius.mqy":{"source":"iana","extensions":["mqy"]},"application/vnd.mobius.msl":{"source":"iana","extensions":["msl"]},"application/vnd.mobius.plc":{"source":"iana","extensions":["plc"]},"application/vnd.mobius.txf":{"source":"iana","extensions":["txf"]},"application/vnd.mophun.application":{"source":"iana","extensions":["mpn"]},"application/vnd.mophun.certificate":{"source":"iana","extensions":["mpc"]},"application/vnd.motorola.flexsuite":{"source":"iana"},"application/vnd.motorola.flexsuite.adsi":{"source":"iana"},"application/vnd.motorola.flexsuite.fis":{"source":"iana"},"application/vnd.motorola.flexsuite.gotap":{"source":"iana"},"application/vnd.motorola.flexsuite.kmr":{"source":"iana"},"application/vnd.motorola.flexsuite.ttc":{"source":"iana"},"application/vnd.motorola.flexsuite.wem":{"source":"iana"},"application/vnd.motorola.iprm":{"source":"iana"},"application/vnd.mozilla.xul+xml":{"source":"iana","compressible":true,"extensions":["xul"]},"application/vnd.ms-3mfdocument":{"source":"iana"},"application/vnd.ms-artgalry":{"source":"iana","extensions":["cil"]},"application/vnd.ms-asf":{"source":"iana"},"application/vnd.ms-cab-compressed":{"source":"iana","extensions":["cab"]},"application/vnd.ms-color.iccprofile":{"source":"apache"},"application/vnd.ms-excel":{"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{"source":"iana","extensions":["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{"source":"iana","extensions":["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{"source":"iana","extensions":["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{"source":"iana","extensions":["xltm"]},"application/vnd.ms-fontobject":{"source":"iana","compressible":true,"extensions":["eot"]},"application/vnd.ms-htmlhelp":{"source":"iana","extensions":["chm"]},"application/vnd.ms-ims":{"source":"iana","extensions":["ims"]},"application/vnd.ms-lrm":{"source":"iana","extensions":["lrm"]},"application/vnd.ms-office.activex+xml":{"source":"iana","compressible":true},"application/vnd.ms-officetheme":{"source":"iana","extensions":["thmx"]},"application/vnd.ms-opentype":{"source":"apache","compressible":true},"application/vnd.ms-outlook":{"compressible":false,"extensions":["msg"]},"application/vnd.ms-package.obfuscated-opentype":{"source":"apache"},"application/vnd.ms-pki.seccat":{"source":"apache","extensions":["cat"]},"application/vnd.ms-pki.stl":{"source":"apache","extensions":["stl"]},"application/vnd.ms-playready.initiator+xml":{"source":"iana","compressible":true},"application/vnd.ms-powerpoint":{"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{"source":"iana","extensions":["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{"source":"iana","extensions":["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{"source":"iana","extensions":["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{"source":"iana","extensions":["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{"source":"iana","extensions":["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{"source":"iana","compressible":true},"application/vnd.ms-printing.printticket+xml":{"source":"apache","compressible":true},"application/vnd.ms-printschematicket+xml":{"source":"iana","compressible":true},"application/vnd.ms-project":{"source":"iana","extensions":["mpp","mpt"]},"application/vnd.ms-tnef":{"source":"iana"},"application/vnd.ms-windows.devicepairing":{"source":"iana"},"application/vnd.ms-windows.nwprinting.oob":{"source":"iana"},"application/vnd.ms-windows.printerpairing":{"source":"iana"},"application/vnd.ms-windows.wsd.oob":{"source":"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.lic-resp":{"source":"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.meter-resp":{"source":"iana"},"application/vnd.ms-word.document.macroenabled.12":{"source":"iana","extensions":["docm"]},"application/vnd.ms-word.template.macroenabled.12":{"source":"iana","extensions":["dotm"]},"application/vnd.ms-works":{"source":"iana","extensions":["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{"source":"iana","extensions":["wpl"]},"application/vnd.ms-xpsdocument":{"source":"iana","compressible":false,"extensions":["xps"]},"application/vnd.msa-disk-image":{"source":"iana"},"application/vnd.mseq":{"source":"iana","extensions":["mseq"]},"application/vnd.msign":{"source":"iana"},"application/vnd.multiad.creator":{"source":"iana"},"application/vnd.multiad.creator.cif":{"source":"iana"},"application/vnd.music-niff":{"source":"iana"},"application/vnd.musician":{"source":"iana","extensions":["mus"]},"application/vnd.muvee.style":{"source":"iana","extensions":["msty"]},"application/vnd.mynfc":{"source":"iana","extensions":["taglet"]},"application/vnd.nacamar.ybrid+json":{"source":"iana","compressible":true},"application/vnd.ncd.control":{"source":"iana"},"application/vnd.ncd.reference":{"source":"iana"},"application/vnd.nearst.inv+json":{"source":"iana","compressible":true},"application/vnd.nebumind.line":{"source":"iana"},"application/vnd.nervana":{"source":"iana"},"application/vnd.netfpx":{"source":"iana"},"application/vnd.neurolanguage.nlu":{"source":"iana","extensions":["nlu"]},"application/vnd.nimn":{"source":"iana"},"application/vnd.nintendo.nitro.rom":{"source":"iana"},"application/vnd.nintendo.snes.rom":{"source":"iana"},"application/vnd.nitf":{"source":"iana","extensions":["ntf","nitf"]},"application/vnd.noblenet-directory":{"source":"iana","extensions":["nnd"]},"application/vnd.noblenet-sealer":{"source":"iana","extensions":["nns"]},"application/vnd.noblenet-web":{"source":"iana","extensions":["nnw"]},"application/vnd.nokia.catalogs":{"source":"iana"},"application/vnd.nokia.conml+wbxml":{"source":"iana"},"application/vnd.nokia.conml+xml":{"source":"iana","compressible":true},"application/vnd.nokia.iptv.config+xml":{"source":"iana","compressible":true},"application/vnd.nokia.isds-radio-presets":{"source":"iana"},"application/vnd.nokia.landmark+wbxml":{"source":"iana"},"application/vnd.nokia.landmark+xml":{"source":"iana","compressible":true},"application/vnd.nokia.landmarkcollection+xml":{"source":"iana","compressible":true},"application/vnd.nokia.n-gage.ac+xml":{"source":"iana","compressible":true,"extensions":["ac"]},"application/vnd.nokia.n-gage.data":{"source":"iana","extensions":["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{"source":"iana","extensions":["n-gage"]},"application/vnd.nokia.ncd":{"source":"iana"},"application/vnd.nokia.pcd+wbxml":{"source":"iana"},"application/vnd.nokia.pcd+xml":{"source":"iana","compressible":true},"application/vnd.nokia.radio-preset":{"source":"iana","extensions":["rpst"]},"application/vnd.nokia.radio-presets":{"source":"iana","extensions":["rpss"]},"application/vnd.novadigm.edm":{"source":"iana","extensions":["edm"]},"application/vnd.novadigm.edx":{"source":"iana","extensions":["edx"]},"application/vnd.novadigm.ext":{"source":"iana","extensions":["ext"]},"application/vnd.ntt-local.content-share":{"source":"iana"},"application/vnd.ntt-local.file-transfer":{"source":"iana"},"application/vnd.ntt-local.ogw_remote-access":{"source":"iana"},"application/vnd.ntt-local.sip-ta_remote":{"source":"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{"source":"iana"},"application/vnd.oasis.opendocument.chart":{"source":"iana","extensions":["odc"]},"application/vnd.oasis.opendocument.chart-template":{"source":"iana","extensions":["otc"]},"application/vnd.oasis.opendocument.database":{"source":"iana","extensions":["odb"]},"application/vnd.oasis.opendocument.formula":{"source":"iana","extensions":["odf"]},"application/vnd.oasis.opendocument.formula-template":{"source":"iana","extensions":["odft"]},"application/vnd.oasis.opendocument.graphics":{"source":"iana","compressible":false,"extensions":["odg"]},"application/vnd.oasis.opendocument.graphics-template":{"source":"iana","extensions":["otg"]},"application/vnd.oasis.opendocument.image":{"source":"iana","extensions":["odi"]},"application/vnd.oasis.opendocument.image-template":{"source":"iana","extensions":["oti"]},"application/vnd.oasis.opendocument.presentation":{"source":"iana","compressible":false,"extensions":["odp"]},"application/vnd.oasis.opendocument.presentation-template":{"source":"iana","extensions":["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{"source":"iana","compressible":false,"extensions":["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{"source":"iana","extensions":["ots"]},"application/vnd.oasis.opendocument.text":{"source":"iana","compressible":false,"extensions":["odt"]},"application/vnd.oasis.opendocument.text-master":{"source":"iana","extensions":["odm"]},"application/vnd.oasis.opendocument.text-template":{"source":"iana","extensions":["ott"]},"application/vnd.oasis.opendocument.text-web":{"source":"iana","extensions":["oth"]},"application/vnd.obn":{"source":"iana"},"application/vnd.ocf+cbor":{"source":"iana"},"application/vnd.oci.image.manifest.v1+json":{"source":"iana","compressible":true},"application/vnd.oftn.l10n+json":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessdownload+xml":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessstreaming+xml":{"source":"iana","compressible":true},"application/vnd.oipf.cspg-hexbinary":{"source":"iana"},"application/vnd.oipf.dae.svg+xml":{"source":"iana","compressible":true},"application/vnd.oipf.dae.xhtml+xml":{"source":"iana","compressible":true},"application/vnd.oipf.mippvcontrolmessage+xml":{"source":"iana","compressible":true},"application/vnd.oipf.pae.gem":{"source":"iana"},"application/vnd.oipf.spdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.oipf.spdlist+xml":{"source":"iana","compressible":true},"application/vnd.oipf.ueprofile+xml":{"source":"iana","compressible":true},"application/vnd.oipf.userprofile+xml":{"source":"iana","compressible":true},"application/vnd.olpc-sugar":{"source":"iana","extensions":["xo"]},"application/vnd.oma-scws-config":{"source":"iana"},"application/vnd.oma-scws-http-request":{"source":"iana"},"application/vnd.oma-scws-http-response":{"source":"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.drm-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.imd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.ltkm":{"source":"iana"},"application/vnd.oma.bcast.notification+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.provisioningtrigger":{"source":"iana"},"application/vnd.oma.bcast.sgboot":{"source":"iana"},"application/vnd.oma.bcast.sgdd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sgdu":{"source":"iana"},"application/vnd.oma.bcast.simple-symbol-container":{"source":"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sprov+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.stkm":{"source":"iana"},"application/vnd.oma.cab-address-book+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-feature-handler+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-pcc+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-subs-invite+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-user-prefs+xml":{"source":"iana","compressible":true},"application/vnd.oma.dcd":{"source":"iana"},"application/vnd.oma.dcdc":{"source":"iana"},"application/vnd.oma.dd2+xml":{"source":"iana","compressible":true,"extensions":["dd2"]},"application/vnd.oma.drm.risd+xml":{"source":"iana","compressible":true},"application/vnd.oma.group-usage-list+xml":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+cbor":{"source":"iana"},"application/vnd.oma.lwm2m+json":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+tlv":{"source":"iana"},"application/vnd.oma.pal+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.detailed-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.final-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.groups+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.invocation-descriptor+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.optimized-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.push":{"source":"iana"},"application/vnd.oma.scidm.messages+xml":{"source":"iana","compressible":true},"application/vnd.oma.xcap-directory+xml":{"source":"iana","compressible":true},"application/vnd.omads-email+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-file+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-folder+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omaloc-supl-init":{"source":"iana"},"application/vnd.onepager":{"source":"iana"},"application/vnd.onepagertamp":{"source":"iana"},"application/vnd.onepagertamx":{"source":"iana"},"application/vnd.onepagertat":{"source":"iana"},"application/vnd.onepagertatp":{"source":"iana"},"application/vnd.onepagertatx":{"source":"iana"},"application/vnd.openblox.game+xml":{"source":"iana","compressible":true,"extensions":["obgx"]},"application/vnd.openblox.game-binary":{"source":"iana"},"application/vnd.openeye.oeb":{"source":"iana"},"application/vnd.openofficeorg.extension":{"source":"apache","extensions":["oxt"]},"application/vnd.openstreetmap.data+xml":{"source":"iana","compressible":true,"extensions":["osm"]},"application/vnd.opentimestamps.ots":{"source":"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawing+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{"source":"iana","compressible":false,"extensions":["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slide":{"source":"iana","extensions":["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{"source":"iana","extensions":["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.template":{"source":"iana","extensions":["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"source":"iana","compressible":false,"extensions":["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{"source":"iana","extensions":["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.theme+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.vmldrawing":{"source":"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{"source":"iana","compressible":false,"extensions":["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{"source":"iana","extensions":["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.core-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.relationships+xml":{"source":"iana","compressible":true},"application/vnd.oracle.resource+json":{"source":"iana","compressible":true},"application/vnd.orange.indata":{"source":"iana"},"application/vnd.osa.netdeploy":{"source":"iana"},"application/vnd.osgeo.mapguide.package":{"source":"iana","extensions":["mgp"]},"application/vnd.osgi.bundle":{"source":"iana"},"application/vnd.osgi.dp":{"source":"iana","extensions":["dp"]},"application/vnd.osgi.subsystem":{"source":"iana","extensions":["esa"]},"application/vnd.otps.ct-kip+xml":{"source":"iana","compressible":true},"application/vnd.oxli.countgraph":{"source":"iana"},"application/vnd.pagerduty+json":{"source":"iana","compressible":true},"application/vnd.palm":{"source":"iana","extensions":["pdb","pqa","oprc"]},"application/vnd.panoply":{"source":"iana"},"application/vnd.paos.xml":{"source":"iana"},"application/vnd.patentdive":{"source":"iana"},"application/vnd.patientecommsdoc":{"source":"iana"},"application/vnd.pawaafile":{"source":"iana","extensions":["paw"]},"application/vnd.pcos":{"source":"iana"},"application/vnd.pg.format":{"source":"iana","extensions":["str"]},"application/vnd.pg.osasli":{"source":"iana","extensions":["ei6"]},"application/vnd.piaccess.application-licence":{"source":"iana"},"application/vnd.picsel":{"source":"iana","extensions":["efif"]},"application/vnd.pmi.widget":{"source":"iana","extensions":["wg"]},"application/vnd.poc.group-advertisement+xml":{"source":"iana","compressible":true},"application/vnd.pocketlearn":{"source":"iana","extensions":["plf"]},"application/vnd.powerbuilder6":{"source":"iana","extensions":["pbd"]},"application/vnd.powerbuilder6-s":{"source":"iana"},"application/vnd.powerbuilder7":{"source":"iana"},"application/vnd.powerbuilder7-s":{"source":"iana"},"application/vnd.powerbuilder75":{"source":"iana"},"application/vnd.powerbuilder75-s":{"source":"iana"},"application/vnd.preminet":{"source":"iana"},"application/vnd.previewsystems.box":{"source":"iana","extensions":["box"]},"application/vnd.proteus.magazine":{"source":"iana","extensions":["mgz"]},"application/vnd.psfs":{"source":"iana"},"application/vnd.publishare-delta-tree":{"source":"iana","extensions":["qps"]},"application/vnd.pvi.ptid1":{"source":"iana","extensions":["ptid"]},"application/vnd.pwg-multiplexed":{"source":"iana"},"application/vnd.pwg-xhtml-print+xml":{"source":"iana","compressible":true},"application/vnd.qualcomm.brew-app-res":{"source":"iana"},"application/vnd.quarantainenet":{"source":"iana"},"application/vnd.quark.quarkxpress":{"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{"source":"iana"},"application/vnd.radisys.moml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conn+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-stream+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-base+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-detect+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-group+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-speech+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-transform+xml":{"source":"iana","compressible":true},"application/vnd.rainstor.data":{"source":"iana"},"application/vnd.rapid":{"source":"iana"},"application/vnd.rar":{"source":"iana","extensions":["rar"]},"application/vnd.realvnc.bed":{"source":"iana","extensions":["bed"]},"application/vnd.recordare.musicxml":{"source":"iana","extensions":["mxl"]},"application/vnd.recordare.musicxml+xml":{"source":"iana","compressible":true,"extensions":["musicxml"]},"application/vnd.renlearn.rlprint":{"source":"iana"},"application/vnd.resilient.logic":{"source":"iana"},"application/vnd.restful+json":{"source":"iana","compressible":true},"application/vnd.rig.cryptonote":{"source":"iana","extensions":["cryptonote"]},"application/vnd.rim.cod":{"source":"apache","extensions":["cod"]},"application/vnd.rn-realmedia":{"source":"apache","extensions":["rm"]},"application/vnd.rn-realmedia-vbr":{"source":"apache","extensions":["rmvb"]},"application/vnd.route66.link66+xml":{"source":"iana","compressible":true,"extensions":["link66"]},"application/vnd.rs-274x":{"source":"iana"},"application/vnd.ruckus.download":{"source":"iana"},"application/vnd.s3sms":{"source":"iana"},"application/vnd.sailingtracker.track":{"source":"iana","extensions":["st"]},"application/vnd.sar":{"source":"iana"},"application/vnd.sbm.cid":{"source":"iana"},"application/vnd.sbm.mid2":{"source":"iana"},"application/vnd.scribus":{"source":"iana"},"application/vnd.sealed.3df":{"source":"iana"},"application/vnd.sealed.csf":{"source":"iana"},"application/vnd.sealed.doc":{"source":"iana"},"application/vnd.sealed.eml":{"source":"iana"},"application/vnd.sealed.mht":{"source":"iana"},"application/vnd.sealed.net":{"source":"iana"},"application/vnd.sealed.ppt":{"source":"iana"},"application/vnd.sealed.tiff":{"source":"iana"},"application/vnd.sealed.xls":{"source":"iana"},"application/vnd.sealedmedia.softseal.html":{"source":"iana"},"application/vnd.sealedmedia.softseal.pdf":{"source":"iana"},"application/vnd.seemail":{"source":"iana","extensions":["see"]},"application/vnd.seis+json":{"source":"iana","compressible":true},"application/vnd.sema":{"source":"iana","extensions":["sema"]},"application/vnd.semd":{"source":"iana","extensions":["semd"]},"application/vnd.semf":{"source":"iana","extensions":["semf"]},"application/vnd.shade-save-file":{"source":"iana"},"application/vnd.shana.informed.formdata":{"source":"iana","extensions":["ifm"]},"application/vnd.shana.informed.formtemplate":{"source":"iana","extensions":["itp"]},"application/vnd.shana.informed.interchange":{"source":"iana","extensions":["iif"]},"application/vnd.shana.informed.package":{"source":"iana","extensions":["ipk"]},"application/vnd.shootproof+json":{"source":"iana","compressible":true},"application/vnd.shopkick+json":{"source":"iana","compressible":true},"application/vnd.shp":{"source":"iana"},"application/vnd.shx":{"source":"iana"},"application/vnd.sigrok.session":{"source":"iana"},"application/vnd.simtech-mindmapper":{"source":"iana","extensions":["twd","twds"]},"application/vnd.siren+json":{"source":"iana","compressible":true},"application/vnd.smaf":{"source":"iana","extensions":["mmf"]},"application/vnd.smart.notebook":{"source":"iana"},"application/vnd.smart.teacher":{"source":"iana","extensions":["teacher"]},"application/vnd.snesdev-page-table":{"source":"iana"},"application/vnd.software602.filler.form+xml":{"source":"iana","compressible":true,"extensions":["fo"]},"application/vnd.software602.filler.form-xml-zip":{"source":"iana"},"application/vnd.solent.sdkm+xml":{"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{"source":"iana","extensions":["dxp"]},"application/vnd.spotfire.sfs":{"source":"iana","extensions":["sfs"]},"application/vnd.sqlite3":{"source":"iana"},"application/vnd.sss-cod":{"source":"iana"},"application/vnd.sss-dtf":{"source":"iana"},"application/vnd.sss-ntf":{"source":"iana"},"application/vnd.stardivision.calc":{"source":"apache","extensions":["sdc"]},"application/vnd.stardivision.draw":{"source":"apache","extensions":["sda"]},"application/vnd.stardivision.impress":{"source":"apache","extensions":["sdd"]},"application/vnd.stardivision.math":{"source":"apache","extensions":["smf"]},"application/vnd.stardivision.writer":{"source":"apache","extensions":["sdw","vor"]},"application/vnd.stardivision.writer-global":{"source":"apache","extensions":["sgl"]},"application/vnd.stepmania.package":{"source":"iana","extensions":["smzip"]},"application/vnd.stepmania.stepchart":{"source":"iana","extensions":["sm"]},"application/vnd.street-stream":{"source":"iana"},"application/vnd.sun.wadl+xml":{"source":"iana","compressible":true,"extensions":["wadl"]},"application/vnd.sun.xml.calc":{"source":"apache","extensions":["sxc"]},"application/vnd.sun.xml.calc.template":{"source":"apache","extensions":["stc"]},"application/vnd.sun.xml.draw":{"source":"apache","extensions":["sxd"]},"application/vnd.sun.xml.draw.template":{"source":"apache","extensions":["std"]},"application/vnd.sun.xml.impress":{"source":"apache","extensions":["sxi"]},"application/vnd.sun.xml.impress.template":{"source":"apache","extensions":["sti"]},"application/vnd.sun.xml.math":{"source":"apache","extensions":["sxm"]},"application/vnd.sun.xml.writer":{"source":"apache","extensions":["sxw"]},"application/vnd.sun.xml.writer.global":{"source":"apache","extensions":["sxg"]},"application/vnd.sun.xml.writer.template":{"source":"apache","extensions":["stw"]},"application/vnd.sus-calendar":{"source":"iana","extensions":["sus","susp"]},"application/vnd.svd":{"source":"iana","extensions":["svd"]},"application/vnd.swiftview-ics":{"source":"iana"},"application/vnd.sycle+xml":{"source":"iana","compressible":true},"application/vnd.syft+json":{"source":"iana","compressible":true},"application/vnd.symbian.install":{"source":"apache","extensions":["sis","sisx"]},"application/vnd.syncml+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},"application/vnd.syncml.dm+wbxml":{"source":"iana","charset":"UTF-8","extensions":["bdm"]},"application/vnd.syncml.dm+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},"application/vnd.syncml.dm.notification":{"source":"iana"},"application/vnd.syncml.dmddf+wbxml":{"source":"iana"},"application/vnd.syncml.dmddf+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{"source":"iana"},"application/vnd.syncml.dmtnds+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.syncml.ds.notification":{"source":"iana"},"application/vnd.tableschema+json":{"source":"iana","compressible":true},"application/vnd.tao.intent-module-archive":{"source":"iana","extensions":["tao"]},"application/vnd.tcpdump.pcap":{"source":"iana","extensions":["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{"source":"iana","compressible":true},"application/vnd.tmd.mediaflex.api+xml":{"source":"iana","compressible":true},"application/vnd.tml":{"source":"iana"},"application/vnd.tmobile-livetv":{"source":"iana","extensions":["tmo"]},"application/vnd.tri.onesource":{"source":"iana"},"application/vnd.trid.tpt":{"source":"iana","extensions":["tpt"]},"application/vnd.triscape.mxs":{"source":"iana","extensions":["mxs"]},"application/vnd.trueapp":{"source":"iana","extensions":["tra"]},"application/vnd.truedoc":{"source":"iana"},"application/vnd.ubisoft.webplayer":{"source":"iana"},"application/vnd.ufdl":{"source":"iana","extensions":["ufd","ufdl"]},"application/vnd.uiq.theme":{"source":"iana","extensions":["utz"]},"application/vnd.umajin":{"source":"iana","extensions":["umj"]},"application/vnd.unity":{"source":"iana","extensions":["unityweb"]},"application/vnd.uoml+xml":{"source":"iana","compressible":true,"extensions":["uoml"]},"application/vnd.uplanet.alert":{"source":"iana"},"application/vnd.uplanet.alert-wbxml":{"source":"iana"},"application/vnd.uplanet.bearer-choice":{"source":"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{"source":"iana"},"application/vnd.uplanet.cacheop":{"source":"iana"},"application/vnd.uplanet.cacheop-wbxml":{"source":"iana"},"application/vnd.uplanet.channel":{"source":"iana"},"application/vnd.uplanet.channel-wbxml":{"source":"iana"},"application/vnd.uplanet.list":{"source":"iana"},"application/vnd.uplanet.list-wbxml":{"source":"iana"},"application/vnd.uplanet.listcmd":{"source":"iana"},"application/vnd.uplanet.listcmd-wbxml":{"source":"iana"},"application/vnd.uplanet.signal":{"source":"iana"},"application/vnd.uri-map":{"source":"iana"},"application/vnd.valve.source.material":{"source":"iana"},"application/vnd.vcx":{"source":"iana","extensions":["vcx"]},"application/vnd.vd-study":{"source":"iana"},"application/vnd.vectorworks":{"source":"iana"},"application/vnd.vel+json":{"source":"iana","compressible":true},"application/vnd.verimatrix.vcas":{"source":"iana"},"application/vnd.veritone.aion+json":{"source":"iana","compressible":true},"application/vnd.veryant.thin":{"source":"iana"},"application/vnd.ves.encrypted":{"source":"iana"},"application/vnd.vidsoft.vidconference":{"source":"iana"},"application/vnd.visio":{"source":"iana","extensions":["vsd","vst","vss","vsw"]},"application/vnd.visionary":{"source":"iana","extensions":["vis"]},"application/vnd.vividence.scriptfile":{"source":"iana"},"application/vnd.vsf":{"source":"iana","extensions":["vsf"]},"application/vnd.wap.sic":{"source":"iana"},"application/vnd.wap.slc":{"source":"iana"},"application/vnd.wap.wbxml":{"source":"iana","charset":"UTF-8","extensions":["wbxml"]},"application/vnd.wap.wmlc":{"source":"iana","extensions":["wmlc"]},"application/vnd.wap.wmlscriptc":{"source":"iana","extensions":["wmlsc"]},"application/vnd.webturbo":{"source":"iana","extensions":["wtb"]},"application/vnd.wfa.dpp":{"source":"iana"},"application/vnd.wfa.p2p":{"source":"iana"},"application/vnd.wfa.wsc":{"source":"iana"},"application/vnd.windows.devicepairing":{"source":"iana"},"application/vnd.wmc":{"source":"iana"},"application/vnd.wmf.bootstrap":{"source":"iana"},"application/vnd.wolfram.mathematica":{"source":"iana"},"application/vnd.wolfram.mathematica.package":{"source":"iana"},"application/vnd.wolfram.player":{"source":"iana","extensions":["nbp"]},"application/vnd.wordperfect":{"source":"iana","extensions":["wpd"]},"application/vnd.wqd":{"source":"iana","extensions":["wqd"]},"application/vnd.wrq-hp3000-labelled":{"source":"iana"},"application/vnd.wt.stf":{"source":"iana","extensions":["stf"]},"application/vnd.wv.csp+wbxml":{"source":"iana"},"application/vnd.wv.csp+xml":{"source":"iana","compressible":true},"application/vnd.wv.ssp+xml":{"source":"iana","compressible":true},"application/vnd.xacml+json":{"source":"iana","compressible":true},"application/vnd.xara":{"source":"iana","extensions":["xar"]},"application/vnd.xfdl":{"source":"iana","extensions":["xfdl"]},"application/vnd.xfdl.webform":{"source":"iana"},"application/vnd.xmi+xml":{"source":"iana","compressible":true},"application/vnd.xmpie.cpkg":{"source":"iana"},"application/vnd.xmpie.dpkg":{"source":"iana"},"application/vnd.xmpie.plan":{"source":"iana"},"application/vnd.xmpie.ppkg":{"source":"iana"},"application/vnd.xmpie.xlim":{"source":"iana"},"application/vnd.yamaha.hv-dic":{"source":"iana","extensions":["hvd"]},"application/vnd.yamaha.hv-script":{"source":"iana","extensions":["hvs"]},"application/vnd.yamaha.hv-voice":{"source":"iana","extensions":["hvp"]},"application/vnd.yamaha.openscoreformat":{"source":"iana","extensions":["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{"source":"iana","compressible":true,"extensions":["osfpvg"]},"application/vnd.yamaha.remote-setup":{"source":"iana"},"application/vnd.yamaha.smaf-audio":{"source":"iana","extensions":["saf"]},"application/vnd.yamaha.smaf-phrase":{"source":"iana","extensions":["spf"]},"application/vnd.yamaha.through-ngn":{"source":"iana"},"application/vnd.yamaha.tunnel-udpencap":{"source":"iana"},"application/vnd.yaoweme":{"source":"iana"},"application/vnd.yellowriver-custom-menu":{"source":"iana","extensions":["cmp"]},"application/vnd.youtube.yt":{"source":"iana"},"application/vnd.zul":{"source":"iana","extensions":["zir","zirz"]},"application/vnd.zzazz.deck+xml":{"source":"iana","compressible":true,"extensions":["zaz"]},"application/voicexml+xml":{"source":"iana","compressible":true,"extensions":["vxml"]},"application/voucher-cms+json":{"source":"iana","compressible":true},"application/vq-rtcpxr":{"source":"iana"},"application/wasm":{"source":"iana","compressible":true,"extensions":["wasm"]},"application/watcherinfo+xml":{"source":"iana","compressible":true,"extensions":["wif"]},"application/webpush-options+json":{"source":"iana","compressible":true},"application/whoispp-query":{"source":"iana"},"application/whoispp-response":{"source":"iana"},"application/widget":{"source":"iana","extensions":["wgt"]},"application/winhlp":{"source":"apache","extensions":["hlp"]},"application/wita":{"source":"iana"},"application/wordperfect5.1":{"source":"iana"},"application/wsdl+xml":{"source":"iana","compressible":true,"extensions":["wsdl"]},"application/wspolicy+xml":{"source":"iana","compressible":true,"extensions":["wspolicy"]},"application/x-7z-compressed":{"source":"apache","compressible":false,"extensions":["7z"]},"application/x-abiword":{"source":"apache","extensions":["abw"]},"application/x-ace-compressed":{"source":"apache","extensions":["ace"]},"application/x-amf":{"source":"apache"},"application/x-apple-diskimage":{"source":"apache","extensions":["dmg"]},"application/x-arj":{"compressible":false,"extensions":["arj"]},"application/x-authorware-bin":{"source":"apache","extensions":["aab","x32","u32","vox"]},"application/x-authorware-map":{"source":"apache","extensions":["aam"]},"application/x-authorware-seg":{"source":"apache","extensions":["aas"]},"application/x-bcpio":{"source":"apache","extensions":["bcpio"]},"application/x-bdoc":{"compressible":false,"extensions":["bdoc"]},"application/x-bittorrent":{"source":"apache","extensions":["torrent"]},"application/x-blorb":{"source":"apache","extensions":["blb","blorb"]},"application/x-bzip":{"source":"apache","compressible":false,"extensions":["bz"]},"application/x-bzip2":{"source":"apache","compressible":false,"extensions":["bz2","boz"]},"application/x-cbr":{"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{"source":"apache","extensions":["vcd"]},"application/x-cfs-compressed":{"source":"apache","extensions":["cfs"]},"application/x-chat":{"source":"apache","extensions":["chat"]},"application/x-chess-pgn":{"source":"apache","extensions":["pgn"]},"application/x-chrome-extension":{"extensions":["crx"]},"application/x-cocoa":{"source":"nginx","extensions":["cco"]},"application/x-compress":{"source":"apache"},"application/x-conference":{"source":"apache","extensions":["nsc"]},"application/x-cpio":{"source":"apache","extensions":["cpio"]},"application/x-csh":{"source":"apache","extensions":["csh"]},"application/x-deb":{"compressible":false},"application/x-debian-package":{"source":"apache","extensions":["deb","udeb"]},"application/x-dgc-compressed":{"source":"apache","extensions":["dgc"]},"application/x-director":{"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{"source":"apache","extensions":["wad"]},"application/x-dtbncx+xml":{"source":"apache","compressible":true,"extensions":["ncx"]},"application/x-dtbook+xml":{"source":"apache","compressible":true,"extensions":["dtb"]},"application/x-dtbresource+xml":{"source":"apache","compressible":true,"extensions":["res"]},"application/x-dvi":{"source":"apache","compressible":false,"extensions":["dvi"]},"application/x-envoy":{"source":"apache","extensions":["evy"]},"application/x-eva":{"source":"apache","extensions":["eva"]},"application/x-font-bdf":{"source":"apache","extensions":["bdf"]},"application/x-font-dos":{"source":"apache"},"application/x-font-framemaker":{"source":"apache"},"application/x-font-ghostscript":{"source":"apache","extensions":["gsf"]},"application/x-font-libgrx":{"source":"apache"},"application/x-font-linux-psf":{"source":"apache","extensions":["psf"]},"application/x-font-pcf":{"source":"apache","extensions":["pcf"]},"application/x-font-snf":{"source":"apache","extensions":["snf"]},"application/x-font-speedo":{"source":"apache"},"application/x-font-sunos-news":{"source":"apache"},"application/x-font-type1":{"source":"apache","extensions":["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{"source":"apache"},"application/x-freearc":{"source":"apache","extensions":["arc"]},"application/x-futuresplash":{"source":"apache","extensions":["spl"]},"application/x-gca-compressed":{"source":"apache","extensions":["gca"]},"application/x-glulx":{"source":"apache","extensions":["ulx"]},"application/x-gnumeric":{"source":"apache","extensions":["gnumeric"]},"application/x-gramps-xml":{"source":"apache","extensions":["gramps"]},"application/x-gtar":{"source":"apache","extensions":["gtar"]},"application/x-gzip":{"source":"apache"},"application/x-hdf":{"source":"apache","extensions":["hdf"]},"application/x-httpd-php":{"compressible":true,"extensions":["php"]},"application/x-install-instructions":{"source":"apache","extensions":["install"]},"application/x-iso9660-image":{"source":"apache","extensions":["iso"]},"application/x-iwork-keynote-sffkey":{"extensions":["key"]},"application/x-iwork-numbers-sffnumbers":{"extensions":["numbers"]},"application/x-iwork-pages-sffpages":{"extensions":["pages"]},"application/x-java-archive-diff":{"source":"nginx","extensions":["jardiff"]},"application/x-java-jnlp-file":{"source":"apache","compressible":false,"extensions":["jnlp"]},"application/x-javascript":{"compressible":true},"application/x-keepass2":{"extensions":["kdbx"]},"application/x-latex":{"source":"apache","compressible":false,"extensions":["latex"]},"application/x-lua-bytecode":{"extensions":["luac"]},"application/x-lzh-compressed":{"source":"apache","extensions":["lzh","lha"]},"application/x-makeself":{"source":"nginx","extensions":["run"]},"application/x-mie":{"source":"apache","extensions":["mie"]},"application/x-mobipocket-ebook":{"source":"apache","extensions":["prc","mobi"]},"application/x-mpegurl":{"compressible":false},"application/x-ms-application":{"source":"apache","extensions":["application"]},"application/x-ms-shortcut":{"source":"apache","extensions":["lnk"]},"application/x-ms-wmd":{"source":"apache","extensions":["wmd"]},"application/x-ms-wmz":{"source":"apache","extensions":["wmz"]},"application/x-ms-xbap":{"source":"apache","extensions":["xbap"]},"application/x-msaccess":{"source":"apache","extensions":["mdb"]},"application/x-msbinder":{"source":"apache","extensions":["obd"]},"application/x-mscardfile":{"source":"apache","extensions":["crd"]},"application/x-msclip":{"source":"apache","extensions":["clp"]},"application/x-msdos-program":{"extensions":["exe"]},"application/x-msdownload":{"source":"apache","extensions":["exe","dll","com","bat","msi"]},"application/x-msmediaview":{"source":"apache","extensions":["mvb","m13","m14"]},"application/x-msmetafile":{"source":"apache","extensions":["wmf","wmz","emf","emz"]},"application/x-msmoney":{"source":"apache","extensions":["mny"]},"application/x-mspublisher":{"source":"apache","extensions":["pub"]},"application/x-msschedule":{"source":"apache","extensions":["scd"]},"application/x-msterminal":{"source":"apache","extensions":["trm"]},"application/x-mswrite":{"source":"apache","extensions":["wri"]},"application/x-netcdf":{"source":"apache","extensions":["nc","cdf"]},"application/x-ns-proxy-autoconfig":{"compressible":true,"extensions":["pac"]},"application/x-nzb":{"source":"apache","extensions":["nzb"]},"application/x-perl":{"source":"nginx","extensions":["pl","pm"]},"application/x-pilot":{"source":"nginx","extensions":["prc","pdb"]},"application/x-pkcs12":{"source":"apache","compressible":false,"extensions":["p12","pfx"]},"application/x-pkcs7-certificates":{"source":"apache","extensions":["p7b","spc"]},"application/x-pkcs7-certreqresp":{"source":"apache","extensions":["p7r"]},"application/x-pki-message":{"source":"iana"},"application/x-rar-compressed":{"source":"apache","compressible":false,"extensions":["rar"]},"application/x-redhat-package-manager":{"source":"nginx","extensions":["rpm"]},"application/x-research-info-systems":{"source":"apache","extensions":["ris"]},"application/x-sea":{"source":"nginx","extensions":["sea"]},"application/x-sh":{"source":"apache","compressible":true,"extensions":["sh"]},"application/x-shar":{"source":"apache","extensions":["shar"]},"application/x-shockwave-flash":{"source":"apache","compressible":false,"extensions":["swf"]},"application/x-silverlight-app":{"source":"apache","extensions":["xap"]},"application/x-sql":{"source":"apache","extensions":["sql"]},"application/x-stuffit":{"source":"apache","compressible":false,"extensions":["sit"]},"application/x-stuffitx":{"source":"apache","extensions":["sitx"]},"application/x-subrip":{"source":"apache","extensions":["srt"]},"application/x-sv4cpio":{"source":"apache","extensions":["sv4cpio"]},"application/x-sv4crc":{"source":"apache","extensions":["sv4crc"]},"application/x-t3vm-image":{"source":"apache","extensions":["t3"]},"application/x-tads":{"source":"apache","extensions":["gam"]},"application/x-tar":{"source":"apache","compressible":true,"extensions":["tar"]},"application/x-tcl":{"source":"apache","extensions":["tcl","tk"]},"application/x-tex":{"source":"apache","extensions":["tex"]},"application/x-tex-tfm":{"source":"apache","extensions":["tfm"]},"application/x-texinfo":{"source":"apache","extensions":["texinfo","texi"]},"application/x-tgif":{"source":"apache","extensions":["obj"]},"application/x-ustar":{"source":"apache","extensions":["ustar"]},"application/x-virtualbox-hdd":{"compressible":true,"extensions":["hdd"]},"application/x-virtualbox-ova":{"compressible":true,"extensions":["ova"]},"application/x-virtualbox-ovf":{"compressible":true,"extensions":["ovf"]},"application/x-virtualbox-vbox":{"compressible":true,"extensions":["vbox"]},"application/x-virtualbox-vbox-extpack":{"compressible":false,"extensions":["vbox-extpack"]},"application/x-virtualbox-vdi":{"compressible":true,"extensions":["vdi"]},"application/x-virtualbox-vhd":{"compressible":true,"extensions":["vhd"]},"application/x-virtualbox-vmdk":{"compressible":true,"extensions":["vmdk"]},"application/x-wais-source":{"source":"apache","extensions":["src"]},"application/x-web-app-manifest+json":{"compressible":true,"extensions":["webapp"]},"application/x-www-form-urlencoded":{"source":"iana","compressible":true},"application/x-x509-ca-cert":{"source":"iana","extensions":["der","crt","pem"]},"application/x-x509-ca-ra-cert":{"source":"iana"},"application/x-x509-next-ca-cert":{"source":"iana"},"application/x-xfig":{"source":"apache","extensions":["fig"]},"application/x-xliff+xml":{"source":"apache","compressible":true,"extensions":["xlf"]},"application/x-xpinstall":{"source":"apache","compressible":false,"extensions":["xpi"]},"application/x-xz":{"source":"apache","extensions":["xz"]},"application/x-zmachine":{"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{"source":"iana"},"application/xacml+xml":{"source":"iana","compressible":true},"application/xaml+xml":{"source":"apache","compressible":true,"extensions":["xaml"]},"application/xcap-att+xml":{"source":"iana","compressible":true,"extensions":["xav"]},"application/xcap-caps+xml":{"source":"iana","compressible":true,"extensions":["xca"]},"application/xcap-diff+xml":{"source":"iana","compressible":true,"extensions":["xdf"]},"application/xcap-el+xml":{"source":"iana","compressible":true,"extensions":["xel"]},"application/xcap-error+xml":{"source":"iana","compressible":true},"application/xcap-ns+xml":{"source":"iana","compressible":true,"extensions":["xns"]},"application/xcon-conference-info+xml":{"source":"iana","compressible":true},"application/xcon-conference-info-diff+xml":{"source":"iana","compressible":true},"application/xenc+xml":{"source":"iana","compressible":true,"extensions":["xenc"]},"application/xhtml+xml":{"source":"iana","compressible":true,"extensions":["xhtml","xht"]},"application/xhtml-voice+xml":{"source":"apache","compressible":true},"application/xliff+xml":{"source":"iana","compressible":true,"extensions":["xlf"]},"application/xml":{"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},"application/xml-dtd":{"source":"iana","compressible":true,"extensions":["dtd"]},"application/xml-external-parsed-entity":{"source":"iana"},"application/xml-patch+xml":{"source":"iana","compressible":true},"application/xmpp+xml":{"source":"iana","compressible":true},"application/xop+xml":{"source":"iana","compressible":true,"extensions":["xop"]},"application/xproc+xml":{"source":"apache","compressible":true,"extensions":["xpl"]},"application/xslt+xml":{"source":"iana","compressible":true,"extensions":["xsl","xslt"]},"application/xspf+xml":{"source":"apache","compressible":true,"extensions":["xspf"]},"application/xv+xml":{"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},"application/yang":{"source":"iana","extensions":["yang"]},"application/yang-data+json":{"source":"iana","compressible":true},"application/yang-data+xml":{"source":"iana","compressible":true},"application/yang-patch+json":{"source":"iana","compressible":true},"application/yang-patch+xml":{"source":"iana","compressible":true},"application/yin+xml":{"source":"iana","compressible":true,"extensions":["yin"]},"application/zip":{"source":"iana","compressible":false,"extensions":["zip"]},"application/zlib":{"source":"iana"},"application/zstd":{"source":"iana"},"audio/1d-interleaved-parityfec":{"source":"iana"},"audio/32kadpcm":{"source":"iana"},"audio/3gpp":{"source":"iana","compressible":false,"extensions":["3gpp"]},"audio/3gpp2":{"source":"iana"},"audio/aac":{"source":"iana"},"audio/ac3":{"source":"iana"},"audio/adpcm":{"source":"apache","extensions":["adp"]},"audio/amr":{"source":"iana","extensions":["amr"]},"audio/amr-wb":{"source":"iana"},"audio/amr-wb+":{"source":"iana"},"audio/aptx":{"source":"iana"},"audio/asc":{"source":"iana"},"audio/atrac-advanced-lossless":{"source":"iana"},"audio/atrac-x":{"source":"iana"},"audio/atrac3":{"source":"iana"},"audio/basic":{"source":"iana","compressible":false,"extensions":["au","snd"]},"audio/bv16":{"source":"iana"},"audio/bv32":{"source":"iana"},"audio/clearmode":{"source":"iana"},"audio/cn":{"source":"iana"},"audio/dat12":{"source":"iana"},"audio/dls":{"source":"iana"},"audio/dsr-es201108":{"source":"iana"},"audio/dsr-es202050":{"source":"iana"},"audio/dsr-es202211":{"source":"iana"},"audio/dsr-es202212":{"source":"iana"},"audio/dv":{"source":"iana"},"audio/dvi4":{"source":"iana"},"audio/eac3":{"source":"iana"},"audio/encaprtp":{"source":"iana"},"audio/evrc":{"source":"iana"},"audio/evrc-qcp":{"source":"iana"},"audio/evrc0":{"source":"iana"},"audio/evrc1":{"source":"iana"},"audio/evrcb":{"source":"iana"},"audio/evrcb0":{"source":"iana"},"audio/evrcb1":{"source":"iana"},"audio/evrcnw":{"source":"iana"},"audio/evrcnw0":{"source":"iana"},"audio/evrcnw1":{"source":"iana"},"audio/evrcwb":{"source":"iana"},"audio/evrcwb0":{"source":"iana"},"audio/evrcwb1":{"source":"iana"},"audio/evs":{"source":"iana"},"audio/flexfec":{"source":"iana"},"audio/fwdred":{"source":"iana"},"audio/g711-0":{"source":"iana"},"audio/g719":{"source":"iana"},"audio/g722":{"source":"iana"},"audio/g7221":{"source":"iana"},"audio/g723":{"source":"iana"},"audio/g726-16":{"source":"iana"},"audio/g726-24":{"source":"iana"},"audio/g726-32":{"source":"iana"},"audio/g726-40":{"source":"iana"},"audio/g728":{"source":"iana"},"audio/g729":{"source":"iana"},"audio/g7291":{"source":"iana"},"audio/g729d":{"source":"iana"},"audio/g729e":{"source":"iana"},"audio/gsm":{"source":"iana"},"audio/gsm-efr":{"source":"iana"},"audio/gsm-hr-08":{"source":"iana"},"audio/ilbc":{"source":"iana"},"audio/ip-mr_v2.5":{"source":"iana"},"audio/isac":{"source":"apache"},"audio/l16":{"source":"iana"},"audio/l20":{"source":"iana"},"audio/l24":{"source":"iana","compressible":false},"audio/l8":{"source":"iana"},"audio/lpc":{"source":"iana"},"audio/melp":{"source":"iana"},"audio/melp1200":{"source":"iana"},"audio/melp2400":{"source":"iana"},"audio/melp600":{"source":"iana"},"audio/mhas":{"source":"iana"},"audio/midi":{"source":"apache","extensions":["mid","midi","kar","rmi"]},"audio/mobile-xmf":{"source":"iana","extensions":["mxmf"]},"audio/mp3":{"compressible":false,"extensions":["mp3"]},"audio/mp4":{"source":"iana","compressible":false,"extensions":["m4a","mp4a"]},"audio/mp4a-latm":{"source":"iana"},"audio/mpa":{"source":"iana"},"audio/mpa-robust":{"source":"iana"},"audio/mpeg":{"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{"source":"iana"},"audio/musepack":{"source":"apache"},"audio/ogg":{"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},"audio/opus":{"source":"iana"},"audio/parityfec":{"source":"iana"},"audio/pcma":{"source":"iana"},"audio/pcma-wb":{"source":"iana"},"audio/pcmu":{"source":"iana"},"audio/pcmu-wb":{"source":"iana"},"audio/prs.sid":{"source":"iana"},"audio/qcelp":{"source":"iana"},"audio/raptorfec":{"source":"iana"},"audio/red":{"source":"iana"},"audio/rtp-enc-aescm128":{"source":"iana"},"audio/rtp-midi":{"source":"iana"},"audio/rtploopback":{"source":"iana"},"audio/rtx":{"source":"iana"},"audio/s3m":{"source":"apache","extensions":["s3m"]},"audio/scip":{"source":"iana"},"audio/silk":{"source":"apache","extensions":["sil"]},"audio/smv":{"source":"iana"},"audio/smv-qcp":{"source":"iana"},"audio/smv0":{"source":"iana"},"audio/sofa":{"source":"iana"},"audio/sp-midi":{"source":"iana"},"audio/speex":{"source":"iana"},"audio/t140c":{"source":"iana"},"audio/t38":{"source":"iana"},"audio/telephone-event":{"source":"iana"},"audio/tetra_acelp":{"source":"iana"},"audio/tetra_acelp_bb":{"source":"iana"},"audio/tone":{"source":"iana"},"audio/tsvcis":{"source":"iana"},"audio/uemclip":{"source":"iana"},"audio/ulpfec":{"source":"iana"},"audio/usac":{"source":"iana"},"audio/vdvi":{"source":"iana"},"audio/vmr-wb":{"source":"iana"},"audio/vnd.3gpp.iufp":{"source":"iana"},"audio/vnd.4sb":{"source":"iana"},"audio/vnd.audiokoz":{"source":"iana"},"audio/vnd.celp":{"source":"iana"},"audio/vnd.cisco.nse":{"source":"iana"},"audio/vnd.cmles.radio-events":{"source":"iana"},"audio/vnd.cns.anp1":{"source":"iana"},"audio/vnd.cns.inf1":{"source":"iana"},"audio/vnd.dece.audio":{"source":"iana","extensions":["uva","uvva"]},"audio/vnd.digital-winds":{"source":"iana","extensions":["eol"]},"audio/vnd.dlna.adts":{"source":"iana"},"audio/vnd.dolby.heaac.1":{"source":"iana"},"audio/vnd.dolby.heaac.2":{"source":"iana"},"audio/vnd.dolby.mlp":{"source":"iana"},"audio/vnd.dolby.mps":{"source":"iana"},"audio/vnd.dolby.pl2":{"source":"iana"},"audio/vnd.dolby.pl2x":{"source":"iana"},"audio/vnd.dolby.pl2z":{"source":"iana"},"audio/vnd.dolby.pulse.1":{"source":"iana"},"audio/vnd.dra":{"source":"iana","extensions":["dra"]},"audio/vnd.dts":{"source":"iana","extensions":["dts"]},"audio/vnd.dts.hd":{"source":"iana","extensions":["dtshd"]},"audio/vnd.dts.uhd":{"source":"iana"},"audio/vnd.dvb.file":{"source":"iana"},"audio/vnd.everad.plj":{"source":"iana"},"audio/vnd.hns.audio":{"source":"iana"},"audio/vnd.lucent.voice":{"source":"iana","extensions":["lvp"]},"audio/vnd.ms-playready.media.pya":{"source":"iana","extensions":["pya"]},"audio/vnd.nokia.mobile-xmf":{"source":"iana"},"audio/vnd.nortel.vbk":{"source":"iana"},"audio/vnd.nuera.ecelp4800":{"source":"iana","extensions":["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{"source":"iana","extensions":["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{"source":"iana","extensions":["ecelp9600"]},"audio/vnd.octel.sbc":{"source":"iana"},"audio/vnd.presonus.multitrack":{"source":"iana"},"audio/vnd.qcelp":{"source":"iana"},"audio/vnd.rhetorex.32kadpcm":{"source":"iana"},"audio/vnd.rip":{"source":"iana","extensions":["rip"]},"audio/vnd.rn-realaudio":{"compressible":false},"audio/vnd.sealedmedia.softseal.mpeg":{"source":"iana"},"audio/vnd.vmx.cvsd":{"source":"iana"},"audio/vnd.wave":{"compressible":false},"audio/vorbis":{"source":"iana","compressible":false},"audio/vorbis-config":{"source":"iana"},"audio/wav":{"compressible":false,"extensions":["wav"]},"audio/wave":{"compressible":false,"extensions":["wav"]},"audio/webm":{"source":"apache","compressible":false,"extensions":["weba"]},"audio/x-aac":{"source":"apache","compressible":false,"extensions":["aac"]},"audio/x-aiff":{"source":"apache","extensions":["aif","aiff","aifc"]},"audio/x-caf":{"source":"apache","compressible":false,"extensions":["caf"]},"audio/x-flac":{"source":"apache","extensions":["flac"]},"audio/x-m4a":{"source":"nginx","extensions":["m4a"]},"audio/x-matroska":{"source":"apache","extensions":["mka"]},"audio/x-mpegurl":{"source":"apache","extensions":["m3u"]},"audio/x-ms-wax":{"source":"apache","extensions":["wax"]},"audio/x-ms-wma":{"source":"apache","extensions":["wma"]},"audio/x-pn-realaudio":{"source":"apache","extensions":["ram","ra"]},"audio/x-pn-realaudio-plugin":{"source":"apache","extensions":["rmp"]},"audio/x-realaudio":{"source":"nginx","extensions":["ra"]},"audio/x-tta":{"source":"apache"},"audio/x-wav":{"source":"apache","extensions":["wav"]},"audio/xm":{"source":"apache","extensions":["xm"]},"chemical/x-cdx":{"source":"apache","extensions":["cdx"]},"chemical/x-cif":{"source":"apache","extensions":["cif"]},"chemical/x-cmdf":{"source":"apache","extensions":["cmdf"]},"chemical/x-cml":{"source":"apache","extensions":["cml"]},"chemical/x-csml":{"source":"apache","extensions":["csml"]},"chemical/x-pdb":{"source":"apache"},"chemical/x-xyz":{"source":"apache","extensions":["xyz"]},"font/collection":{"source":"iana","extensions":["ttc"]},"font/otf":{"source":"iana","compressible":true,"extensions":["otf"]},"font/sfnt":{"source":"iana"},"font/ttf":{"source":"iana","compressible":true,"extensions":["ttf"]},"font/woff":{"source":"iana","extensions":["woff"]},"font/woff2":{"source":"iana","extensions":["woff2"]},"image/aces":{"source":"iana","extensions":["exr"]},"image/apng":{"compressible":false,"extensions":["apng"]},"image/avci":{"source":"iana","extensions":["avci"]},"image/avcs":{"source":"iana","extensions":["avcs"]},"image/avif":{"source":"iana","compressible":false,"extensions":["avif"]},"image/bmp":{"source":"iana","compressible":true,"extensions":["bmp"]},"image/cgm":{"source":"iana","extensions":["cgm"]},"image/dicom-rle":{"source":"iana","extensions":["drle"]},"image/emf":{"source":"iana","extensions":["emf"]},"image/fits":{"source":"iana","extensions":["fits"]},"image/g3fax":{"source":"iana","extensions":["g3"]},"image/gif":{"source":"iana","compressible":false,"extensions":["gif"]},"image/heic":{"source":"iana","extensions":["heic"]},"image/heic-sequence":{"source":"iana","extensions":["heics"]},"image/heif":{"source":"iana","extensions":["heif"]},"image/heif-sequence":{"source":"iana","extensions":["heifs"]},"image/hej2k":{"source":"iana","extensions":["hej2"]},"image/hsj2":{"source":"iana","extensions":["hsj2"]},"image/ief":{"source":"iana","extensions":["ief"]},"image/jls":{"source":"iana","extensions":["jls"]},"image/jp2":{"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},"image/jpeg":{"source":"iana","compressible":false,"extensions":["jpeg","jpg","jpe"]},"image/jph":{"source":"iana","extensions":["jph"]},"image/jphc":{"source":"iana","extensions":["jhc"]},"image/jpm":{"source":"iana","compressible":false,"extensions":["jpm"]},"image/jpx":{"source":"iana","compressible":false,"extensions":["jpx","jpf"]},"image/jxr":{"source":"iana","extensions":["jxr"]},"image/jxra":{"source":"iana","extensions":["jxra"]},"image/jxrs":{"source":"iana","extensions":["jxrs"]},"image/jxs":{"source":"iana","extensions":["jxs"]},"image/jxsc":{"source":"iana","extensions":["jxsc"]},"image/jxsi":{"source":"iana","extensions":["jxsi"]},"image/jxss":{"source":"iana","extensions":["jxss"]},"image/ktx":{"source":"iana","extensions":["ktx"]},"image/ktx2":{"source":"iana","extensions":["ktx2"]},"image/naplps":{"source":"iana"},"image/pjpeg":{"compressible":false},"image/png":{"source":"iana","compressible":false,"extensions":["png"]},"image/prs.btif":{"source":"iana","extensions":["btif"]},"image/prs.pti":{"source":"iana","extensions":["pti"]},"image/pwg-raster":{"source":"iana"},"image/sgi":{"source":"apache","extensions":["sgi"]},"image/svg+xml":{"source":"iana","compressible":true,"extensions":["svg","svgz"]},"image/t38":{"source":"iana","extensions":["t38"]},"image/tiff":{"source":"iana","compressible":false,"extensions":["tif","tiff"]},"image/tiff-fx":{"source":"iana","extensions":["tfx"]},"image/vnd.adobe.photoshop":{"source":"iana","compressible":true,"extensions":["psd"]},"image/vnd.airzip.accelerator.azv":{"source":"iana","extensions":["azv"]},"image/vnd.cns.inf2":{"source":"iana"},"image/vnd.dece.graphic":{"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{"source":"iana","extensions":["djvu","djv"]},"image/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"image/vnd.dwg":{"source":"iana","extensions":["dwg"]},"image/vnd.dxf":{"source":"iana","extensions":["dxf"]},"image/vnd.fastbidsheet":{"source":"iana","extensions":["fbs"]},"image/vnd.fpx":{"source":"iana","extensions":["fpx"]},"image/vnd.fst":{"source":"iana","extensions":["fst"]},"image/vnd.fujixerox.edmics-mmr":{"source":"iana","extensions":["mmr"]},"image/vnd.fujixerox.edmics-rlc":{"source":"iana","extensions":["rlc"]},"image/vnd.globalgraphics.pgb":{"source":"iana"},"image/vnd.microsoft.icon":{"source":"iana","compressible":true,"extensions":["ico"]},"image/vnd.mix":{"source":"iana"},"image/vnd.mozilla.apng":{"source":"iana"},"image/vnd.ms-dds":{"compressible":true,"extensions":["dds"]},"image/vnd.ms-modi":{"source":"iana","extensions":["mdi"]},"image/vnd.ms-photo":{"source":"apache","extensions":["wdp"]},"image/vnd.net-fpx":{"source":"iana","extensions":["npx"]},"image/vnd.pco.b16":{"source":"iana","extensions":["b16"]},"image/vnd.radiance":{"source":"iana"},"image/vnd.sealed.png":{"source":"iana"},"image/vnd.sealedmedia.softseal.gif":{"source":"iana"},"image/vnd.sealedmedia.softseal.jpg":{"source":"iana"},"image/vnd.svf":{"source":"iana"},"image/vnd.tencent.tap":{"source":"iana","extensions":["tap"]},"image/vnd.valve.source.texture":{"source":"iana","extensions":["vtf"]},"image/vnd.wap.wbmp":{"source":"iana","extensions":["wbmp"]},"image/vnd.xiff":{"source":"iana","extensions":["xif"]},"image/vnd.zbrush.pcx":{"source":"iana","extensions":["pcx"]},"image/webp":{"source":"apache","extensions":["webp"]},"image/wmf":{"source":"iana","extensions":["wmf"]},"image/x-3ds":{"source":"apache","extensions":["3ds"]},"image/x-cmu-raster":{"source":"apache","extensions":["ras"]},"image/x-cmx":{"source":"apache","extensions":["cmx"]},"image/x-freehand":{"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{"source":"apache","compressible":true,"extensions":["ico"]},"image/x-jng":{"source":"nginx","extensions":["jng"]},"image/x-mrsid-image":{"source":"apache","extensions":["sid"]},"image/x-ms-bmp":{"source":"nginx","compressible":true,"extensions":["bmp"]},"image/x-pcx":{"source":"apache","extensions":["pcx"]},"image/x-pict":{"source":"apache","extensions":["pic","pct"]},"image/x-portable-anymap":{"source":"apache","extensions":["pnm"]},"image/x-portable-bitmap":{"source":"apache","extensions":["pbm"]},"image/x-portable-graymap":{"source":"apache","extensions":["pgm"]},"image/x-portable-pixmap":{"source":"apache","extensions":["ppm"]},"image/x-rgb":{"source":"apache","extensions":["rgb"]},"image/x-tga":{"source":"apache","extensions":["tga"]},"image/x-xbitmap":{"source":"apache","extensions":["xbm"]},"image/x-xcf":{"compressible":false},"image/x-xpixmap":{"source":"apache","extensions":["xpm"]},"image/x-xwindowdump":{"source":"apache","extensions":["xwd"]},"message/cpim":{"source":"iana"},"message/delivery-status":{"source":"iana"},"message/disposition-notification":{"source":"iana","extensions":["disposition-notification"]},"message/external-body":{"source":"iana"},"message/feedback-report":{"source":"iana"},"message/global":{"source":"iana","extensions":["u8msg"]},"message/global-delivery-status":{"source":"iana","extensions":["u8dsn"]},"message/global-disposition-notification":{"source":"iana","extensions":["u8mdn"]},"message/global-headers":{"source":"iana","extensions":["u8hdr"]},"message/http":{"source":"iana","compressible":false},"message/imdn+xml":{"source":"iana","compressible":true},"message/news":{"source":"iana"},"message/partial":{"source":"iana","compressible":false},"message/rfc822":{"source":"iana","compressible":true,"extensions":["eml","mime"]},"message/s-http":{"source":"iana"},"message/sip":{"source":"iana"},"message/sipfrag":{"source":"iana"},"message/tracking-status":{"source":"iana"},"message/vnd.si.simp":{"source":"iana"},"message/vnd.wfa.wsc":{"source":"iana","extensions":["wsc"]},"model/3mf":{"source":"iana","extensions":["3mf"]},"model/e57":{"source":"iana"},"model/gltf+json":{"source":"iana","compressible":true,"extensions":["gltf"]},"model/gltf-binary":{"source":"iana","compressible":true,"extensions":["glb"]},"model/iges":{"source":"iana","compressible":false,"extensions":["igs","iges"]},"model/mesh":{"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},"model/mtl":{"source":"iana","extensions":["mtl"]},"model/obj":{"source":"iana","extensions":["obj"]},"model/step":{"source":"iana"},"model/step+xml":{"source":"iana","compressible":true,"extensions":["stpx"]},"model/step+zip":{"source":"iana","compressible":false,"extensions":["stpz"]},"model/step-xml+zip":{"source":"iana","compressible":false,"extensions":["stpxz"]},"model/stl":{"source":"iana","extensions":["stl"]},"model/vnd.collada+xml":{"source":"iana","compressible":true,"extensions":["dae"]},"model/vnd.dwf":{"source":"iana","extensions":["dwf"]},"model/vnd.flatland.3dml":{"source":"iana"},"model/vnd.gdl":{"source":"iana","extensions":["gdl"]},"model/vnd.gs-gdl":{"source":"apache"},"model/vnd.gs.gdl":{"source":"iana"},"model/vnd.gtw":{"source":"iana","extensions":["gtw"]},"model/vnd.moml+xml":{"source":"iana","compressible":true},"model/vnd.mts":{"source":"iana","extensions":["mts"]},"model/vnd.opengex":{"source":"iana","extensions":["ogex"]},"model/vnd.parasolid.transmit.binary":{"source":"iana","extensions":["x_b"]},"model/vnd.parasolid.transmit.text":{"source":"iana","extensions":["x_t"]},"model/vnd.pytha.pyox":{"source":"iana"},"model/vnd.rosette.annotated-data-model":{"source":"iana"},"model/vnd.sap.vds":{"source":"iana","extensions":["vds"]},"model/vnd.usdz+zip":{"source":"iana","compressible":false,"extensions":["usdz"]},"model/vnd.valve.source.compiled-map":{"source":"iana","extensions":["bsp"]},"model/vnd.vtu":{"source":"iana","extensions":["vtu"]},"model/vrml":{"source":"iana","compressible":false,"extensions":["wrl","vrml"]},"model/x3d+binary":{"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},"model/x3d+fastinfoset":{"source":"iana","extensions":["x3db"]},"model/x3d+vrml":{"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},"model/x3d+xml":{"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},"model/x3d-vrml":{"source":"iana","extensions":["x3dv"]},"multipart/alternative":{"source":"iana","compressible":false},"multipart/appledouble":{"source":"iana"},"multipart/byteranges":{"source":"iana"},"multipart/digest":{"source":"iana"},"multipart/encrypted":{"source":"iana","compressible":false},"multipart/form-data":{"source":"iana","compressible":false},"multipart/header-set":{"source":"iana"},"multipart/mixed":{"source":"iana"},"multipart/multilingual":{"source":"iana"},"multipart/parallel":{"source":"iana"},"multipart/related":{"source":"iana","compressible":false},"multipart/report":{"source":"iana"},"multipart/signed":{"source":"iana","compressible":false},"multipart/vnd.bint.med-plus":{"source":"iana"},"multipart/voice-message":{"source":"iana"},"multipart/x-mixed-replace":{"source":"iana"},"text/1d-interleaved-parityfec":{"source":"iana"},"text/cache-manifest":{"source":"iana","compressible":true,"extensions":["appcache","manifest"]},"text/calendar":{"source":"iana","extensions":["ics","ifb"]},"text/calender":{"compressible":true},"text/cmd":{"compressible":true},"text/coffeescript":{"extensions":["coffee","litcoffee"]},"text/cql":{"source":"iana"},"text/cql-expression":{"source":"iana"},"text/cql-identifier":{"source":"iana"},"text/css":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},"text/csv":{"source":"iana","compressible":true,"extensions":["csv"]},"text/csv-schema":{"source":"iana"},"text/directory":{"source":"iana"},"text/dns":{"source":"iana"},"text/ecmascript":{"source":"iana"},"text/encaprtp":{"source":"iana"},"text/enriched":{"source":"iana"},"text/fhirpath":{"source":"iana"},"text/flexfec":{"source":"iana"},"text/fwdred":{"source":"iana"},"text/gff3":{"source":"iana"},"text/grammar-ref-list":{"source":"iana"},"text/html":{"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},"text/jade":{"extensions":["jade"]},"text/javascript":{"source":"iana","compressible":true},"text/jcr-cnd":{"source":"iana"},"text/jsx":{"compressible":true,"extensions":["jsx"]},"text/less":{"compressible":true,"extensions":["less"]},"text/markdown":{"source":"iana","compressible":true,"extensions":["markdown","md"]},"text/mathml":{"source":"nginx","extensions":["mml"]},"text/mdx":{"compressible":true,"extensions":["mdx"]},"text/mizar":{"source":"iana"},"text/n3":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},"text/parameters":{"source":"iana","charset":"UTF-8"},"text/parityfec":{"source":"iana"},"text/plain":{"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{"source":"iana","charset":"UTF-8"},"text/prs.fallenstein.rst":{"source":"iana"},"text/prs.lines.tag":{"source":"iana","extensions":["dsc"]},"text/prs.prop.logic":{"source":"iana"},"text/raptorfec":{"source":"iana"},"text/red":{"source":"iana"},"text/rfc822-headers":{"source":"iana"},"text/richtext":{"source":"iana","compressible":true,"extensions":["rtx"]},"text/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"text/rtp-enc-aescm128":{"source":"iana"},"text/rtploopback":{"source":"iana"},"text/rtx":{"source":"iana"},"text/sgml":{"source":"iana","extensions":["sgml","sgm"]},"text/shaclc":{"source":"iana"},"text/shex":{"source":"iana","extensions":["shex"]},"text/slim":{"extensions":["slim","slm"]},"text/spdx":{"source":"iana","extensions":["spdx"]},"text/strings":{"source":"iana"},"text/stylus":{"extensions":["stylus","styl"]},"text/t140":{"source":"iana"},"text/tab-separated-values":{"source":"iana","compressible":true,"extensions":["tsv"]},"text/troff":{"source":"iana","extensions":["t","tr","roff","man","me","ms"]},"text/turtle":{"source":"iana","charset":"UTF-8","extensions":["ttl"]},"text/ulpfec":{"source":"iana"},"text/uri-list":{"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},"text/vcard":{"source":"iana","compressible":true,"extensions":["vcard"]},"text/vnd.a":{"source":"iana"},"text/vnd.abc":{"source":"iana"},"text/vnd.ascii-art":{"source":"iana"},"text/vnd.curl":{"source":"iana","extensions":["curl"]},"text/vnd.curl.dcurl":{"source":"apache","extensions":["dcurl"]},"text/vnd.curl.mcurl":{"source":"apache","extensions":["mcurl"]},"text/vnd.curl.scurl":{"source":"apache","extensions":["scurl"]},"text/vnd.debian.copyright":{"source":"iana","charset":"UTF-8"},"text/vnd.dmclientscript":{"source":"iana"},"text/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"text/vnd.esmertec.theme-descriptor":{"source":"iana","charset":"UTF-8"},"text/vnd.familysearch.gedcom":{"source":"iana","extensions":["ged"]},"text/vnd.ficlab.flt":{"source":"iana"},"text/vnd.fly":{"source":"iana","extensions":["fly"]},"text/vnd.fmi.flexstor":{"source":"iana","extensions":["flx"]},"text/vnd.gml":{"source":"iana"},"text/vnd.graphviz":{"source":"iana","extensions":["gv"]},"text/vnd.hans":{"source":"iana"},"text/vnd.hgl":{"source":"iana"},"text/vnd.in3d.3dml":{"source":"iana","extensions":["3dml"]},"text/vnd.in3d.spot":{"source":"iana","extensions":["spot"]},"text/vnd.iptc.newsml":{"source":"iana"},"text/vnd.iptc.nitf":{"source":"iana"},"text/vnd.latex-z":{"source":"iana"},"text/vnd.motorola.reflex":{"source":"iana"},"text/vnd.ms-mediapackage":{"source":"iana"},"text/vnd.net2phone.commcenter.command":{"source":"iana"},"text/vnd.radisys.msml-basic-layout":{"source":"iana"},"text/vnd.senx.warpscript":{"source":"iana"},"text/vnd.si.uricatalogue":{"source":"iana"},"text/vnd.sosi":{"source":"iana"},"text/vnd.sun.j2me.app-descriptor":{"source":"iana","charset":"UTF-8","extensions":["jad"]},"text/vnd.trolltech.linguist":{"source":"iana","charset":"UTF-8"},"text/vnd.wap.si":{"source":"iana"},"text/vnd.wap.sl":{"source":"iana"},"text/vnd.wap.wml":{"source":"iana","extensions":["wml"]},"text/vnd.wap.wmlscript":{"source":"iana","extensions":["wmls"]},"text/vtt":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},"text/x-asm":{"source":"apache","extensions":["s","asm"]},"text/x-c":{"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{"source":"nginx","extensions":["htc"]},"text/x-fortran":{"source":"apache","extensions":["f","for","f77","f90"]},"text/x-gwt-rpc":{"compressible":true},"text/x-handlebars-template":{"extensions":["hbs"]},"text/x-java-source":{"source":"apache","extensions":["java"]},"text/x-jquery-tmpl":{"compressible":true},"text/x-lua":{"extensions":["lua"]},"text/x-markdown":{"compressible":true,"extensions":["mkd"]},"text/x-nfo":{"source":"apache","extensions":["nfo"]},"text/x-opml":{"source":"apache","extensions":["opml"]},"text/x-org":{"compressible":true,"extensions":["org"]},"text/x-pascal":{"source":"apache","extensions":["p","pas"]},"text/x-processing":{"compressible":true,"extensions":["pde"]},"text/x-sass":{"extensions":["sass"]},"text/x-scss":{"extensions":["scss"]},"text/x-setext":{"source":"apache","extensions":["etx"]},"text/x-sfv":{"source":"apache","extensions":["sfv"]},"text/x-suse-ymp":{"compressible":true,"extensions":["ymp"]},"text/x-uuencode":{"source":"apache","extensions":["uu"]},"text/x-vcalendar":{"source":"apache","extensions":["vcs"]},"text/x-vcard":{"source":"apache","extensions":["vcf"]},"text/xml":{"source":"iana","compressible":true,"extensions":["xml"]},"text/xml-external-parsed-entity":{"source":"iana"},"text/yaml":{"compressible":true,"extensions":["yaml","yml"]},"video/1d-interleaved-parityfec":{"source":"iana"},"video/3gpp":{"source":"iana","extensions":["3gp","3gpp"]},"video/3gpp-tt":{"source":"iana"},"video/3gpp2":{"source":"iana","extensions":["3g2"]},"video/av1":{"source":"iana"},"video/bmpeg":{"source":"iana"},"video/bt656":{"source":"iana"},"video/celb":{"source":"iana"},"video/dv":{"source":"iana"},"video/encaprtp":{"source":"iana"},"video/ffv1":{"source":"iana"},"video/flexfec":{"source":"iana"},"video/h261":{"source":"iana","extensions":["h261"]},"video/h263":{"source":"iana","extensions":["h263"]},"video/h263-1998":{"source":"iana"},"video/h263-2000":{"source":"iana"},"video/h264":{"source":"iana","extensions":["h264"]},"video/h264-rcdo":{"source":"iana"},"video/h264-svc":{"source":"iana"},"video/h265":{"source":"iana"},"video/iso.segment":{"source":"iana","extensions":["m4s"]},"video/jpeg":{"source":"iana","extensions":["jpgv"]},"video/jpeg2000":{"source":"iana"},"video/jpm":{"source":"apache","extensions":["jpm","jpgm"]},"video/jxsv":{"source":"iana"},"video/mj2":{"source":"iana","extensions":["mj2","mjp2"]},"video/mp1s":{"source":"iana"},"video/mp2p":{"source":"iana"},"video/mp2t":{"source":"iana","extensions":["ts"]},"video/mp4":{"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},"video/mp4v-es":{"source":"iana"},"video/mpeg":{"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{"source":"iana"},"video/mpv":{"source":"iana"},"video/nv":{"source":"iana"},"video/ogg":{"source":"iana","compressible":false,"extensions":["ogv"]},"video/parityfec":{"source":"iana"},"video/pointer":{"source":"iana"},"video/quicktime":{"source":"iana","compressible":false,"extensions":["qt","mov"]},"video/raptorfec":{"source":"iana"},"video/raw":{"source":"iana"},"video/rtp-enc-aescm128":{"source":"iana"},"video/rtploopback":{"source":"iana"},"video/rtx":{"source":"iana"},"video/scip":{"source":"iana"},"video/smpte291":{"source":"iana"},"video/smpte292m":{"source":"iana"},"video/ulpfec":{"source":"iana"},"video/vc1":{"source":"iana"},"video/vc2":{"source":"iana"},"video/vnd.cctv":{"source":"iana"},"video/vnd.dece.hd":{"source":"iana","extensions":["uvh","uvvh"]},"video/vnd.dece.mobile":{"source":"iana","extensions":["uvm","uvvm"]},"video/vnd.dece.mp4":{"source":"iana"},"video/vnd.dece.pd":{"source":"iana","extensions":["uvp","uvvp"]},"video/vnd.dece.sd":{"source":"iana","extensions":["uvs","uvvs"]},"video/vnd.dece.video":{"source":"iana","extensions":["uvv","uvvv"]},"video/vnd.directv.mpeg":{"source":"iana"},"video/vnd.directv.mpeg-tts":{"source":"iana"},"video/vnd.dlna.mpeg-tts":{"source":"iana"},"video/vnd.dvb.file":{"source":"iana","extensions":["dvb"]},"video/vnd.fvt":{"source":"iana","extensions":["fvt"]},"video/vnd.hns.video":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.ttsavc":{"source":"iana"},"video/vnd.iptvforum.ttsmpeg2":{"source":"iana"},"video/vnd.motorola.video":{"source":"iana"},"video/vnd.motorola.videop":{"source":"iana"},"video/vnd.mpegurl":{"source":"iana","extensions":["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{"source":"iana","extensions":["pyv"]},"video/vnd.nokia.interleaved-multimedia":{"source":"iana"},"video/vnd.nokia.mp4vr":{"source":"iana"},"video/vnd.nokia.videovoip":{"source":"iana"},"video/vnd.objectvideo":{"source":"iana"},"video/vnd.radgamettools.bink":{"source":"iana"},"video/vnd.radgamettools.smacker":{"source":"iana"},"video/vnd.sealed.mpeg1":{"source":"iana"},"video/vnd.sealed.mpeg4":{"source":"iana"},"video/vnd.sealed.swf":{"source":"iana"},"video/vnd.sealedmedia.softseal.mov":{"source":"iana"},"video/vnd.uvvu.mp4":{"source":"iana","extensions":["uvu","uvvu"]},"video/vnd.vivo":{"source":"iana","extensions":["viv"]},"video/vnd.youtube.yt":{"source":"iana"},"video/vp8":{"source":"iana"},"video/vp9":{"source":"iana"},"video/webm":{"source":"apache","compressible":false,"extensions":["webm"]},"video/x-f4v":{"source":"apache","extensions":["f4v"]},"video/x-fli":{"source":"apache","extensions":["fli"]},"video/x-flv":{"source":"apache","compressible":false,"extensions":["flv"]},"video/x-m4v":{"source":"apache","extensions":["m4v"]},"video/x-matroska":{"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},"video/x-mng":{"source":"apache","extensions":["mng"]},"video/x-ms-asf":{"source":"apache","extensions":["asf","asx"]},"video/x-ms-vob":{"source":"apache","extensions":["vob"]},"video/x-ms-wm":{"source":"apache","extensions":["wm"]},"video/x-ms-wmv":{"source":"apache","compressible":false,"extensions":["wmv"]},"video/x-ms-wmx":{"source":"apache","extensions":["wmx"]},"video/x-ms-wvx":{"source":"apache","extensions":["wvx"]},"video/x-msvideo":{"source":"apache","extensions":["avi"]},"video/x-sgi-movie":{"source":"apache","extensions":["movie"]},"video/x-smv":{"source":"apache","extensions":["smv"]},"x-conference/x-cooltalk":{"source":"apache","extensions":["ice"]},"x-shader/x-fragment":{"compressible":true},"x-shader/x-vertex":{"compressible":true}}');
/***/ }),
/***/ 82954:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"name":"thread-stream","version":"3.0.2","description":"A streaming way to send data to a Node.js Worker Thread","main":"index.js","types":"index.d.ts","dependencies":{"real-require":"^0.2.0"},"devDependencies":{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5","desm":"^1.3.0","fastbench":"^1.0.1","husky":"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1","standard":"^17.0.0","tap":"^16.2.0","ts-node":"^10.8.0","typescript":"^5.3.2","why-is-node-running":"^2.2.2"},"scripts":{"build":"tsc --noEmit","test":"standard && npm run build && npm run transpile && tap \\"test/**/*.test.*js\\" && tap --ts test/*.test.*ts","test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\"test/**/*.test.*js\\"","test:ci:ts":"tap --ts --no-check-coverage --coverage-report=lcovonly \\"test/**/*.test.*ts\\"","test:yarn":"npm run transpile && tap \\"test/**/*.test.js\\" --no-check-coverage","transpile":"sh ./test/ts/transpile.sh","prepare":"husky install"},"standard":{"ignore":["test/ts/**/*"]},"repository":{"type":"git","url":"git+https://github.com/mcollina/thread-stream.git"},"keywords":["worker","thread","threads","stream"],"author":"Matteo Collina <hello@matteocollina.com>","license":"MIT","bugs":{"url":"https://github.com/mcollina/thread-stream/issues"},"homepage":"https://github.com/mcollina/thread-stream#readme"}');
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/node module decorator */
/******/ (() => {
/******/ __nccwpck_require__.nmd = (module) => {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true }));
/**
* The entrypoint for the action.
*/
const main_1 = __nccwpck_require__(70399);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(0, main_1.run)();
})();
module.exports = __webpack_exports__;
/******/ })()
;
//# sourceMappingURL=index.js.map