import './sourcemap-register.cjs';import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; /******/ var __webpack_modules__ = ({ /***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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__(2037)); 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 /***/ }), /***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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__(7351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); const os = __importStar(__nccwpck_require__(2037)); const path = __importStar(__nccwpck_require__(1017)); const oidc_utils_1 = __nccwpck_require__(8041); /** * 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__(1327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(1327); 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__) { // 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__(7147)); const os = __importStar(__nccwpck_require__(2037)); const uuid_1 = __nccwpck_require__(5840); 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 /***/ }), /***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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__(6255); const auth_1 = __nccwpck_require__(5526); const core_1 = __nccwpck_require__(2186); 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.result.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__) { 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__(1017)); /** * 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 /***/ }), /***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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__(2037); const fs_1 = __nccwpck_require__(7147); 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}`; } /** * 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 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 (
) 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 (
) 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) => { // 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 /***/ }), /***/ 5526: /***/ (function(__unused_webpack_module, exports) { 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 /***/ }), /***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /* eslint-disable @typescript-eslint/no-explicit-any */ 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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(3685)); const https = __importStar(__nccwpck_require__(5687)); const pm = __importStar(__nccwpck_require__(9835)); const tunnel = __importStar(__nccwpck_require__(4294)); 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 || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.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()); }); })); }); } } 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); } _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; } _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 /***/ }), /***/ 9835: /***/ ((__unused_webpack_module, exports) => { 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) { return new URL(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 /***/ }), /***/ 6494: /***/ ((__unused_webpack_module, exports) => { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); function applyDefaults(options) { if (!options) { options = {}; } return { delay: (options.delay === undefined) ? 200 : options.delay, initialDelay: (options.initialDelay === undefined) ? 0 : options.initialDelay, minDelay: (options.minDelay === undefined) ? 0 : options.minDelay, maxDelay: (options.maxDelay === undefined) ? 0 : options.maxDelay, factor: (options.factor === undefined) ? 0 : options.factor, maxAttempts: (options.maxAttempts === undefined) ? 3 : options.maxAttempts, timeout: (options.timeout === undefined) ? 0 : options.timeout, jitter: (options.jitter === true), handleError: (options.handleError === undefined) ? null : options.handleError, handleTimeout: (options.handleTimeout === undefined) ? null : options.handleTimeout, beforeAttempt: (options.beforeAttempt === undefined) ? null : options.beforeAttempt, calculateDelay: (options.calculateDelay === undefined) ? null : options.calculateDelay }; } async function sleep(delay) { return new Promise((resolve, reject) => { setTimeout(resolve, delay); }); } __webpack_unused_export__ = sleep; function defaultCalculateDelay(context, options) { let delay = options.delay; if (delay === 0) { // no delay between attempts return 0; } if (options.factor) { delay *= Math.pow(options.factor, context.attemptNum - 1); if (options.maxDelay !== 0) { delay = Math.min(delay, options.maxDelay); } } if (options.jitter) { // Jitter will result in a random value between `minDelay` and // calculated delay for a given attempt. // See https://www.awsarchitectureblog.com/2015/03/backoff.html // We're using the "full jitter" strategy. const min = Math.ceil(options.minDelay); const max = Math.floor(delay); delay = Math.floor(Math.random() * (max - min + 1)) + min; } return Math.round(delay); } __webpack_unused_export__ = defaultCalculateDelay; async function retry(attemptFunc, attemptOptions) { const options = applyDefaults(attemptOptions); for (const prop of [ 'delay', 'initialDelay', 'minDelay', 'maxDelay', 'maxAttempts', 'timeout' ]) { const value = options[prop]; if (!Number.isInteger(value) || (value < 0)) { throw new Error(`Value for ${prop} must be an integer greater than or equal to 0`); } } if ((options.factor.constructor !== Number) || (options.factor < 0)) { throw new Error(`Value for factor must be a number greater than or equal to 0`); } if (options.delay < options.minDelay) { throw new Error(`delay cannot be less than minDelay (delay: ${options.delay}, minDelay: ${options.minDelay}`); } const context = { attemptNum: 0, attemptsRemaining: options.maxAttempts ? options.maxAttempts : -1, aborted: false, abort() { context.aborted = true; } }; const calculateDelay = options.calculateDelay || defaultCalculateDelay; async function makeAttempt() { if (options.beforeAttempt) { options.beforeAttempt(context, options); } if (context.aborted) { const err = new Error(`Attempt aborted`); err.code = 'ATTEMPT_ABORTED'; throw err; } const onError = async (err) => { if (options.handleError) { await options.handleError(err, context, options); } if (context.aborted || (context.attemptsRemaining === 0)) { throw err; } // We are about to try again so increment attempt number context.attemptNum++; const delay = calculateDelay(context, options); if (delay) { await sleep(delay); } return makeAttempt(); }; if (context.attemptsRemaining > 0) { context.attemptsRemaining--; } if (options.timeout) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { if (options.handleTimeout) { // If calling handleTimeout throws an error that is not wrapped in a promise // we want to catch the error and reject. try { resolve(options.handleTimeout(context, options)); } catch (e) { reject(e); } } else { const err = new Error(`Retry timeout (attemptNum: ${context.attemptNum}, timeout: ${options.timeout})`); err.code = 'ATTEMPT_TIMEOUT'; reject(err); } }, options.timeout); attemptFunc(context, options).then((result) => { clearTimeout(timer); resolve(result); }).catch((err) => { clearTimeout(timer); // Calling resolve with a Promise that rejects here will result // in an unhandled rejection. Calling `reject` with errors // does not result in an unhandled rejection onError(err).then(resolve).catch(reject); }); }); } else { // No timeout provided so wait indefinitely for the returned promise // to be resolved. return attemptFunc(context, options).catch(onError); } } const initialDelay = options.calculateDelay ? options.calculateDelay(context, options) : options.initialDelay; if (initialDelay) { await sleep(initialDelay); } return makeAttempt(); } exports.XD = retry; /***/ }), /***/ 7760: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! node-domexception. MIT License. Jimmy Wärting */ if (!globalThis.DOMException) { try { const { MessageChannel } = __nccwpck_require__(1267), port = new MessageChannel().port1, ab = new ArrayBuffer() port.postMessage(ab, [ab, ab]) } catch (err) { err.constructor.name === 'DOMException' && ( globalThis.DOMException = err.constructor ) } } module.exports = globalThis.DOMException /***/ }), /***/ 4294: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(4219); /***/ }), /***/ 4219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var net = __nccwpck_require__(1808); var tls = __nccwpck_require__(4404); var http = __nccwpck_require__(3685); var https = __nccwpck_require__(5687); var events = __nccwpck_require__(2361); var assert = __nccwpck_require__(9491); var util = __nccwpck_require__(3837); 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 /***/ }), /***/ 5840: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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__(8628)); var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); var _nil = _interopRequireDefault(__nccwpck_require__(5332)); var _version = _interopRequireDefault(__nccwpck_require__(1595)); var _validate = _interopRequireDefault(__nccwpck_require__(6900)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); var _parse = _interopRequireDefault(__nccwpck_require__(2746)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ 4569: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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; /***/ }), /***/ 5332: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _default = '00000000-0000-0000-0000-000000000000'; exports["default"] = _default; /***/ }), /***/ 2746: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 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; /***/ }), /***/ 814: /***/ ((__unused_webpack_module, exports) => { 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; /***/ }), /***/ 807: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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); } /***/ }), /***/ 5274: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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; /***/ }), /***/ 8950: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 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; /***/ }), /***/ 8628: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(807)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 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; /***/ }), /***/ 6409: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(5998)); 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; /***/ }), /***/ 5998: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = _default; exports.URL = exports.DNS = void 0; var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); var _parse = _interopRequireDefault(__nccwpck_require__(2746)); 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; } /***/ }), /***/ 5122: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(807)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 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; /***/ }), /***/ 9120: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(5998)); var _sha = _interopRequireDefault(__nccwpck_require__(5274)); 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; /***/ }), /***/ 6900: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _regex = _interopRequireDefault(__nccwpck_require__(814)); 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; /***/ }), /***/ 1595: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 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; /***/ }), /***/ 1452: /***/ (function(__unused_webpack_module, exports) { /** * web-streams-polyfill v3.2.1 */ (function (global, factory) { true ? factory(exports) : 0; }(this, (function (exports) { 'use strict'; /// const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol : description => `Symbol(${description})`; /// function noop() { return undefined; } function getGlobals() { if (typeof self !== 'undefined') { return self; } else if (typeof window !== 'undefined') { return window; } else if (typeof global !== 'undefined') { return global; } return undefined; } const globals = getGlobals(); function typeIsObject(x) { return (typeof x === 'object' && x !== null) || typeof x === 'function'; } const rethrowAssertionErrorRejection = noop; const originalPromise = Promise; const originalPromiseThen = Promise.prototype.then; const originalPromiseResolve = Promise.resolve.bind(originalPromise); const originalPromiseReject = Promise.reject.bind(originalPromise); function newPromise(executor) { return new originalPromise(executor); } function promiseResolvedWith(value) { return originalPromiseResolve(value); } function promiseRejectedWith(reason) { return originalPromiseReject(reason); } function PerformPromiseThen(promise, onFulfilled, onRejected) { // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an // approximation. return originalPromiseThen.call(promise, onFulfilled, onRejected); } function uponPromise(promise, onFulfilled, onRejected) { PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); } function uponFulfillment(promise, onFulfilled) { uponPromise(promise, onFulfilled); } function uponRejection(promise, onRejected) { uponPromise(promise, undefined, onRejected); } function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); } function setPromiseIsHandledToTrue(promise) { PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); } const queueMicrotask = (() => { const globalQueueMicrotask = globals && globals.queueMicrotask; if (typeof globalQueueMicrotask === 'function') { return globalQueueMicrotask; } const resolvedPromise = promiseResolvedWith(undefined); return (fn) => PerformPromiseThen(resolvedPromise, fn); })(); function reflectCall(F, V, args) { if (typeof F !== 'function') { throw new TypeError('Argument is not a function'); } return Function.prototype.apply.call(F, V, args); } function promiseCall(F, V, args) { try { return promiseResolvedWith(reflectCall(F, V, args)); } catch (value) { return promiseRejectedWith(value); } } // Original from Chromium // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js const QUEUE_MAX_ARRAY_SIZE = 16384; /** * Simple queue structure. * * Avoids scalability issues with using a packed array directly by using * multiple arrays in a linked list and keeping the array size bounded. */ class SimpleQueue { constructor() { this._cursor = 0; this._size = 0; // _front and _back are always defined. this._front = { _elements: [], _next: undefined }; this._back = this._front; // The cursor is used to avoid calling Array.shift(). // It contains the index of the front element of the array inside the // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). this._cursor = 0; // When there is only one node, size === elements.length - cursor. this._size = 0; } get length() { return this._size; } // For exception safety, this method is structured in order: // 1. Read state // 2. Calculate required state mutations // 3. Perform state mutations push(element) { const oldBack = this._back; let newBack = oldBack; if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { newBack = { _elements: [], _next: undefined }; } // push() is the mutation most likely to throw an exception, so it // goes first. oldBack._elements.push(element); if (newBack !== oldBack) { this._back = newBack; oldBack._next = newBack; } ++this._size; } // Like push(), shift() follows the read -> calculate -> mutate pattern for // exception safety. shift() { // must not be called on an empty queue const oldFront = this._front; let newFront = oldFront; const oldCursor = this._cursor; let newCursor = oldCursor + 1; const elements = oldFront._elements; const element = elements[oldCursor]; if (newCursor === QUEUE_MAX_ARRAY_SIZE) { newFront = oldFront._next; newCursor = 0; } // No mutations before this point. --this._size; this._cursor = newCursor; if (oldFront !== newFront) { this._front = newFront; } // Permit shifted element to be garbage collected. elements[oldCursor] = undefined; return element; } // The tricky thing about forEach() is that it can be called // re-entrantly. The queue may be mutated inside the callback. It is easy to // see that push() within the callback has no negative effects since the end // of the queue is checked for on every iteration. If shift() is called // repeatedly within the callback then the next iteration may return an // element that has been removed. In this case the callback will be called // with undefined values until we either "catch up" with elements that still // exist or reach the back of the queue. forEach(callback) { let i = this._cursor; let node = this._front; let elements = node._elements; while (i !== elements.length || node._next !== undefined) { if (i === elements.length) { node = node._next; elements = node._elements; i = 0; if (elements.length === 0) { break; } } callback(elements[i]); ++i; } } // Return the element that would be returned if shift() was called now, // without modifying the queue. peek() { // must not be called on an empty queue const front = this._front; const cursor = this._cursor; return front._elements[cursor]; } } function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === 'readable') { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === 'closed') { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); } } // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state // check. function ReadableStreamReaderGenericCancel(reader, reason) { const stream = reader._ownerReadableStream; return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { if (reader._ownerReadableStream._state === 'readable') { defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } reader._ownerReadableStream._reader = undefined; reader._ownerReadableStream = undefined; } // Helper functions for the readers. function readerLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released reader'); } // Helper functions for the ReadableStreamDefaultReader. function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = newPromise((resolve, reject) => { reader._closedPromise_resolve = resolve; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseReject(reader, reason); } function defaultReaderClosedPromiseInitializeAsResolved(reader) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseResolve(reader); } function defaultReaderClosedPromiseReject(reader, reason) { if (reader._closedPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(reader._closedPromise); reader._closedPromise_reject(reason); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { defaultReaderClosedPromiseInitializeAsRejected(reader, reason); } function defaultReaderClosedPromiseResolve(reader) { if (reader._closedPromise_resolve === undefined) { return; } reader._closedPromise_resolve(undefined); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); const PullSteps = SymbolPolyfill('[[PullSteps]]'); /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill const NumberIsFinite = Number.isFinite || function (x) { return typeof x === 'number' && isFinite(x); }; /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill const MathTrunc = Math.trunc || function (v) { return v < 0 ? Math.ceil(v) : Math.floor(v); }; // https://heycam.github.io/webidl/#idl-dictionaries function isDictionary(x) { return typeof x === 'object' || typeof x === 'function'; } function assertDictionary(obj, context) { if (obj !== undefined && !isDictionary(obj)) { throw new TypeError(`${context} is not an object.`); } } // https://heycam.github.io/webidl/#idl-callback-functions function assertFunction(x, context) { if (typeof x !== 'function') { throw new TypeError(`${context} is not a function.`); } } // https://heycam.github.io/webidl/#idl-object function isObject(x) { return (typeof x === 'object' && x !== null) || typeof x === 'function'; } function assertObject(x, context) { if (!isObject(x)) { throw new TypeError(`${context} is not an object.`); } } function assertRequiredArgument(x, position, context) { if (x === undefined) { throw new TypeError(`Parameter ${position} is required in '${context}'.`); } } function assertRequiredField(x, field, context) { if (x === undefined) { throw new TypeError(`${field} is required in '${context}'.`); } } // https://heycam.github.io/webidl/#idl-unrestricted-double function convertUnrestrictedDouble(value) { return Number(value); } function censorNegativeZero(x) { return x === 0 ? 0 : x; } function integerPart(x) { return censorNegativeZero(MathTrunc(x)); } // https://heycam.github.io/webidl/#idl-unsigned-long-long function convertUnsignedLongLongWithEnforceRange(value, context) { const lowerBound = 0; const upperBound = Number.MAX_SAFE_INTEGER; let x = Number(value); x = censorNegativeZero(x); if (!NumberIsFinite(x)) { throw new TypeError(`${context} is not a finite number`); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); } if (!NumberIsFinite(x) || x === 0) { return 0; } // TODO Use BigInt if supported? // let xBigInt = BigInt(integerPart(x)); // xBigInt = BigInt.asUintN(64, xBigInt); // return Number(xBigInt); return x; } function assertReadableStream(x, context) { if (!IsReadableStream(x)) { throw new TypeError(`${context} is not a ReadableStream.`); } } // Abstract operations for the ReadableStream. function AcquireReadableStreamDefaultReader(stream) { return new ReadableStreamDefaultReader(stream); } // ReadableStream API exposed for controllers. function ReadableStreamAddReadRequest(stream, readRequest) { stream._reader._readRequests.push(readRequest); } function ReadableStreamFulfillReadRequest(stream, chunk, done) { const reader = stream._reader; const readRequest = reader._readRequests.shift(); if (done) { readRequest._closeSteps(); } else { readRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadRequests(stream) { return stream._reader._readRequests.length; } function ReadableStreamHasDefaultReader(stream) { const reader = stream._reader; if (reader === undefined) { return false; } if (!IsReadableStreamDefaultReader(reader)) { return false; } return true; } /** * A default reader vended by a {@link ReadableStream}. * * @public */ class ReadableStreamDefaultReader { constructor(stream) { assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); assertReadableStream(stream, 'First parameter'); if (IsReadableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } ReadableStreamReaderGenericInitialize(this, stream); this._readRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('closed')); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = undefined) { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } /** * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. * * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. */ read() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('read')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('read from')); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), _closeSteps: () => resolvePromise({ value: undefined, done: true }), _errorSteps: e => rejectPromise(e) }; ReadableStreamDefaultReaderRead(this, readRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamDefaultReader(this)) { throw defaultReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } if (this._readRequests.length > 0) { throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); } ReadableStreamReaderGenericRelease(this); } } Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableStreamDefaultReader', configurable: true }); } // Abstract operations for the readers. function IsReadableStreamDefaultReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { return false; } return x instanceof ReadableStreamDefaultReader; } function ReadableStreamDefaultReaderRead(reader, readRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === 'closed') { readRequest._closeSteps(); } else if (stream._state === 'errored') { readRequest._errorSteps(stream._storedError); } else { stream._readableStreamController[PullSteps](readRequest); } } // Helper functions for the ReadableStreamDefaultReader. function defaultReaderBrandCheckException(name) { return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } /// /* eslint-disable @typescript-eslint/no-empty-function */ const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); /// class ReadableStreamAsyncIteratorImpl { constructor(reader, preventCancel) { this._ongoingPromise = undefined; this._isFinished = false; this._reader = reader; this._preventCancel = preventCancel; } next() { const nextSteps = () => this._nextSteps(); this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); return this._ongoingPromise; } return(value) { const returnSteps = () => this._returnSteps(value); return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); } _nextSteps() { if (this._isFinished) { return Promise.resolve({ value: undefined, done: true }); } const reader = this._reader; if (reader._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('iterate')); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: chunk => { this._ongoingPromise = undefined; // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. // FIXME Is this a bug in the specification, or in the test? queueMicrotask(() => resolvePromise({ value: chunk, done: false })); }, _closeSteps: () => { this._ongoingPromise = undefined; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); resolvePromise({ value: undefined, done: true }); }, _errorSteps: reason => { this._ongoingPromise = undefined; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); rejectPromise(reason); } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promise; } _returnSteps(value) { if (this._isFinished) { return Promise.resolve({ value, done: true }); } this._isFinished = true; const reader = this._reader; if (reader._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('finish iterating')); } if (!this._preventCancel) { const result = ReadableStreamReaderGenericCancel(reader, value); ReadableStreamReaderGenericRelease(reader); return transformPromiseWith(result, () => ({ value, done: true })); } ReadableStreamReaderGenericRelease(reader); return promiseResolvedWith({ value, done: true }); } } const ReadableStreamAsyncIteratorPrototype = { next() { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); } return this._asyncIteratorImpl.next(); }, return(value) { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); } return this._asyncIteratorImpl.return(value); } }; if (AsyncIteratorPrototype !== undefined) { Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); } // Abstract operations for the ReadableStream. function AcquireReadableStreamAsyncIterator(stream, preventCancel) { const reader = AcquireReadableStreamDefaultReader(stream); const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); iterator._asyncIteratorImpl = impl; return iterator; } function IsReadableStreamAsyncIterator(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { return false; } try { // noinspection SuspiciousTypeOfGuard return x._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; } catch (_a) { return false; } } // Helper functions for the ReadableStream. function streamAsyncIteratorBrandCheckException(name) { return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); } /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill const NumberIsNaN = Number.isNaN || function (x) { // eslint-disable-next-line no-self-compare return x !== x; }; function CreateArrayFromList(elements) { // We use arrays to represent lists, so this is basically a no-op. // Do a slice though just in case we happen to depend on the unique-ness. return elements.slice(); } function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); } // Not implemented correctly function TransferArrayBuffer(O) { return O; } // Not implemented correctly // eslint-disable-next-line @typescript-eslint/no-unused-vars function IsDetachedBuffer(O) { return false; } function ArrayBufferSlice(buffer, begin, end) { // ArrayBuffer.prototype.slice is not available on IE10 // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice if (buffer.slice) { return buffer.slice(begin, end); } const length = end - begin; const slice = new ArrayBuffer(length); CopyDataBlockBytes(slice, 0, buffer, begin, length); return slice; } function IsNonNegativeNumber(v) { if (typeof v !== 'number') { return false; } if (NumberIsNaN(v)) { return false; } if (v < 0) { return false; } return true; } function CloneAsUint8Array(O) { const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); return new Uint8Array(buffer); } function DequeueValue(container) { const pair = container._queue.shift(); container._queueTotalSize -= pair.size; if (container._queueTotalSize < 0) { container._queueTotalSize = 0; } return pair.value; } function EnqueueValueWithSize(container, value, size) { if (!IsNonNegativeNumber(size) || size === Infinity) { throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); } container._queue.push({ value, size }); container._queueTotalSize += size; } function PeekQueueValue(container) { const pair = container._queue.peek(); return pair.value; } function ResetQueue(container) { container._queue = new SimpleQueue(); container._queueTotalSize = 0; } /** * A pull-into request in a {@link ReadableByteStreamController}. * * @public */ class ReadableStreamBYOBRequest { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. */ get view() { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('view'); } return this._view; } respond(bytesWritten) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('respond'); } assertRequiredArgument(bytesWritten, 1, 'respond'); bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } if (IsDetachedBuffer(this._view.buffer)) ; ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); } respondWithNewView(view) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('respondWithNewView'); } assertRequiredArgument(view, 1, 'respondWithNewView'); if (!ArrayBuffer.isView(view)) { throw new TypeError('You can only respond with array buffer views'); } if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } if (IsDetachedBuffer(view.buffer)) ; ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); } } Object.defineProperties(ReadableStreamBYOBRequest.prototype, { respond: { enumerable: true }, respondWithNewView: { enumerable: true }, view: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableStreamBYOBRequest', configurable: true }); } /** * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. * * @public */ class ReadableByteStreamController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the current BYOB pull request, or `null` if there isn't one. */ get byobRequest() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('byobRequest'); } return ReadableByteStreamControllerGetBYOBRequest(this); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('desiredSize'); } return ReadableByteStreamControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('close'); } if (this._closeRequested) { throw new TypeError('The stream has already been closed; do not close it again!'); } const state = this._controlledReadableByteStream._state; if (state !== 'readable') { throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); } ReadableByteStreamControllerClose(this); } enqueue(chunk) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('enqueue'); } assertRequiredArgument(chunk, 1, 'enqueue'); if (!ArrayBuffer.isView(chunk)) { throw new TypeError('chunk must be an array buffer view'); } if (chunk.byteLength === 0) { throw new TypeError('chunk must have non-zero byteLength'); } if (chunk.buffer.byteLength === 0) { throw new TypeError(`chunk's buffer must have non-zero byteLength`); } if (this._closeRequested) { throw new TypeError('stream is closed or draining'); } const state = this._controlledReadableByteStream._state; if (state !== 'readable') { throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); } ReadableByteStreamControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e = undefined) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('error'); } ReadableByteStreamControllerError(this, e); } /** @internal */ [CancelSteps](reason) { ReadableByteStreamControllerClearPendingPullIntos(this); ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableByteStreamControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableByteStream; if (this._queueTotalSize > 0) { const entry = this._queue.shift(); this._queueTotalSize -= entry.byteLength; ReadableByteStreamControllerHandleQueueDrain(this); const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); readRequest._chunkSteps(view); return; } const autoAllocateChunkSize = this._autoAllocateChunkSize; if (autoAllocateChunkSize !== undefined) { let buffer; try { buffer = new ArrayBuffer(autoAllocateChunkSize); } catch (bufferE) { readRequest._errorSteps(bufferE); return; } const pullIntoDescriptor = { buffer, bufferByteLength: autoAllocateChunkSize, byteOffset: 0, byteLength: autoAllocateChunkSize, bytesFilled: 0, elementSize: 1, viewConstructor: Uint8Array, readerType: 'default' }; this._pendingPullIntos.push(pullIntoDescriptor); } ReadableStreamAddReadRequest(stream, readRequest); ReadableByteStreamControllerCallPullIfNeeded(this); } } Object.defineProperties(ReadableByteStreamController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, byobRequest: { enumerable: true }, desiredSize: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableByteStreamController', configurable: true }); } // Abstract operations for the ReadableByteStreamController. function IsReadableByteStreamController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { return false; } return x instanceof ReadableByteStreamController; } function IsReadableStreamBYOBRequest(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { return false; } return x instanceof ReadableStreamBYOBRequest; } function ReadableByteStreamControllerCallPullIfNeeded(controller) { const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; // TODO: Test controller argument const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableByteStreamControllerCallPullIfNeeded(controller); } }, e => { ReadableByteStreamControllerError(controller, e); }); } function ReadableByteStreamControllerClearPendingPullIntos(controller) { ReadableByteStreamControllerInvalidateBYOBRequest(controller); controller._pendingPullIntos = new SimpleQueue(); } function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { let done = false; if (stream._state === 'closed') { done = true; } const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); if (pullIntoDescriptor.readerType === 'default') { ReadableStreamFulfillReadRequest(stream, filledView, done); } else { ReadableStreamFulfillReadIntoRequest(stream, filledView, done); } } function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { const bytesFilled = pullIntoDescriptor.bytesFilled; const elementSize = pullIntoDescriptor.elementSize; return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); } function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { controller._queue.push({ buffer, byteOffset, byteLength }); controller._queueTotalSize += byteLength; } function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { const elementSize = pullIntoDescriptor.elementSize; const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; let totalBytesToCopyRemaining = maxBytesToCopy; let ready = false; if (maxAlignedBytes > currentAlignedBytes) { totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; ready = true; } const queue = controller._queue; while (totalBytesToCopyRemaining > 0) { const headOfQueue = queue.peek(); const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); if (headOfQueue.byteLength === bytesToCopy) { queue.shift(); } else { headOfQueue.byteOffset += bytesToCopy; headOfQueue.byteLength -= bytesToCopy; } controller._queueTotalSize -= bytesToCopy; ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); totalBytesToCopyRemaining -= bytesToCopy; } return ready; } function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { pullIntoDescriptor.bytesFilled += size; } function ReadableByteStreamControllerHandleQueueDrain(controller) { if (controller._queueTotalSize === 0 && controller._closeRequested) { ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(controller._controlledReadableByteStream); } else { ReadableByteStreamControllerCallPullIfNeeded(controller); } } function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { if (controller._byobRequest === null) { return; } controller._byobRequest._associatedReadableByteStreamController = undefined; controller._byobRequest._view = null; controller._byobRequest = null; } function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { while (controller._pendingPullIntos.length > 0) { if (controller._queueTotalSize === 0) { return; } const pullIntoDescriptor = controller._pendingPullIntos.peek(); if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); } } } function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { const stream = controller._controlledReadableByteStream; let elementSize = 1; if (view.constructor !== DataView) { elementSize = view.constructor.BYTES_PER_ELEMENT; } const ctor = view.constructor; // try { const buffer = TransferArrayBuffer(view.buffer); // } catch (e) { // readIntoRequest._errorSteps(e); // return; // } const pullIntoDescriptor = { buffer, bufferByteLength: buffer.byteLength, byteOffset: view.byteOffset, byteLength: view.byteLength, bytesFilled: 0, elementSize, viewConstructor: ctor, readerType: 'byob' }; if (controller._pendingPullIntos.length > 0) { controller._pendingPullIntos.push(pullIntoDescriptor); // No ReadableByteStreamControllerCallPullIfNeeded() call since: // - No change happens on desiredSize // - The source has already been notified of that there's at least 1 pending read(view) ReadableStreamAddReadIntoRequest(stream, readIntoRequest); return; } if (stream._state === 'closed') { const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); readIntoRequest._closeSteps(emptyView); return; } if (controller._queueTotalSize > 0) { if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); ReadableByteStreamControllerHandleQueueDrain(controller); readIntoRequest._chunkSteps(filledView); return; } if (controller._closeRequested) { const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); readIntoRequest._errorSteps(e); return; } } controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(stream, readIntoRequest); ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { const stream = controller._controlledReadableByteStream; if (ReadableStreamHasBYOBReader(stream)) { while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); } } } function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { return; } ReadableByteStreamControllerShiftPendingPullInto(controller); const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; if (remainderSize > 0) { const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); } pullIntoDescriptor.bytesFilled -= remainderSize; ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); ReadableByteStreamControllerInvalidateBYOBRequest(controller); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { ReadableByteStreamControllerRespondInClosedState(controller); } else { ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerShiftPendingPullInto(controller) { const descriptor = controller._pendingPullIntos.shift(); return descriptor; } function ReadableByteStreamControllerShouldCallPull(controller) { const stream = controller._controlledReadableByteStream; if (stream._state !== 'readable') { return false; } if (controller._closeRequested) { return false; } if (!controller._started) { return false; } if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { return true; } const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableByteStreamControllerClearAlgorithms(controller) { controller._pullAlgorithm = undefined; controller._cancelAlgorithm = undefined; } // A client of ReadableByteStreamController may use these functions directly to bypass state check. function ReadableByteStreamControllerClose(controller) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== 'readable') { return; } if (controller._queueTotalSize > 0) { controller._closeRequested = true; return; } if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (firstPendingPullInto.bytesFilled > 0) { const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); throw e; } } ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(stream); } function ReadableByteStreamControllerEnqueue(controller, chunk) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== 'readable') { return; } const buffer = chunk.buffer; const byteOffset = chunk.byteOffset; const byteLength = chunk.byteLength; const transferredBuffer = TransferArrayBuffer(buffer); if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); } ReadableByteStreamControllerInvalidateBYOBRequest(controller); if (ReadableStreamHasDefaultReader(stream)) { if (ReadableStreamGetNumReadRequests(stream) === 0) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } else { if (controller._pendingPullIntos.length > 0) { ReadableByteStreamControllerShiftPendingPullInto(controller); } const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); ReadableStreamFulfillReadRequest(stream, transferredView, false); } } else if (ReadableStreamHasBYOBReader(stream)) { // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } else { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerError(controller, e) { const stream = controller._controlledReadableByteStream; if (stream._state !== 'readable') { return; } ReadableByteStreamControllerClearPendingPullIntos(controller); ResetQueue(controller); ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamError(stream, e); } function ReadableByteStreamControllerGetBYOBRequest(controller) { if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { const firstDescriptor = controller._pendingPullIntos.peek(); const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); SetUpReadableStreamBYOBRequest(byobRequest, controller, view); controller._byobRequest = byobRequest; } return controller._byobRequest; } function ReadableByteStreamControllerGetDesiredSize(controller) { const state = controller._controlledReadableByteStream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableByteStreamControllerRespond(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { if (bytesWritten !== 0) { throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); } } else { if (bytesWritten === 0) { throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); } if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { throw new RangeError('bytesWritten out of range'); } } firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } function ReadableByteStreamControllerRespondWithNewView(controller, view) { const firstDescriptor = controller._pendingPullIntos.peek(); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { if (view.byteLength !== 0) { throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); } } else { if (view.byteLength === 0) { throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); } } if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { throw new RangeError('The region specified by view does not match byobRequest'); } if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { throw new RangeError('The buffer of view has different capacity than byobRequest'); } if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { throw new RangeError('The region specified by view is larger than byobRequest'); } const viewByteLength = view.byteLength; firstDescriptor.buffer = TransferArrayBuffer(view.buffer); ReadableByteStreamControllerRespondInternal(controller, viewByteLength); } function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { controller._controlledReadableByteStream = stream; controller._pullAgain = false; controller._pulling = false; controller._byobRequest = null; // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. controller._queue = controller._queueTotalSize = undefined; ResetQueue(controller); controller._closeRequested = false; controller._started = false; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._autoAllocateChunkSize = autoAllocateChunkSize; controller._pendingPullIntos = new SimpleQueue(); stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableByteStreamControllerCallPullIfNeeded(controller); }, r => { ReadableByteStreamControllerError(controller, r); }); } function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { const controller = Object.create(ReadableByteStreamController.prototype); let startAlgorithm = () => undefined; let pullAlgorithm = () => promiseResolvedWith(undefined); let cancelAlgorithm = () => promiseResolvedWith(undefined); if (underlyingByteSource.start !== undefined) { startAlgorithm = () => underlyingByteSource.start(controller); } if (underlyingByteSource.pull !== undefined) { pullAlgorithm = () => underlyingByteSource.pull(controller); } if (underlyingByteSource.cancel !== undefined) { cancelAlgorithm = reason => underlyingByteSource.cancel(reason); } const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; if (autoAllocateChunkSize === 0) { throw new TypeError('autoAllocateChunkSize must be greater than 0'); } SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); } function SetUpReadableStreamBYOBRequest(request, controller, view) { request._associatedReadableByteStreamController = controller; request._view = view; } // Helper functions for the ReadableStreamBYOBRequest. function byobRequestBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); } // Helper functions for the ReadableByteStreamController. function byteStreamControllerBrandCheckException(name) { return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); } // Abstract operations for the ReadableStream. function AcquireReadableStreamBYOBReader(stream) { return new ReadableStreamBYOBReader(stream); } // ReadableStream API exposed for controllers. function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { stream._reader._readIntoRequests.push(readIntoRequest); } function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { const reader = stream._reader; const readIntoRequest = reader._readIntoRequests.shift(); if (done) { readIntoRequest._closeSteps(chunk); } else { readIntoRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadIntoRequests(stream) { return stream._reader._readIntoRequests.length; } function ReadableStreamHasBYOBReader(stream) { const reader = stream._reader; if (reader === undefined) { return false; } if (!IsReadableStreamBYOBReader(reader)) { return false; } return true; } /** * A BYOB reader vended by a {@link ReadableStream}. * * @public */ class ReadableStreamBYOBReader { constructor(stream) { assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); assertReadableStream(stream, 'First parameter'); if (IsReadableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } if (!IsReadableByteStreamController(stream._readableStreamController)) { throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + 'source'); } ReadableStreamReaderGenericInitialize(this, stream); this._readIntoRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('closed')); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = undefined) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } /** * Attempts to reads bytes into view, and returns a promise resolved with the result. * * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. */ read(view) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('read')); } if (!ArrayBuffer.isView(view)) { return promiseRejectedWith(new TypeError('view must be an array buffer view')); } if (view.byteLength === 0) { return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); } if (view.buffer.byteLength === 0) { return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); } if (IsDetachedBuffer(view.buffer)) ; if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('read from')); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readIntoRequest = { _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), _errorSteps: e => rejectPromise(e) }; ReadableStreamBYOBReaderRead(this, view, readIntoRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamBYOBReader(this)) { throw byobReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } if (this._readIntoRequests.length > 0) { throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); } ReadableStreamReaderGenericRelease(this); } } Object.defineProperties(ReadableStreamBYOBReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableStreamBYOBReader', configurable: true }); } // Abstract operations for the readers. function IsReadableStreamBYOBReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { return false; } return x instanceof ReadableStreamBYOBReader; } function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === 'errored') { readIntoRequest._errorSteps(stream._storedError); } else { ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); } } // Helper functions for the ReadableStreamBYOBReader. function byobReaderBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); } function ExtractHighWaterMark(strategy, defaultHWM) { const { highWaterMark } = strategy; if (highWaterMark === undefined) { return defaultHWM; } if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError('Invalid highWaterMark'); } return highWaterMark; } function ExtractSizeAlgorithm(strategy) { const { size } = strategy; if (!size) { return () => 1; } return size; } function convertQueuingStrategy(init, context) { assertDictionary(init, context); const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; const size = init === null || init === void 0 ? void 0 : init.size; return { highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) }; } function convertQueuingStrategySize(fn, context) { assertFunction(fn, context); return chunk => convertUnrestrictedDouble(fn(chunk)); } function convertUnderlyingSink(original, context) { assertDictionary(original, context); const abort = original === null || original === void 0 ? void 0 : original.abort; const close = original === null || original === void 0 ? void 0 : original.close; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; const write = original === null || original === void 0 ? void 0 : original.write; return { abort: abort === undefined ? undefined : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), close: close === undefined ? undefined : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), start: start === undefined ? undefined : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), write: write === undefined ? undefined : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), type }; } function convertUnderlyingSinkAbortCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSinkCloseCallback(fn, original, context) { assertFunction(fn, context); return () => promiseCall(fn, original, []); } function convertUnderlyingSinkStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertUnderlyingSinkWriteCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } function assertWritableStream(x, context) { if (!IsWritableStream(x)) { throw new TypeError(`${context} is not a WritableStream.`); } } function isAbortSignal(value) { if (typeof value !== 'object' || value === null) { return false; } try { return typeof value.aborted === 'boolean'; } catch (_a) { // AbortSignal.prototype.aborted throws if its brand check fails return false; } } const supportsAbortController = typeof AbortController === 'function'; /** * Construct a new AbortController, if supported by the platform. * * @internal */ function createAbortController() { if (supportsAbortController) { return new AbortController(); } return undefined; } /** * A writable stream represents a destination for data, into which you can write. * * @public */ class WritableStream { constructor(rawUnderlyingSink = {}, rawStrategy = {}) { if (rawUnderlyingSink === undefined) { rawUnderlyingSink = null; } else { assertObject(rawUnderlyingSink, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); InitializeWritableStream(this); const type = underlyingSink.type; if (type !== undefined) { throw new RangeError('Invalid type is specified'); } const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); } /** * Returns whether or not the writable stream is locked to a writer. */ get locked() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2('locked'); } return IsWritableStreamLocked(this); } /** * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort * mechanism of the underlying sink. * * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel * the stream) if the stream is currently locked. */ abort(reason = undefined) { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2('abort')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); } return WritableStreamAbort(this, reason); } /** * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its * close behavior. During this time any further attempts to write will fail (without erroring the stream). * * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. */ close() { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2('close')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); } if (WritableStreamCloseQueuedOrInFlight(this)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamClose(this); } /** * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream * is locked, no other writer can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to write to a stream * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at * the same time, which would cause the resulting written data to be unpredictable and probably useless. */ getWriter() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2('getWriter'); } return AcquireWritableStreamDefaultWriter(this); } } Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { value: 'WritableStream', configurable: true }); } // Abstract operations for the WritableStream. function AcquireWritableStreamDefaultWriter(stream) { return new WritableStreamDefaultWriter(stream); } // Throws if and only if startAlgorithm throws. function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(WritableStream.prototype); InitializeWritableStream(stream); const controller = Object.create(WritableStreamDefaultController.prototype); SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function InitializeWritableStream(stream) { stream._state = 'writable'; // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is // 'erroring' or 'errored'. May be set to an undefined value. stream._storedError = undefined; stream._writer = undefined; // Initialize to undefined first because the constructor of the controller checks this // variable to validate the caller. stream._writableStreamController = undefined; // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data // producer without waiting for the queued writes to finish. stream._writeRequests = new SimpleQueue(); // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. stream._inFlightWriteRequest = undefined; // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer // has been detached. stream._closeRequest = undefined; // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. stream._inFlightCloseRequest = undefined; // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. stream._pendingAbortRequest = undefined; // The backpressure signal set by the controller. stream._backpressure = false; } function IsWritableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { return false; } return x instanceof WritableStream; } function IsWritableStreamLocked(stream) { if (stream._writer === undefined) { return false; } return true; } function WritableStreamAbort(stream, reason) { var _a; if (stream._state === 'closed' || stream._state === 'errored') { return promiseResolvedWith(undefined); } stream._writableStreamController._abortReason = reason; (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', // but it doesn't know that signaling abort runs author code that might have changed the state. // Widen the type again by casting to WritableStreamState. const state = stream._state; if (state === 'closed' || state === 'errored') { return promiseResolvedWith(undefined); } if (stream._pendingAbortRequest !== undefined) { return stream._pendingAbortRequest._promise; } let wasAlreadyErroring = false; if (state === 'erroring') { wasAlreadyErroring = true; // reason will not be used, so don't keep a reference to it. reason = undefined; } const promise = newPromise((resolve, reject) => { stream._pendingAbortRequest = { _promise: undefined, _resolve: resolve, _reject: reject, _reason: reason, _wasAlreadyErroring: wasAlreadyErroring }; }); stream._pendingAbortRequest._promise = promise; if (!wasAlreadyErroring) { WritableStreamStartErroring(stream, reason); } return promise; } function WritableStreamClose(stream) { const state = stream._state; if (state === 'closed' || state === 'errored') { return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); } const promise = newPromise((resolve, reject) => { const closeRequest = { _resolve: resolve, _reject: reject }; stream._closeRequest = closeRequest; }); const writer = stream._writer; if (writer !== undefined && stream._backpressure && state === 'writable') { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } // WritableStream API exposed for controllers. function WritableStreamAddWriteRequest(stream) { const promise = newPromise((resolve, reject) => { const writeRequest = { _resolve: resolve, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream, error) { const state = stream._state; if (state === 'writable') { WritableStreamStartErroring(stream, error); return; } WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream, reason) { const controller = stream._writableStreamController; stream._state = 'erroring'; stream._storedError = reason; const writer = stream._writer; if (writer !== undefined) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream) { stream._state = 'errored'; stream._writableStreamController[ErrorSteps](); const storedError = stream._storedError; stream._writeRequests.forEach(writeRequest => { writeRequest._reject(storedError); }); stream._writeRequests = new SimpleQueue(); if (stream._pendingAbortRequest === undefined) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = undefined; if (abortRequest._wasAlreadyErroring) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); uponPromise(promise, () => { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }, (reason) => { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }); } function WritableStreamFinishInFlightWrite(stream) { stream._inFlightWriteRequest._resolve(undefined); stream._inFlightWriteRequest = undefined; } function WritableStreamFinishInFlightWriteWithError(stream, error) { stream._inFlightWriteRequest._reject(error); stream._inFlightWriteRequest = undefined; WritableStreamDealWithRejection(stream, error); } function WritableStreamFinishInFlightClose(stream) { stream._inFlightCloseRequest._resolve(undefined); stream._inFlightCloseRequest = undefined; const state = stream._state; if (state === 'erroring') { // The error was too late to do anything, so it is ignored. stream._storedError = undefined; if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = undefined; } } stream._state = 'closed'; const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseResolve(writer); } } function WritableStreamFinishInFlightCloseWithError(stream, error) { stream._inFlightCloseRequest._reject(error); stream._inFlightCloseRequest = undefined; // Never execute sink abort() after sink close(). if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._reject(error); stream._pendingAbortRequest = undefined; } WritableStreamDealWithRejection(stream, error); } // TODO(ricea): Fix alphabetical order. function WritableStreamCloseQueuedOrInFlight(stream) { if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream) { if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream) { stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = undefined; } function WritableStreamMarkFirstWriteRequestInFlight(stream) { stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { if (stream._closeRequest !== undefined) { stream._closeRequest._reject(stream._storedError); stream._closeRequest = undefined; } const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseReject(writer, stream._storedError); } } function WritableStreamUpdateBackpressure(stream, backpressure) { const writer = stream._writer; if (writer !== undefined && backpressure !== stream._backpressure) { if (backpressure) { defaultWriterReadyPromiseReset(writer); } else { defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } /** * A default writer vended by a {@link WritableStream}. * * @public */ class WritableStreamDefaultWriter { constructor(stream) { assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); assertWritableStream(stream, 'First parameter'); if (IsWritableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive writing by another writer'); } this._ownerWritableStream = stream; stream._writer = this; const state = stream._state; if (state === 'writable') { if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state === 'erroring') { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); defaultWriterClosedPromiseInitialize(this); } else if (state === 'closed') { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { const storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the writer’s lock is released before the stream finishes closing. */ get closed() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('closed')); } return this._closedPromise; } /** * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. * A producer can use this information to determine the right amount of data to write. * * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when * the writer’s lock is released. */ get desiredSize() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('desiredSize'); } if (this._ownerWritableStream === undefined) { throw defaultWriterLockException('desiredSize'); } return WritableStreamDefaultWriterGetDesiredSize(this); } /** * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips * back to zero or below, the getter will return a new promise that stays pending until the next transition. * * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become * rejected. */ get ready() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('ready')); } return this._readyPromise; } /** * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. */ abort(reason = undefined) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('abort')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('abort')); } return WritableStreamDefaultWriterAbort(this, reason); } /** * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. */ close() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('close')); } const stream = this._ownerWritableStream; if (stream === undefined) { return promiseRejectedWith(defaultWriterLockException('close')); } if (WritableStreamCloseQueuedOrInFlight(stream)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamDefaultWriterClose(this); } /** * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from * now on; otherwise, the writer will appear closed. * * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents * other producers from writing in an interleaved manner. */ releaseLock() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('releaseLock'); } const stream = this._ownerWritableStream; if (stream === undefined) { return; } WritableStreamDefaultWriterRelease(this); } write(chunk = undefined) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('write')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('write to')); } return WritableStreamDefaultWriterWrite(this, chunk); } } Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { value: 'WritableStreamDefaultWriter', configurable: true }); } // Abstract operations for the WritableStreamDefaultWriter. function IsWritableStreamDefaultWriter(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { return false; } return x instanceof WritableStreamDefaultWriter; } // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. function WritableStreamDefaultWriterAbort(writer, reason) { const stream = writer._ownerWritableStream; return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer) { const stream = writer._ownerWritableStream; return WritableStreamClose(stream); } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { const stream = writer._ownerWritableStream; const state = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseResolvedWith(undefined); } if (state === 'errored') { return promiseRejectedWith(stream._storedError); } return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { if (writer._closedPromiseState === 'pending') { defaultWriterClosedPromiseReject(writer, error); } else { defaultWriterClosedPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { if (writer._readyPromiseState === 'pending') { defaultWriterReadyPromiseReject(writer, error); } else { defaultWriterReadyPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterGetDesiredSize(writer) { const stream = writer._ownerWritableStream; const state = stream._state; if (state === 'errored' || state === 'erroring') { return null; } if (state === 'closed') { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer) { const stream = writer._ownerWritableStream; const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not // rejected until afterwards. This means that simply testing state will not work. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = undefined; writer._ownerWritableStream = undefined; } function WritableStreamDefaultWriterWrite(writer, chunk) { const stream = writer._ownerWritableStream; const controller = stream._writableStreamController; const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return promiseRejectedWith(defaultWriterLockException('write to')); } const state = stream._state; if (state === 'errored') { return promiseRejectedWith(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); } if (state === 'erroring') { return promiseRejectedWith(stream._storedError); } const promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } const closeSentinel = {}; /** * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. * * @public */ class WritableStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. * * @deprecated * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. */ get abortReason() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('abortReason'); } return this._abortReason; } /** * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. */ get signal() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('signal'); } if (this._abortController === undefined) { // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, // so instead we only implement support for `signal` if we find a global `AbortController` constructor. throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); } return this._abortController.signal; } /** * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. * * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the * normal lifecycle of interactions with the underlying sink. */ error(e = undefined) { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('error'); } const state = this._controlledWritableStream._state; if (state !== 'writable') { // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so // just treat it as a no-op. return; } WritableStreamDefaultControllerError(this, e); } /** @internal */ [AbortSteps](reason) { const result = this._abortAlgorithm(reason); WritableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [ErrorSteps]() { ResetQueue(this); } } Object.defineProperties(WritableStreamDefaultController.prototype, { abortReason: { enumerable: true }, signal: { enumerable: true }, error: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { value: 'WritableStreamDefaultController', configurable: true }); } // Abstract operations implementing interface required by the WritableStream. function IsWritableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { return false; } return x instanceof WritableStreamDefaultController; } function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledWritableStream = stream; stream._writableStreamController = controller; // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. controller._queue = undefined; controller._queueTotalSize = undefined; ResetQueue(controller); controller._abortReason = undefined; controller._abortController = createAbortController(); controller._started = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._writeAlgorithm = writeAlgorithm; controller._closeAlgorithm = closeAlgorithm; controller._abortAlgorithm = abortAlgorithm; const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); const startPromise = promiseResolvedWith(startResult); uponPromise(startPromise, () => { controller._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, r => { controller._started = true; WritableStreamDealWithRejection(stream, r); }); } function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { const controller = Object.create(WritableStreamDefaultController.prototype); let startAlgorithm = () => undefined; let writeAlgorithm = () => promiseResolvedWith(undefined); let closeAlgorithm = () => promiseResolvedWith(undefined); let abortAlgorithm = () => promiseResolvedWith(undefined); if (underlyingSink.start !== undefined) { startAlgorithm = () => underlyingSink.start(controller); } if (underlyingSink.write !== undefined) { writeAlgorithm = chunk => underlyingSink.write(chunk, controller); } if (underlyingSink.close !== undefined) { closeAlgorithm = () => underlyingSink.close(); } if (underlyingSink.abort !== undefined) { abortAlgorithm = reason => underlyingSink.abort(reason); } SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); } // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. function WritableStreamDefaultControllerClearAlgorithms(controller) { controller._writeAlgorithm = undefined; controller._closeAlgorithm = undefined; controller._abortAlgorithm = undefined; controller._strategySizeAlgorithm = undefined; } function WritableStreamDefaultControllerClose(controller) { EnqueueValueWithSize(controller, closeSentinel, 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { try { return controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller) { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } const stream = controller._controlledWritableStream; if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } // Abstract operations for the WritableStreamDefaultController. function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { const stream = controller._controlledWritableStream; if (!controller._started) { return; } if (stream._inFlightWriteRequest !== undefined) { return; } const state = stream._state; if (state === 'erroring') { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } const value = PeekQueueValue(controller); if (value === closeSentinel) { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, value); } } function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { if (controller._controlledWritableStream._state === 'writable') { WritableStreamDefaultControllerError(controller, error); } } function WritableStreamDefaultControllerProcessClose(controller) { const stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); const sinkClosePromise = controller._closeAlgorithm(); WritableStreamDefaultControllerClearAlgorithms(controller); uponPromise(sinkClosePromise, () => { WritableStreamFinishInFlightClose(stream); }, reason => { WritableStreamFinishInFlightCloseWithError(stream, reason); }); } function WritableStreamDefaultControllerProcessWrite(controller, chunk) { const stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); const sinkWritePromise = controller._writeAlgorithm(chunk); uponPromise(sinkWritePromise, () => { WritableStreamFinishInFlightWrite(stream); const state = stream._state; DequeueValue(controller); if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, reason => { if (stream._state === 'writable') { WritableStreamDefaultControllerClearAlgorithms(controller); } WritableStreamFinishInFlightWriteWithError(stream, reason); }); } function WritableStreamDefaultControllerGetBackpressure(controller) { const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } // A client of WritableStreamDefaultController may use these functions directly to bypass state check. function WritableStreamDefaultControllerError(controller, error) { const stream = controller._controlledWritableStream; WritableStreamDefaultControllerClearAlgorithms(controller); WritableStreamStartErroring(stream, error); } // Helper functions for the WritableStream. function streamBrandCheckException$2(name) { return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } // Helper functions for the WritableStreamDefaultController. function defaultControllerBrandCheckException$2(name) { return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } // Helper functions for the WritableStreamDefaultWriter. function defaultWriterBrandCheckException(name) { return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } function defaultWriterLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released writer'); } function defaultWriterClosedPromiseInitialize(writer) { writer._closedPromise = newPromise((resolve, reject) => { writer._closedPromise_resolve = resolve; writer._closedPromise_reject = reject; writer._closedPromiseState = 'pending'; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseReject(writer, reason); } function defaultWriterClosedPromiseInitializeAsResolved(writer) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseResolve(writer); } function defaultWriterClosedPromiseReject(writer, reason) { if (writer._closedPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(writer._closedPromise); writer._closedPromise_reject(reason); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseResetToRejected(writer, reason) { defaultWriterClosedPromiseInitializeAsRejected(writer, reason); } function defaultWriterClosedPromiseResolve(writer) { if (writer._closedPromise_resolve === undefined) { return; } writer._closedPromise_resolve(undefined); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'resolved'; } function defaultWriterReadyPromiseInitialize(writer) { writer._readyPromise = newPromise((resolve, reject) => { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = 'pending'; } function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseReject(writer, reason); } function defaultWriterReadyPromiseInitializeAsResolved(writer) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseResolve(writer); } function defaultWriterReadyPromiseReject(writer, reason) { if (writer._readyPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(writer._readyPromise); writer._readyPromise_reject(reason); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseReset(writer) { defaultWriterReadyPromiseInitialize(writer); } function defaultWriterReadyPromiseResetToRejected(writer, reason) { defaultWriterReadyPromiseInitializeAsRejected(writer, reason); } function defaultWriterReadyPromiseResolve(writer) { if (writer._readyPromise_resolve === undefined) { return; } writer._readyPromise_resolve(undefined); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'fulfilled'; } /// const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; /// function isDOMExceptionConstructor(ctor) { if (!(typeof ctor === 'function' || typeof ctor === 'object')) { return false; } try { new ctor(); return true; } catch (_a) { return false; } } function createDOMExceptionPolyfill() { // eslint-disable-next-line no-shadow const ctor = function DOMException(message, name) { this.message = message || ''; this.name = name || 'Error'; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }; ctor.prototype = Object.create(Error.prototype); Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); return ctor; } // eslint-disable-next-line no-redeclare const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { const reader = AcquireReadableStreamDefaultReader(source); const writer = AcquireWritableStreamDefaultWriter(dest); source._disturbed = true; let shuttingDown = false; // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. let currentWrite = promiseResolvedWith(undefined); return newPromise((resolve, reject) => { let abortAlgorithm; if (signal !== undefined) { abortAlgorithm = () => { const error = new DOMException$1('Aborted', 'AbortError'); const actions = []; if (!preventAbort) { actions.push(() => { if (dest._state === 'writable') { return WritableStreamAbort(dest, error); } return promiseResolvedWith(undefined); }); } if (!preventCancel) { actions.push(() => { if (source._state === 'readable') { return ReadableStreamCancel(source, error); } return promiseResolvedWith(undefined); }); } shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); }; if (signal.aborted) { abortAlgorithm(); return; } signal.addEventListener('abort', abortAlgorithm); } // Using reader and writer, read all chunks from this and write them to dest // - Backpressure must be enforced // - Shutdown must stop all activity function pipeLoop() { return newPromise((resolveLoop, rejectLoop) => { function next(done) { if (done) { resolveLoop(); } else { // Use `PerformPromiseThen` instead of `uponPromise` to avoid // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers PerformPromiseThen(pipeStep(), next, rejectLoop); } } next(false); }); } function pipeStep() { if (shuttingDown) { return promiseResolvedWith(true); } return PerformPromiseThen(writer._readyPromise, () => { return newPromise((resolveRead, rejectRead) => { ReadableStreamDefaultReaderRead(reader, { _chunkSteps: chunk => { currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); resolveRead(false); }, _closeSteps: () => resolveRead(true), _errorSteps: rejectRead }); }); }); } // Errors must be propagated forward isOrBecomesErrored(source, reader._closedPromise, storedError => { if (!preventAbort) { shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); } else { shutdown(true, storedError); } }); // Errors must be propagated backward isOrBecomesErrored(dest, writer._closedPromise, storedError => { if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); } else { shutdown(true, storedError); } }); // Closing must be propagated forward isOrBecomesClosed(source, reader._closedPromise, () => { if (!preventClose) { shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); } else { shutdown(); } }); // Closing must be propagated backward if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); } else { shutdown(true, destClosed); } } setPromiseIsHandledToTrue(pipeLoop()); function waitForWritesToFinish() { // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait // for that too. const oldCurrentWrite = currentWrite; return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); } function isOrBecomesErrored(stream, promise, action) { if (stream._state === 'errored') { action(stream._storedError); } else { uponRejection(promise, action); } } function isOrBecomesClosed(stream, promise, action) { if (stream._state === 'closed') { action(); } else { uponFulfillment(promise, action); } } function shutdownWithAction(action, originalIsError, originalError) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), doTheRest); } else { doTheRest(); } function doTheRest() { uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); } } function shutdown(isError, error) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); } else { finalize(isError, error); } } function finalize(isError, error) { WritableStreamDefaultWriterRelease(writer); ReadableStreamReaderGenericRelease(reader); if (signal !== undefined) { signal.removeEventListener('abort', abortAlgorithm); } if (isError) { reject(error); } else { resolve(undefined); } } }); } /** * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. * * @public */ class ReadableStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('desiredSize'); } return ReadableStreamDefaultControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('close'); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError('The stream is not in a state that permits close'); } ReadableStreamDefaultControllerClose(this); } enqueue(chunk = undefined) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('enqueue'); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError('The stream is not in a state that permits enqueue'); } return ReadableStreamDefaultControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e = undefined) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('error'); } ReadableStreamDefaultControllerError(this, e); } /** @internal */ [CancelSteps](reason) { ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableStream; if (this._queue.length > 0) { const chunk = DequeueValue(this); if (this._closeRequested && this._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(this); ReadableStreamClose(stream); } else { ReadableStreamDefaultControllerCallPullIfNeeded(this); } readRequest._chunkSteps(chunk); } else { ReadableStreamAddReadRequest(stream, readRequest); ReadableStreamDefaultControllerCallPullIfNeeded(this); } } } Object.defineProperties(ReadableStreamDefaultController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, desiredSize: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableStreamDefaultController', configurable: true }); } // Abstract operations for the ReadableStreamDefaultController. function IsReadableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { return false; } return x instanceof ReadableStreamDefaultController; } function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableStreamDefaultControllerCallPullIfNeeded(controller); } }, e => { ReadableStreamDefaultControllerError(controller, e); }); } function ReadableStreamDefaultControllerShouldCallPull(controller) { const stream = controller._controlledReadableStream; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return false; } if (!controller._started) { return false; } if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableStreamDefaultControllerClearAlgorithms(controller) { controller._pullAlgorithm = undefined; controller._cancelAlgorithm = undefined; controller._strategySizeAlgorithm = undefined; } // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. function ReadableStreamDefaultControllerClose(controller) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; controller._closeRequested = true; if (controller._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamClose(stream); } } function ReadableStreamDefaultControllerEnqueue(controller, chunk) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { ReadableStreamFulfillReadRequest(stream, chunk, false); } else { let chunkSize; try { chunkSize = controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { ReadableStreamDefaultControllerError(controller, chunkSizeE); throw chunkSizeE; } try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { ReadableStreamDefaultControllerError(controller, enqueueE); throw enqueueE; } } ReadableStreamDefaultControllerCallPullIfNeeded(controller); } function ReadableStreamDefaultControllerError(controller, e) { const stream = controller._controlledReadableStream; if (stream._state !== 'readable') { return; } ResetQueue(controller); ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamError(stream, e); } function ReadableStreamDefaultControllerGetDesiredSize(controller) { const state = controller._controlledReadableStream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } // This is used in the implementation of TransformStream. function ReadableStreamDefaultControllerHasBackpressure(controller) { if (ReadableStreamDefaultControllerShouldCallPull(controller)) { return false; } return true; } function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { const state = controller._controlledReadableStream._state; if (!controller._closeRequested && state === 'readable') { return true; } return false; } function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledReadableStream = stream; controller._queue = undefined; controller._queueTotalSize = undefined; ResetQueue(controller); controller._started = false; controller._closeRequested = false; controller._pullAgain = false; controller._pulling = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableStreamDefaultControllerCallPullIfNeeded(controller); }, r => { ReadableStreamDefaultControllerError(controller, r); }); } function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { const controller = Object.create(ReadableStreamDefaultController.prototype); let startAlgorithm = () => undefined; let pullAlgorithm = () => promiseResolvedWith(undefined); let cancelAlgorithm = () => promiseResolvedWith(undefined); if (underlyingSource.start !== undefined) { startAlgorithm = () => underlyingSource.start(controller); } if (underlyingSource.pull !== undefined) { pullAlgorithm = () => underlyingSource.pull(controller); } if (underlyingSource.cancel !== undefined) { cancelAlgorithm = reason => underlyingSource.cancel(reason); } SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); } // Helper functions for the ReadableStreamDefaultController. function defaultControllerBrandCheckException$1(name) { return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); } function ReadableStreamTee(stream, cloneForBranch2) { if (IsReadableByteStreamController(stream._readableStreamController)) { return ReadableByteStreamTee(stream); } return ReadableStreamDefaultTee(stream); } function ReadableStreamDefaultTee(stream, cloneForBranch2) { const reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgain = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise(resolve => { resolveCancelPromise = resolve; }); function pullAlgorithm() { if (reading) { readAgain = true; return promiseResolvedWith(undefined); } reading = true; const readRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. queueMicrotask(() => { readAgain = false; const chunk1 = chunk; const chunk2 = chunk; // There is no way to access the cloning code right now in the reference implementation. // If we add one then we'll need an implementation for serializable objects. // if (!canceled2 && cloneForBranch2) { // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); // } if (!canceled1) { ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgain) { pullAlgorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableStreamDefaultControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableStreamDefaultControllerClose(branch2._readableStreamController); } if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promiseResolvedWith(undefined); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { // do nothing } branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); uponRejection(reader._closedPromise, (r) => { ReadableStreamDefaultControllerError(branch1._readableStreamController, r); ReadableStreamDefaultControllerError(branch2._readableStreamController, r); if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }); return [branch1, branch2]; } function ReadableByteStreamTee(stream) { let reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgainForBranch1 = false; let readAgainForBranch2 = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise(resolve => { resolveCancelPromise = resolve; }); function forwardReaderError(thisReader) { uponRejection(thisReader._closedPromise, r => { if (thisReader !== reader) { return; } ReadableByteStreamControllerError(branch1._readableStreamController, r); ReadableByteStreamControllerError(branch2._readableStreamController, r); if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }); } function pullWithDefaultReader() { if (IsReadableStreamBYOBReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamDefaultReader(stream); forwardReaderError(reader); } const readRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const chunk1 = chunk; let chunk2 = chunk; if (!canceled1 && !canceled2) { try { chunk2 = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } } if (!canceled1) { ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableByteStreamControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableByteStreamControllerClose(branch2._readableStreamController); } if (branch1._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); } if (branch2._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); } if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); } function pullWithBYOBReader(view, forBranch2) { if (IsReadableStreamDefaultReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamBYOBReader(stream); forwardReaderError(reader); } const byobBranch = forBranch2 ? branch2 : branch1; const otherBranch = forBranch2 ? branch1 : branch2; const readIntoRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!otherCanceled) { let clonedChunk; try { clonedChunk = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); } else if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: chunk => { reading = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!byobCanceled) { ReadableByteStreamControllerClose(byobBranch._readableStreamController); } if (!otherCanceled) { ReadableByteStreamControllerClose(otherBranch._readableStreamController); } if (chunk !== undefined) { if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); } } if (!byobCanceled || !otherCanceled) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); } function pull1Algorithm() { if (reading) { readAgainForBranch1 = true; return promiseResolvedWith(undefined); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, false); } return promiseResolvedWith(undefined); } function pull2Algorithm() { if (reading) { readAgainForBranch2 = true; return promiseResolvedWith(undefined); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, true); } return promiseResolvedWith(undefined); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { return; } branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); forwardReaderError(reader); return [branch1, branch2]; } function convertUnderlyingDefaultOrByteSource(source, context) { assertDictionary(source, context); const original = source; const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; const cancel = original === null || original === void 0 ? void 0 : original.cancel; const pull = original === null || original === void 0 ? void 0 : original.pull; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; return { autoAllocateChunkSize: autoAllocateChunkSize === undefined ? undefined : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), cancel: cancel === undefined ? undefined : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), pull: pull === undefined ? undefined : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), start: start === undefined ? undefined : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) }; } function convertUnderlyingSourceCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSourcePullCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertUnderlyingSourceStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertReadableStreamType(type, context) { type = `${type}`; if (type !== 'bytes') { throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); } return type; } function convertReaderOptions(options, context) { assertDictionary(options, context); const mode = options === null || options === void 0 ? void 0 : options.mode; return { mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) }; } function convertReadableStreamReaderMode(mode, context) { mode = `${mode}`; if (mode !== 'byob') { throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); } return mode; } function convertIteratorOptions(options, context) { assertDictionary(options, context); const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; return { preventCancel: Boolean(preventCancel) }; } function convertPipeOptions(options, context) { assertDictionary(options, context); const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; const signal = options === null || options === void 0 ? void 0 : options.signal; if (signal !== undefined) { assertAbortSignal(signal, `${context} has member 'signal' that`); } return { preventAbort: Boolean(preventAbort), preventCancel: Boolean(preventCancel), preventClose: Boolean(preventClose), signal }; } function assertAbortSignal(signal, context) { if (!isAbortSignal(signal)) { throw new TypeError(`${context} is not an AbortSignal.`); } } function convertReadableWritablePair(pair, context) { assertDictionary(pair, context); const readable = pair === null || pair === void 0 ? void 0 : pair.readable; assertRequiredField(readable, 'readable', 'ReadableWritablePair'); assertReadableStream(readable, `${context} has member 'readable' that`); const writable = pair === null || pair === void 0 ? void 0 : pair.writable; assertRequiredField(writable, 'writable', 'ReadableWritablePair'); assertWritableStream(writable, `${context} has member 'writable' that`); return { readable, writable }; } /** * A readable stream represents a source of data, from which you can read. * * @public */ class ReadableStream { constructor(rawUnderlyingSource = {}, rawStrategy = {}) { if (rawUnderlyingSource === undefined) { rawUnderlyingSource = null; } else { assertObject(rawUnderlyingSource, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); InitializeReadableStream(this); if (underlyingSource.type === 'bytes') { if (strategy.size !== undefined) { throw new RangeError('The strategy for a byte stream cannot have a size function'); } const highWaterMark = ExtractHighWaterMark(strategy, 0); SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); } else { const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); } } /** * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. */ get locked() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('locked'); } return IsReadableStreamLocked(this); } /** * Cancels the stream, signaling a loss of interest in the stream by a consumer. * * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} * method, which might or might not use it. */ cancel(reason = undefined) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1('cancel')); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); } return ReadableStreamCancel(this, reason); } getReader(rawOptions = undefined) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('getReader'); } const options = convertReaderOptions(rawOptions, 'First parameter'); if (options.mode === undefined) { return AcquireReadableStreamDefaultReader(this); } return AcquireReadableStreamBYOBReader(this); } pipeThrough(rawTransform, rawOptions = {}) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('pipeThrough'); } assertRequiredArgument(rawTransform, 1, 'pipeThrough'); const transform = convertReadableWritablePair(rawTransform, 'First parameter'); const options = convertPipeOptions(rawOptions, 'Second parameter'); if (IsReadableStreamLocked(this)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); } if (IsWritableStreamLocked(transform.writable)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); } const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); setPromiseIsHandledToTrue(promise); return transform.readable; } pipeTo(destination, rawOptions = {}) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); } if (destination === undefined) { return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); } if (!IsWritableStream(destination)) { return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); } let options; try { options = convertPipeOptions(rawOptions, 'Second parameter'); } catch (e) { return promiseRejectedWith(e); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); } if (IsWritableStreamLocked(destination)) { return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); } return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); } /** * Tees this readable stream, returning a two-element array containing the two resulting branches as * new {@link ReadableStream} instances. * * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be * propagated to the stream's underlying source. * * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, * this could allow interference between the two branches. */ tee() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('tee'); } const branches = ReadableStreamTee(this); return CreateArrayFromList(branches); } values(rawOptions = undefined) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('values'); } const options = convertIteratorOptions(rawOptions, 'First parameter'); return AcquireReadableStreamAsyncIterator(this, options.preventCancel); } } Object.defineProperties(ReadableStream.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { value: 'ReadableStream', configurable: true }); } if (typeof SymbolPolyfill.asyncIterator === 'symbol') { Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { value: ReadableStream.prototype.values, writable: true, configurable: true }); } // Abstract operations for the ReadableStream. // Throws if and only if startAlgorithm throws. function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableStreamDefaultController.prototype); SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); return stream; } // Throws if and only if startAlgorithm throws. function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { const stream = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableByteStreamController.prototype); SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); return stream; } function InitializeReadableStream(stream) { stream._state = 'readable'; stream._reader = undefined; stream._storedError = undefined; stream._disturbed = false; } function IsReadableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { return false; } return x instanceof ReadableStream; } function IsReadableStreamLocked(stream) { if (stream._reader === undefined) { return false; } return true; } // ReadableStream API exposed for controllers. function ReadableStreamCancel(stream, reason) { stream._disturbed = true; if (stream._state === 'closed') { return promiseResolvedWith(undefined); } if (stream._state === 'errored') { return promiseRejectedWith(stream._storedError); } ReadableStreamClose(stream); const reader = stream._reader; if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { reader._readIntoRequests.forEach(readIntoRequest => { readIntoRequest._closeSteps(undefined); }); reader._readIntoRequests = new SimpleQueue(); } const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); return transformPromiseWith(sourceCancelPromise, noop); } function ReadableStreamClose(stream) { stream._state = 'closed'; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseResolve(reader); if (IsReadableStreamDefaultReader(reader)) { reader._readRequests.forEach(readRequest => { readRequest._closeSteps(); }); reader._readRequests = new SimpleQueue(); } } function ReadableStreamError(stream, e) { stream._state = 'errored'; stream._storedError = e; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseReject(reader, e); if (IsReadableStreamDefaultReader(reader)) { reader._readRequests.forEach(readRequest => { readRequest._errorSteps(e); }); reader._readRequests = new SimpleQueue(); } else { reader._readIntoRequests.forEach(readIntoRequest => { readIntoRequest._errorSteps(e); }); reader._readIntoRequests = new SimpleQueue(); } } // Helper functions for the ReadableStream. function streamBrandCheckException$1(name) { return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); } function convertQueuingStrategyInit(init, context) { assertDictionary(init, context); const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); return { highWaterMark: convertUnrestrictedDouble(highWaterMark) }; } // The size function must not have a prototype property nor be a constructor const byteLengthSizeFunction = (chunk) => { return chunk.byteLength; }; try { Object.defineProperty(byteLengthSizeFunction, 'name', { value: 'size', configurable: true }); } catch (_a) { // This property is non-configurable in older browsers, so ignore if this throws. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility } /** * A queuing strategy that counts the number of bytes in each chunk. * * @public */ class ByteLengthQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); options = convertQueuingStrategyInit(options, 'First parameter'); this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException('highWaterMark'); } return this._byteLengthQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by returning the value of its `byteLength` property. */ get size() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException('size'); } return byteLengthSizeFunction; } } Object.defineProperties(ByteLengthQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { value: 'ByteLengthQueuingStrategy', configurable: true }); } // Helper functions for the ByteLengthQueuingStrategy. function byteLengthBrandCheckException(name) { return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); } function IsByteLengthQueuingStrategy(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { return false; } return x instanceof ByteLengthQueuingStrategy; } // The size function must not have a prototype property nor be a constructor const countSizeFunction = () => { return 1; }; try { Object.defineProperty(countSizeFunction, 'name', { value: 'size', configurable: true }); } catch (_a) { // This property is non-configurable in older browsers, so ignore if this throws. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility } /** * A queuing strategy that counts the number of chunks. * * @public */ class CountQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, 'CountQueuingStrategy'); options = convertQueuingStrategyInit(options, 'First parameter'); this._countQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException('highWaterMark'); } return this._countQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by always returning 1. * This ensures that the total queue size is a count of the number of chunks in the queue. */ get size() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException('size'); } return countSizeFunction; } } Object.defineProperties(CountQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { value: 'CountQueuingStrategy', configurable: true }); } // Helper functions for the CountQueuingStrategy. function countBrandCheckException(name) { return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); } function IsCountQueuingStrategy(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { return false; } return x instanceof CountQueuingStrategy; } function convertTransformer(original, context) { assertDictionary(original, context); const flush = original === null || original === void 0 ? void 0 : original.flush; const readableType = original === null || original === void 0 ? void 0 : original.readableType; const start = original === null || original === void 0 ? void 0 : original.start; const transform = original === null || original === void 0 ? void 0 : original.transform; const writableType = original === null || original === void 0 ? void 0 : original.writableType; return { flush: flush === undefined ? undefined : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), readableType, start: start === undefined ? undefined : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), transform: transform === undefined ? undefined : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), writableType }; } function convertTransformerFlushCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertTransformerStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertTransformerTransformCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } // Class TransformStream /** * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. * In a manner specific to the transform stream in question, writes to the writable side result in new data being * made available for reading from the readable side. * * @public */ class TransformStream { constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { if (rawTransformer === undefined) { rawTransformer = null; } const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); const transformer = convertTransformer(rawTransformer, 'First parameter'); if (transformer.readableType !== undefined) { throw new RangeError('Invalid readableType specified'); } if (transformer.writableType !== undefined) { throw new RangeError('Invalid writableType specified'); } const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); let startPromise_resolve; const startPromise = newPromise(resolve => { startPromise_resolve = resolve; }); InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); if (transformer.start !== undefined) { startPromise_resolve(transformer.start(this._transformStreamController)); } else { startPromise_resolve(undefined); } } /** * The readable side of the transform stream. */ get readable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('readable'); } return this._readable; } /** * The writable side of the transform stream. */ get writable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('writable'); } return this._writable; } } Object.defineProperties(TransformStream.prototype, { readable: { enumerable: true }, writable: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { value: 'TransformStream', configurable: true }); } function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { function startAlgorithm() { return startPromise; } function writeAlgorithm(chunk) { return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); } function abortAlgorithm(reason) { return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); } function closeAlgorithm() { return TransformStreamDefaultSinkCloseAlgorithm(stream); } stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); function pullAlgorithm() { return TransformStreamDefaultSourcePullAlgorithm(stream); } function cancelAlgorithm(reason) { TransformStreamErrorWritableAndUnblockWrite(stream, reason); return promiseResolvedWith(undefined); } stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. stream._backpressure = undefined; stream._backpressureChangePromise = undefined; stream._backpressureChangePromise_resolve = undefined; TransformStreamSetBackpressure(stream, true); stream._transformStreamController = undefined; } function IsTransformStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { return false; } return x instanceof TransformStream; } // This is a no-op if both sides are already errored. function TransformStreamError(stream, e) { ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); TransformStreamErrorWritableAndUnblockWrite(stream, e); } function TransformStreamErrorWritableAndUnblockWrite(stream, e) { TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); if (stream._backpressure) { // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time // _backpressure is set. TransformStreamSetBackpressure(stream, false); } } function TransformStreamSetBackpressure(stream, backpressure) { // Passes also when called during construction. if (stream._backpressureChangePromise !== undefined) { stream._backpressureChangePromise_resolve(); } stream._backpressureChangePromise = newPromise(resolve => { stream._backpressureChangePromise_resolve = resolve; }); stream._backpressure = backpressure; } // Class TransformStreamDefaultController /** * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. * * @public */ class TransformStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. */ get desiredSize() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('desiredSize'); } const readableController = this._controlledTransformStream._readable._readableStreamController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } enqueue(chunk = undefined) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('enqueue'); } TransformStreamDefaultControllerEnqueue(this, chunk); } /** * Errors both the readable side and the writable side of the controlled transform stream, making all future * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. */ error(reason = undefined) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('error'); } TransformStreamDefaultControllerError(this, reason); } /** * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the * transformer only needs to consume a portion of the chunks written to the writable side. */ terminate() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('terminate'); } TransformStreamDefaultControllerTerminate(this); } } Object.defineProperties(TransformStreamDefaultController.prototype, { enqueue: { enumerable: true }, error: { enumerable: true }, terminate: { enumerable: true }, desiredSize: { enumerable: true } }); if (typeof SymbolPolyfill.toStringTag === 'symbol') { Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { value: 'TransformStreamDefaultController', configurable: true }); } // Transform Stream Default Controller Abstract Operations function IsTransformStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { return false; } return x instanceof TransformStreamDefaultController; } function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { controller._controlledTransformStream = stream; stream._transformStreamController = controller; controller._transformAlgorithm = transformAlgorithm; controller._flushAlgorithm = flushAlgorithm; } function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { const controller = Object.create(TransformStreamDefaultController.prototype); let transformAlgorithm = (chunk) => { try { TransformStreamDefaultControllerEnqueue(controller, chunk); return promiseResolvedWith(undefined); } catch (transformResultE) { return promiseRejectedWith(transformResultE); } }; let flushAlgorithm = () => promiseResolvedWith(undefined); if (transformer.transform !== undefined) { transformAlgorithm = chunk => transformer.transform(chunk, controller); } if (transformer.flush !== undefined) { flushAlgorithm = () => transformer.flush(controller); } SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); } function TransformStreamDefaultControllerClearAlgorithms(controller) { controller._transformAlgorithm = undefined; controller._flushAlgorithm = undefined; } function TransformStreamDefaultControllerEnqueue(controller, chunk) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { throw new TypeError('Readable side is not in a state that permits enqueue'); } // We throttle transform invocations based on the backpressure of the ReadableStream, but we still // accept TransformStreamDefaultControllerEnqueue() calls. try { ReadableStreamDefaultControllerEnqueue(readableController, chunk); } catch (e) { // This happens when readableStrategy.size() throws. TransformStreamErrorWritableAndUnblockWrite(stream, e); throw stream._readable._storedError; } const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); if (backpressure !== stream._backpressure) { TransformStreamSetBackpressure(stream, true); } } function TransformStreamDefaultControllerError(controller, e) { TransformStreamError(controller._controlledTransformStream, e); } function TransformStreamDefaultControllerPerformTransform(controller, chunk) { const transformPromise = controller._transformAlgorithm(chunk); return transformPromiseWith(transformPromise, undefined, r => { TransformStreamError(controller._controlledTransformStream, r); throw r; }); } function TransformStreamDefaultControllerTerminate(controller) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; ReadableStreamDefaultControllerClose(readableController); const error = new TypeError('TransformStream terminated'); TransformStreamErrorWritableAndUnblockWrite(stream, error); } // TransformStreamDefaultSink Algorithms function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { const controller = stream._transformStreamController; if (stream._backpressure) { const backpressureChangePromise = stream._backpressureChangePromise; return transformPromiseWith(backpressureChangePromise, () => { const writable = stream._writable; const state = writable._state; if (state === 'erroring') { throw writable._storedError; } return TransformStreamDefaultControllerPerformTransform(controller, chunk); }); } return TransformStreamDefaultControllerPerformTransform(controller, chunk); } function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already // errored. TransformStreamError(stream, reason); return promiseResolvedWith(undefined); } function TransformStreamDefaultSinkCloseAlgorithm(stream) { // stream._readable cannot change after construction, so caching it across a call to user code is safe. const readable = stream._readable; const controller = stream._transformStreamController; const flushPromise = controller._flushAlgorithm(); TransformStreamDefaultControllerClearAlgorithms(controller); // Return a promise that is fulfilled with undefined on success. return transformPromiseWith(flushPromise, () => { if (readable._state === 'errored') { throw readable._storedError; } ReadableStreamDefaultControllerClose(readable._readableStreamController); }, r => { TransformStreamError(stream, r); throw readable._storedError; }); } // TransformStreamDefaultSource Algorithms function TransformStreamDefaultSourcePullAlgorithm(stream) { // Invariant. Enforced by the promises returned by start() and pull(). TransformStreamSetBackpressure(stream, false); // Prevent the next pull() call until there is backpressure. return stream._backpressureChangePromise; } // Helper functions for the TransformStreamDefaultController. function defaultControllerBrandCheckException(name) { return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } // Helper functions for the TransformStream. function streamBrandCheckException(name) { return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); } exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; exports.CountQueuingStrategy = CountQueuingStrategy; exports.ReadableByteStreamController = ReadableByteStreamController; exports.ReadableStream = ReadableStream; exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; exports.ReadableStreamDefaultController = ReadableStreamDefaultController; exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; exports.TransformStream = TransformStream; exports.TransformStreamDefaultController = TransformStreamDefaultController; exports.WritableStream = WritableStream; exports.WritableStreamDefaultController = WritableStreamDefaultController; exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=ponyfill.es2018.js.map /***/ }), /***/ 3311: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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.isValidationErrorLike = exports.isValidationError = exports.toValidationError = exports.fromZodError = exports.ValidationError = void 0; const zod = __importStar(__nccwpck_require__(3301)); const joinPath_1 = __nccwpck_require__(5406); const NonEmptyArray_1 = __nccwpck_require__(7915); class ValidationError extends Error { details; name; constructor(message, details = []) { super(message); this.details = details; this.name = 'ZodValidationError'; } toString() { return this.message; } } exports.ValidationError = ValidationError; function fromZodIssue(issue, issueSeparator, unionSeparator) { if (issue.code === 'invalid_union') { return issue.unionErrors .reduce((acc, zodError) => { const newIssues = zodError.issues .map((issue) => fromZodIssue(issue, issueSeparator, unionSeparator)) .join(issueSeparator); if (!acc.includes(newIssues)) { acc.push(newIssues); } return acc; }, []) .join(unionSeparator); } if ((0, NonEmptyArray_1.isNonEmptyArray)(issue.path)) { if (issue.path.length === 1) { const identifier = issue.path[0]; if (typeof identifier === 'number') { return `${issue.message} at index ${identifier}`; } } return `${issue.message} at "${(0, joinPath_1.joinPath)(issue.path)}"`; } return issue.message; } function fromZodError(zodError, options = {}) { const { maxIssuesInMessage = 99, issueSeparator = '; ', unionSeparator = ', or ', prefixSeparator = ': ', prefix = 'Validation error', } = options; const reason = zodError.errors .slice(0, maxIssuesInMessage) .map((issue) => fromZodIssue(issue, issueSeparator, unionSeparator)) .join(issueSeparator); const message = reason ? [prefix, reason].join(prefixSeparator) : prefix; return new ValidationError(message, zodError.errors); } exports.fromZodError = fromZodError; const toValidationError = (options = {}) => (err) => { if (err instanceof zod.ZodError) { return fromZodError(err, options); } if (err instanceof Error) { return err; } return new Error('Unknown error'); }; exports.toValidationError = toValidationError; function isValidationError(err) { return err instanceof ValidationError; } exports.isValidationError = isValidationError; function isValidationErrorLike(err) { return err instanceof Error && err.name === 'ZodValidationError'; } exports.isValidationErrorLike = isValidationErrorLike; /***/ }), /***/ 8780: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.CC = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = void 0; var ValidationError_1 = __nccwpck_require__(3311); __webpack_unused_export__ = ({ enumerable: true, get: function () { return ValidationError_1.ValidationError; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return ValidationError_1.toValidationError; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return ValidationError_1.isValidationError; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return ValidationError_1.isValidationErrorLike; } }); Object.defineProperty(exports, "CC", ({ enumerable: true, get: function () { return ValidationError_1.fromZodError; } })); /***/ }), /***/ 7915: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNonEmptyArray = void 0; function isNonEmptyArray(value) { return value.length !== 0; } exports.isNonEmptyArray = isNonEmptyArray; /***/ }), /***/ 5406: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPath = void 0; const identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u; function joinPath(path) { if (path.length === 1) { return path[0].toString(); } return path.reduce((acc, item) => { if (typeof item === 'number') { return acc + '[' + item.toString() + ']'; } if (item.includes('"')) { return acc + '["' + escapeQuotes(item) + '"]'; } if (!identifierRegex.test(item)) { return acc + '["' + item + '"]'; } const separator = acc.length === 0 ? '' : '.'; return acc + separator + item; }, ''); } exports.joinPath = joinPath; function escapeQuotes(str) { return str.replace(/"/g, '\\"'); } /***/ }), /***/ 9892: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; const util_1 = __nccwpck_require__(3985); exports.ZodIssueCode = util_1.util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite", ]); const quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; exports.quotelessJson = quotelessJson; class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } exports.ZodError = ZodError; ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; /***/ }), /***/ 9566: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; const en_1 = __importDefault(__nccwpck_require__(468)); exports.defaultErrorMap = en_1.default; let overrideErrorMap = en_1.default; function setErrorMap(map) { overrideErrorMap = map; } exports.setErrorMap = setErrorMap; function getErrorMap() { return overrideErrorMap; } exports.getErrorMap = getErrorMap; /***/ }), /***/ 9906: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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__(9566), exports); __exportStar(__nccwpck_require__(888), exports); __exportStar(__nccwpck_require__(9449), exports); __exportStar(__nccwpck_require__(3985), exports); __exportStar(__nccwpck_require__(9335), exports); __exportStar(__nccwpck_require__(9892), exports); /***/ }), /***/ 2513: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.errorUtil = void 0; var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil = exports.errorUtil || (exports.errorUtil = {})); /***/ }), /***/ 888: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; const errors_1 = __nccwpck_require__(9566); const en_1 = __importDefault(__nccwpck_require__(468)); const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; let errorMessage = ""; const maps = errorMaps .filter((m) => !!m) .slice() .reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage, }; }; exports.makeIssue = makeIssue; exports.EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const issue = (0, exports.makeIssue)({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), en_1.default, ].filter((x) => !!x), }); ctx.common.issues.push(issue); } exports.addIssueToContext = addIssueToContext; class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return exports.INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { syncPairs.push({ key: await pair.key, value: await pair.value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return exports.INVALID; if (value.status === "aborted") return exports.INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (typeof value.value !== "undefined" || pair.alwaysSet) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } exports.ParseStatus = ParseStatus; exports.INVALID = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); exports.DIRTY = DIRTY; const OK = (value) => ({ status: "valid", value }); exports.OK = OK; const isAborted = (x) => x.status === "aborted"; exports.isAborted = isAborted; const isDirty = (x) => x.status === "dirty"; exports.isDirty = isDirty; const isValid = (x) => x.status === "valid"; exports.isValid = isValid; const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; exports.isAsync = isAsync; /***/ }), /***/ 9449: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 3985: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; var util; (function (util) { util.assertEqual = (val) => val; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util = exports.util || (exports.util = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, }; }; })(objectUtil = exports.objectUtil || (exports.objectUtil = {})); exports.ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return exports.ZodParsedType.undefined; case "string": return exports.ZodParsedType.string; case "number": return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; case "boolean": return exports.ZodParsedType.boolean; case "function": return exports.ZodParsedType.function; case "bigint": return exports.ZodParsedType.bigint; case "symbol": return exports.ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return exports.ZodParsedType.array; } if (data === null) { return exports.ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return exports.ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return exports.ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return exports.ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return exports.ZodParsedType.date; } return exports.ZodParsedType.object; default: return exports.ZodParsedType.unknown; } }; exports.getParsedType = getParsedType; /***/ }), /***/ 3301: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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; }; 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.z = void 0; const z = __importStar(__nccwpck_require__(9906)); exports.z = z; __exportStar(__nccwpck_require__(9906), exports); exports["default"] = z; /***/ }), /***/ 468: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); const util_1 = __nccwpck_require__(3985); const ZodError_1 = __nccwpck_require__(9892); const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodError_1.ZodIssueCode.invalid_type: if (issue.received === util_1.ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodError_1.ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; break; case ZodError_1.ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; break; case ZodError_1.ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodError_1.ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; break; case ZodError_1.ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodError_1.ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodError_1.ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodError_1.ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodError_1.ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util_1.util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodError_1.ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodError_1.ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodError_1.ZodIssueCode.custom: message = `Invalid input`; break; case ZodError_1.ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodError_1.ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodError_1.ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util_1.util.assertNever(issue); } return { message }; }; exports["default"] = errorMap; /***/ }), /***/ 9335: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = void 0; const errors_1 = __nccwpck_require__(9566); const errorUtil_1 = __nccwpck_require__(2513); const parseUtil_1 = __nccwpck_require__(888); const util_1 = __nccwpck_require__(3985); const ZodError_1 = __nccwpck_require__(9892); class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } } const handleResult = (ctx, result) => { if ((0, parseUtil_1.isValid)(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError_1.ZodError(ctx.common.issues); this._error = error; return this._error; }, }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap) return { errorMap: errorMap, description }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined") { return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; } return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; }; return { errorMap: customMap, description }; } class ZodType { constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return (0, util_1.getParsedType)(input.data); } _getOrReturnCtx(input, ctx) { return (ctx || { common: input.parent.common, data: input.data, parsedType: (0, util_1.getParsedType)(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }); } _processInputParams(input) { return { status: new parseUtil_1.ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: (0, util_1.getParsedType)(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }, }; } _parseSync(input) { const result = this._parse(input); if ((0, parseUtil_1.isAsync)(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: (0, util_1.getParsedType)(data), }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: (0, util_1.getParsedType)(data), }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodError_1.ZodIssueCode.custom, ...getIssueProperties(val), }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement }, }); } superRefine(refinement) { return this._refinement(refinement); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform }, }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault, }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def), }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch, }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description, }); } pipe(target) { return ZodPipeline.create(this, target); } isOptional() { return this.safeParse(undefined).success; } isNullable() { return this.safeParse(null).success; } } exports.ZodType = ZodType; exports.Schema = ZodType; exports.ZodSchema = ZodType; const cuidRegex = /^c[^\s-]{8,}$/i; const cuid2Regex = /^[a-z][a-z0-9]*$/; const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; const datetimeRegex = (args) => { if (args.precision) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } } else if (args.precision === 0) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); } } else { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); } } }; function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } class ZodString extends ZodType { constructor() { super(...arguments); this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { validation, code: ZodError_1.ZodIssueCode.invalid_string, ...errorUtil_1.errorUtil.errToObj(message), }); this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message)); this.trim = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }], }); this.toLowerCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }], }); this.toUpperCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }], }); } _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.string, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const status = new parseUtil_1.ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } else if (tooSmall) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "email", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "emoji", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "uuid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "cuid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "cuid2", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "ulid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "url", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "regex", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message, }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: "datetime", message: check.message, }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "ip", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check], }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); } datetime(options) { var _a; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, message: options, }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex: regex, ...errorUtil_1.errorUtil.errToObj(message), }); } includes(value, options) { return this._addCheck({ kind: "includes", value: value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value: value, ...errorUtil_1.errorUtil.errToObj(message), }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value: value, ...errorUtil_1.errorUtil.errToObj(message), }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil_1.errorUtil.errToObj(message), }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil_1.errorUtil.errToObj(message), }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil_1.errorUtil.errToObj(message), }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } exports.ZodString = ZodString; ZodString.create = (params) => { var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params), }); }; function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / Math.pow(10, decCount); } class ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.number, received: ctx.parsedType, }); return parseUtil_1.INVALID; } let ctx = undefined; const status = new parseUtil_1.ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util_1.util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_finite, message: check.message, }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil_1.errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check], }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil_1.errorUtil.toString(message), }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil_1.errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil_1.errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil_1.errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil_1.errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value: value, message: errorUtil_1.errorUtil.toString(message), }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil_1.errorUtil.toString(message), }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil_1.errorUtil.toString(message), })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil_1.errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } } exports.ZodNumber = ZodNumber; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; class ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.bigint) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.bigint, received: ctx.parsedType, }); return parseUtil_1.INVALID; } let ctx = undefined; const status = new parseUtil_1.ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil_1.errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check], }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil_1.errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil_1.errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil_1.errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil_1.errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil_1.errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } exports.ZodBigInt = ZodBigInt; ZodBigInt.create = (params) => { var _a; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params), }); }; class ZodBoolean extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.boolean, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } } exports.ZodBoolean = ZodBoolean; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; class ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.date) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.date, received: ctx.parsedType, }); return parseUtil_1.INVALID; } if (isNaN(input.data.getTime())) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_date, }); return parseUtil_1.INVALID; } const status = new parseUtil_1.ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date", }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date", }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()), }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check], }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil_1.errorUtil.toString(message), }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil_1.errorUtil.toString(message), }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } } exports.ZodDate = ZodDate; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params), }); }; class ZodSymbol extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.symbol, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } } exports.ZodSymbol = ZodSymbol; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params), }); }; class ZodUndefined extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.undefined, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } } exports.ZodUndefined = ZodUndefined; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; class ZodNull extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.null, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } } exports.ZodNull = ZodNull; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params), }); }; class ZodAny extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return (0, parseUtil_1.OK)(input.data); } } exports.ZodAny = ZodAny; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params), }); }; class ZodUnknown extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return (0, parseUtil_1.OK)(input.data); } } exports.ZodUnknown = ZodUnknown; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params), }); }; class ZodNever extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.never, received: ctx.parsedType, }); return parseUtil_1.INVALID; } } exports.ZodNever = ZodNever; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params), }); }; class ZodVoid extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.void, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } } exports.ZodVoid = ZodVoid; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; class ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== util_1.ZodParsedType.array) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.array, received: ctx.parsedType, }); return parseUtil_1.INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { (0, parseUtil_1.addIssueToContext)(ctx, { code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, minimum: (tooSmall ? def.exactLength.value : undefined), maximum: (tooBig ? def.exactLength.value : undefined), type: "array", inclusive: true, exact: true, message: def.exactLength.message, }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message, }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message, }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result) => { return parseUtil_1.ParseStatus.mergeArray(status, result); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return parseUtil_1.ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, }); } nonempty(message) { return this.min(1, message); } } exports.ZodArray = ZodArray; ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape, }); } else if (schema instanceof ZodArray) { return new ZodArray({ ...schema._def, type: deepPartialify(schema.element), }); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } class ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util_1.util.objectKeys(shape); return (this._cached = { shape, keys }); } _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] }, }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.unrecognized_keys, keys: extraKeys, }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } } if (ctx.common.async) { return Promise.resolve() .then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet, }); } return syncPairs; }) .then((syncPairs) => { return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil_1.errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...(message !== undefined ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, }; return { message: defaultError, }; }, } : {}), }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip", }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough", }); } extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation, }), }); } merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape(), }), typeName: ZodFirstPartyTypeKind.ZodObject, }); return merged; } setKey(key, schema) { return this.augment({ [key]: schema }); } catchall(index) { return new ZodObject({ ...this._def, catchall: index, }); } pick(mask) { const shape = {}; util_1.util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } required(mask) { const newShape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } keyof() { return createZodEnum(util_1.util.objectKeys(this.shape)); } } exports.ZodObject = ZodObject; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; class ZodUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union, unionErrors, }); return parseUtil_1.INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx, }), ctx: childCtx, }; })).then(handleResults); } else { let dirty = undefined; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx, }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union, unionErrors, }); return parseUtil_1.INVALID; } } get options() { return this._def.options; } } exports.ZodUnion = ZodUnion; ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; const getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return Object.keys(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [undefined]; } else if (type instanceof ZodNull) { return [null]; } else { return null; } }; class ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.object) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator], }); return parseUtil_1.INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } static create(discriminator, options, params) { const optionsMap = new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params), }); } } exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; function mergeValues(a, b) { const aType = (0, util_1.getParsedType)(a); const bType = (0, util_1.getParsedType)(b); if (a === b) { return { valid: true, data: a }; } else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { const bKeys = util_1.util.objectKeys(b); const sharedKeys = util_1.util .objectKeys(a) .filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === util_1.ZodParsedType.date && bType === util_1.ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } class ZodIntersection extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { return parseUtil_1.INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_intersection_types, }); return parseUtil_1.INVALID; } if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, })); } } } exports.ZodIntersection = ZodIntersection; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left: left, right: right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; class ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.array) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.array, received: ctx.parsedType, }); return parseUtil_1.INVALID; } if (ctx.data.length < this._def.items.length) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array", }); return parseUtil_1.INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array", }); status.dirty(); } const items = [...ctx.data] .map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }) .filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return parseUtil_1.ParseStatus.mergeArray(status, results); }); } else { return parseUtil_1.ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest, }); } } exports.ZodTuple = ZodTuple; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params), }); }; class ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.object) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), }); } if (ctx.common.async) { return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); } else { return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third), }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second), }); } } exports.ZodRecord = ZodRecord; class ZodMap extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.map) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.map, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return parseUtil_1.INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return parseUtil_1.INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } exports.ZodMap = ZodMap; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; class ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.set) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.set, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message, }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message, }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements) { const parsedSet = new Set(); for (const element of elements) { if (element.status === "aborted") return parseUtil_1.INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements) => finalizeSet(elements)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } exports.ZodSet = ZodSet; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; class ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.function) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.function, received: ctx.parsedType, }); return parseUtil_1.INVALID; } function makeArgsIssue(args, error) { return (0, parseUtil_1.makeIssue)({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), errors_1.defaultErrorMap, ].filter((x) => !!x), issueData: { code: ZodError_1.ZodIssueCode.invalid_arguments, argumentsError: error, }, }); } function makeReturnsIssue(returns, error) { return (0, parseUtil_1.makeIssue)({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), errors_1.defaultErrorMap, ].filter((x) => !!x), issueData: { code: ZodError_1.ZodIssueCode.invalid_return_type, returnTypeError: error, }, }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { return (0, parseUtil_1.OK)(async (...args) => { const error = new ZodError_1.ZodError([]); const parsedArgs = await this._def.args .parseAsync(args, params) .catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await fn(...parsedArgs); const parsedReturns = await this._def.returns._def.type .parseAsync(result, params) .catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { return (0, parseUtil_1.OK)((...args) => { const parsedArgs = this._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = fn(...parsedArgs.data); const parsedReturns = this._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType, }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params), }); } } exports.ZodFunction = ZodFunction; class ZodLazy extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } exports.ZodLazy = ZodLazy; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter: getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; class ZodLiteral extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_literal, expected: this._def.value, }); return parseUtil_1.INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } exports.ZodLiteral = ZodLiteral; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value: value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; function createZodEnum(values, params) { return new ZodEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params), }); } class ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; (0, parseUtil_1.addIssueToContext)(ctx, { expected: util_1.util.joinValues(expectedValues), received: ctx.parsedType, code: ZodError_1.ZodIssueCode.invalid_type, }); return parseUtil_1.INVALID; } if (this._def.values.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_enum_value, options: expectedValues, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values) { return ZodEnum.create(values); } exclude(values) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); } } exports.ZodEnum = ZodEnum; ZodEnum.create = createZodEnum; class ZodNativeEnum extends ZodType { _parse(input) { const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== util_1.ZodParsedType.string && ctx.parsedType !== util_1.ZodParsedType.number) { const expectedValues = util_1.util.objectValues(nativeEnumValues); (0, parseUtil_1.addIssueToContext)(ctx, { expected: util_1.util.joinValues(expectedValues), received: ctx.parsedType, code: ZodError_1.ZodIssueCode.invalid_type, }); return parseUtil_1.INVALID; } if (nativeEnumValues.indexOf(input.data) === -1) { const expectedValues = util_1.util.objectValues(nativeEnumValues); (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_enum_value, options: expectedValues, }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } get enum() { return this._def.values; } } exports.ZodNativeEnum = ZodNativeEnum; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params), }); }; class ZodPromise extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.promise && ctx.common.async === false) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.promise, received: ctx.parsedType, }); return parseUtil_1.INVALID; } const promisified = ctx.parsedType === util_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return (0, parseUtil_1.OK)(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap, }); })); } } exports.ZodPromise = ZodPromise; ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params), }); }; class ZodEffects extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; if (effect.type === "preprocess") { const processed = effect.transform(ctx.data); if (ctx.common.async) { return Promise.resolve(processed).then((processed) => { return this._def.schema._parseAsync({ data: processed, path: ctx.path, parent: ctx, }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx, }); } } const checkCtx = { addIssue: (arg) => { (0, parseUtil_1.addIssueToContext)(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; }, }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inner.status === "aborted") return parseUtil_1.INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((inner) => { if (inner.status === "aborted") return parseUtil_1.INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (!(0, parseUtil_1.isValid)(base)) return base; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((base) => { if (!(0, parseUtil_1.isValid)(base)) return base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util_1.util.assertNever(effect); } } exports.ZodEffects = ZodEffects; exports.ZodTransformer = ZodEffects; ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params), }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params), }); }; class ZodOptional extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === util_1.ZodParsedType.undefined) { return (0, parseUtil_1.OK)(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } exports.ZodOptional = ZodOptional; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class ZodNullable extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === util_1.ZodParsedType.null) { return (0, parseUtil_1.OK)(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } exports.ZodNullable = ZodNullable; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params), }); }; class ZodDefault extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === util_1.ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx, }); } removeDefault() { return this._def.innerType; } } exports.ZodDefault = ZodDefault; ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params), }); }; class ZodCatch extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [], }, }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx, }, }); if ((0, parseUtil_1.isAsync)(result)) { return result.then((result) => { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError_1.ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError_1.ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; } } removeCatch() { return this._def.innerType; } } exports.ZodCatch = ZodCatch; ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params), }); }; class ZodNaN extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.nan, received: ctx.parsedType, }); return parseUtil_1.INVALID; } return { status: "valid", value: input.data }; } } exports.ZodNaN = ZodNaN; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; exports.BRAND = Symbol("zod_brand"); class ZodBranded extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx, }); } unwrap() { return this._def.type; } } exports.ZodBranded = ZodBranded; class ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return parseUtil_1.INVALID; if (inResult.status === "dirty") { status.dirty(); return (0, parseUtil_1.DIRTY)(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx, }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return parseUtil_1.INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value, }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx, }); } } } static create(a, b) { return new ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline, }); } } exports.ZodPipeline = ZodPipeline; const custom = (check, params = {}, fatal) => { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a, _b; if (!check(data)) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; const p2 = typeof p === "string" ? { message: p } : p; ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); } }); return ZodAny.create(); }; exports.custom = custom; exports.late = { object: ZodObject.lazycreate, }; var ZodFirstPartyTypeKind; (function (ZodFirstPartyTypeKind) { ZodFirstPartyTypeKind["ZodString"] = "ZodString"; ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); class Class { constructor(..._) { } } const instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}`, }) => (0, exports.custom)((data) => data instanceof cls, params); exports["instanceof"] = instanceOfType; const stringType = ZodString.create; exports.string = stringType; const numberType = ZodNumber.create; exports.number = numberType; const nanType = ZodNaN.create; exports.nan = nanType; const bigIntType = ZodBigInt.create; exports.bigint = bigIntType; const booleanType = ZodBoolean.create; exports.boolean = booleanType; const dateType = ZodDate.create; exports.date = dateType; const symbolType = ZodSymbol.create; exports.symbol = symbolType; const undefinedType = ZodUndefined.create; exports.undefined = undefinedType; const nullType = ZodNull.create; exports["null"] = nullType; const anyType = ZodAny.create; exports.any = anyType; const unknownType = ZodUnknown.create; exports.unknown = unknownType; const neverType = ZodNever.create; exports.never = neverType; const voidType = ZodVoid.create; exports["void"] = voidType; const arrayType = ZodArray.create; exports.array = arrayType; const objectType = ZodObject.create; exports.object = objectType; const strictObjectType = ZodObject.strictCreate; exports.strictObject = strictObjectType; const unionType = ZodUnion.create; exports.union = unionType; const discriminatedUnionType = ZodDiscriminatedUnion.create; exports.discriminatedUnion = discriminatedUnionType; const intersectionType = ZodIntersection.create; exports.intersection = intersectionType; const tupleType = ZodTuple.create; exports.tuple = tupleType; const recordType = ZodRecord.create; exports.record = recordType; const mapType = ZodMap.create; exports.map = mapType; const setType = ZodSet.create; exports.set = setType; const functionType = ZodFunction.create; exports["function"] = functionType; const lazyType = ZodLazy.create; exports.lazy = lazyType; const literalType = ZodLiteral.create; exports.literal = literalType; const enumType = ZodEnum.create; exports["enum"] = enumType; const nativeEnumType = ZodNativeEnum.create; exports.nativeEnum = nativeEnumType; const promiseType = ZodPromise.create; exports.promise = promiseType; const effectsType = ZodEffects.create; exports.effect = effectsType; exports.transformer = effectsType; const optionalType = ZodOptional.create; exports.optional = optionalType; const nullableType = ZodNullable.create; exports.nullable = nullableType; const preprocessType = ZodEffects.createWithPreprocess; exports.preprocess = preprocessType; const pipelineType = ZodPipeline.create; exports.pipeline = pipelineType; const ostring = () => stringType().optional(); exports.ostring = ostring; const onumber = () => numberType().optional(); exports.onumber = onumber; const oboolean = () => booleanType().optional(); exports.oboolean = oboolean; exports.coerce = { string: ((arg) => ZodString.create({ ...arg, coerce: true })), number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), boolean: ((arg) => ZodBoolean.create({ ...arg, coerce: true, })), bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), date: ((arg) => ZodDate.create({ ...arg, coerce: true })), }; exports.NEVER = parseUtil_1.INVALID; /***/ }), /***/ 9491: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); /***/ }), /***/ 4300: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); /***/ }), /***/ 6113: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); /***/ }), /***/ 2361: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); /***/ }), /***/ 7147: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); /***/ }), /***/ 3685: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); /***/ }), /***/ 5687: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); /***/ }), /***/ 1808: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); /***/ }), /***/ 7742: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process"); /***/ }), /***/ 2477: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream/web"); /***/ }), /***/ 2037: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); /***/ }), /***/ 1017: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); /***/ }), /***/ 4404: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); /***/ }), /***/ 3837: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); /***/ }), /***/ 1267: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); /***/ }), /***/ 8572: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nccwpck_require__) => { /* c8 ignore start */ // 64 KiB (same size chrome slice theirs blob into Uint8array's) const POOL_SIZE = 65536 if (!globalThis.ReadableStream) { // `node:stream/web` got introduced in v16.5.0 as experimental // and it's preferred over the polyfilled version. So we also // suppress the warning that gets emitted by NodeJS for using it. try { const process = __nccwpck_require__(7742) const { emitWarning } = process try { process.emitWarning = () => {} Object.assign(globalThis, __nccwpck_require__(2477)) process.emitWarning = emitWarning } catch (error) { process.emitWarning = emitWarning throw error } } catch (error) { // fallback to polyfill implementation Object.assign(globalThis, __nccwpck_require__(1452)) } } try { // Don't use node: prefix for this, require+node: is not supported until node v14.14 // Only `import()` can use prefix in 12.20 and later const { Blob } = __nccwpck_require__(4300) if (Blob && !Blob.prototype.stream) { Blob.prototype.stream = function name (params) { let position = 0 const blob = this return new ReadableStream({ type: 'bytes', async pull (ctrl) { const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)) const buffer = await chunk.arrayBuffer() position += buffer.byteLength ctrl.enqueue(new Uint8Array(buffer)) if (position === blob.size) { ctrl.close() } } }) } } } catch (error) {} /* c8 ignore end */ /***/ }), /***/ 3213: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* unused harmony export File */ /* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(1410); const _File = class File extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z { #lastModified = 0 #name = '' /** * @param {*[]} fileBits * @param {string} fileName * @param {{lastModified?: number, type?: string}} options */// @ts-ignore constructor (fileBits, fileName, options = {}) { if (arguments.length < 2) { throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`) } super(fileBits, options) if (options === null) options = {} // Simulate WebIDL type casting for NaN value in lastModified option. const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified) if (!Number.isNaN(lastModified)) { this.#lastModified = lastModified } this.#name = String(fileName) } get name () { return this.#name } get lastModified () { return this.#lastModified } get [Symbol.toStringTag] () { return 'File' } static [Symbol.hasInstance] (object) { return !!object && object instanceof _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z && /^(File)$/.test(object[Symbol.toStringTag]) } } /** @type {typeof globalThis.File} */// @ts-ignore const File = _File /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (File); /***/ }), /***/ 2777: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { "$B": () => (/* reexport */ file/* default */.Z) }); // UNUSED EXPORTS: Blob, blobFrom, blobFromSync, default, fileFrom, fileFromSync ;// CONCATENATED MODULE: external "node:fs" const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); ;// CONCATENATED MODULE: external "node:path" const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path"); // EXTERNAL MODULE: ./node_modules/node-domexception/index.js var node_domexception = __nccwpck_require__(7760); // EXTERNAL MODULE: ./node_modules/fetch-blob/file.js var file = __nccwpck_require__(3213); // EXTERNAL MODULE: ./node_modules/fetch-blob/index.js var fetch_blob = __nccwpck_require__(1410); ;// CONCATENATED MODULE: ./node_modules/fetch-blob/from.js const { stat } = external_node_fs_namespaceObject.promises /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use */ const blobFromSync = (path, type) => fromBlob(statSync(path), path, type) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use * @returns {Promise} */ const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type)) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use * @returns {Promise} */ const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type)) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use */ const fileFromSync = (path, type) => fromFile(statSync(path), path, type) // @ts-ignore const fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({ path, size: stat.size, lastModified: stat.mtimeMs, start: 0 })], { type }) // @ts-ignore const fromFile = (stat, path, type = '') => new File([new BlobDataItem({ path, size: stat.size, lastModified: stat.mtimeMs, start: 0 })], basename(path), { type, lastModified: stat.mtimeMs }) /** * This is a blob backed up by a file on the disk * with minium requirement. Its wrapped around a Blob as a blobPart * so you have no direct access to this. * * @private */ class BlobDataItem { #path #start constructor (options) { this.#path = options.path this.#start = options.start this.size = options.size this.lastModified = options.lastModified } /** * Slicing arguments is first validated and formatted * to not be out of range by Blob.prototype.slice */ slice (start, end) { return new BlobDataItem({ path: this.#path, lastModified: this.lastModified, size: end - start, start: this.#start + start }) } async * stream () { const { mtimeMs } = await stat(this.#path) if (mtimeMs > this.lastModified) { throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError') } yield * createReadStream(this.#path, { start: this.#start, end: this.#start + this.size - 1 }) } get [Symbol.toStringTag] () { return 'Blob' } } /* harmony default export */ const from = ((/* unused pure expression or super */ null && (blobFromSync))); /***/ }), /***/ 1410: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* unused harmony export Blob */ /* harmony import */ var _streams_cjs__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8572); /*! fetch-blob. MIT License. Jimmy Wärting */ // TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x) // Node has recently added whatwg stream into core // 64 KiB (same size chrome slice theirs blob into Uint8array's) const POOL_SIZE = 65536 /** @param {(Blob | Uint8Array)[]} parts */ async function * toIterator (parts, clone = true) { for (const part of parts) { if ('stream' in part) { yield * (/** @type {AsyncIterableIterator} */ (part.stream())) } else if (ArrayBuffer.isView(part)) { if (clone) { let position = part.byteOffset const end = part.byteOffset + part.byteLength while (position !== end) { const size = Math.min(end - position, POOL_SIZE) const chunk = part.buffer.slice(position, position + size) position += chunk.byteLength yield new Uint8Array(chunk) } } else { yield part } /* c8 ignore next 10 */ } else { // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob) let position = 0, b = (/** @type {Blob} */ (part)) while (position !== b.size) { const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)) const buffer = await chunk.arrayBuffer() position += buffer.byteLength yield new Uint8Array(buffer) } } } } const _Blob = class Blob { /** @type {Array.<(Blob|Uint8Array)>} */ #parts = [] #type = '' #size = 0 #endings = 'transparent' /** * The Blob() constructor returns a new Blob object. The content * of the blob consists of the concatenation of the values given * in the parameter array. * * @param {*} blobParts * @param {{ type?: string, endings?: string }} [options] */ constructor (blobParts = [], options = {}) { if (typeof blobParts !== 'object' || blobParts === null) { throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.') } if (typeof blobParts[Symbol.iterator] !== 'function') { throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.') } if (typeof options !== 'object' && typeof options !== 'function') { throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.') } if (options === null) options = {} const encoder = new TextEncoder() for (const element of blobParts) { let part if (ArrayBuffer.isView(element)) { part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)) } else if (element instanceof ArrayBuffer) { part = new Uint8Array(element.slice(0)) } else if (element instanceof Blob) { part = element } else { part = encoder.encode(`${element}`) } this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size this.#parts.push(part) } this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}` const type = options.type === undefined ? '' : String(options.type) this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '' } /** * The Blob interface's size property returns the * size of the Blob in bytes. */ get size () { return this.#size } /** * The type property of a Blob object returns the MIME type of the file. */ get type () { return this.#type } /** * The text() method in the Blob interface returns a Promise * that resolves with a string containing the contents of * the blob, interpreted as UTF-8. * * @return {Promise} */ async text () { // More optimized than using this.arrayBuffer() // that requires twice as much ram const decoder = new TextDecoder() let str = '' for await (const part of toIterator(this.#parts, false)) { str += decoder.decode(part, { stream: true }) } // Remaining str += decoder.decode() return str } /** * The arrayBuffer() method in the Blob interface returns a * Promise that resolves with the contents of the blob as * binary data contained in an ArrayBuffer. * * @return {Promise} */ async arrayBuffer () { // Easier way... Just a unnecessary overhead // const view = new Uint8Array(this.size); // await this.stream().getReader({mode: 'byob'}).read(view); // return view.buffer; const data = new Uint8Array(this.size) let offset = 0 for await (const chunk of toIterator(this.#parts, false)) { data.set(chunk, offset) offset += chunk.length } return data.buffer } stream () { const it = toIterator(this.#parts, true) return new globalThis.ReadableStream({ // @ts-ignore type: 'bytes', async pull (ctrl) { const chunk = await it.next() chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value) }, async cancel () { await it.return() } }) } /** * The Blob interface's slice() method creates and returns a * new Blob object which contains data from a subset of the * blob on which it's called. * * @param {number} [start] * @param {number} [end] * @param {string} [type] */ slice (start = 0, end = this.size, type = '') { const { size } = this let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size) let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size) const span = Math.max(relativeEnd - relativeStart, 0) const parts = this.#parts const blobParts = [] let added = 0 for (const part of parts) { // don't add the overflow to new blobParts if (added >= span) { break } const size = ArrayBuffer.isView(part) ? part.byteLength : part.size if (relativeStart && size <= relativeStart) { // Skip the beginning and change the relative // start & end position as we skip the unwanted parts relativeStart -= size relativeEnd -= size } else { let chunk if (ArrayBuffer.isView(part)) { chunk = part.subarray(relativeStart, Math.min(size, relativeEnd)) added += chunk.byteLength } else { chunk = part.slice(relativeStart, Math.min(size, relativeEnd)) added += chunk.size } relativeEnd -= size blobParts.push(chunk) relativeStart = 0 // All next sequential parts should start at 0 } } const blob = new Blob([], { type: String(type).toLowerCase() }) blob.#size = span blob.#parts = blobParts return blob } get [Symbol.toStringTag] () { return 'Blob' } static [Symbol.hasInstance] (object) { return ( object && typeof object === 'object' && typeof object.constructor === 'function' && ( typeof object.stream === 'function' || typeof object.arrayBuffer === 'function' ) && /^(Blob|File)$/.test(object[Symbol.toStringTag]) ) } } Object.defineProperties(_Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, slice: { enumerable: true } }) /** @type {typeof globalThis.Blob} */ const Blob = _Blob /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Blob); /***/ }), /***/ 8010: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ "Ct": () => (/* binding */ FormData), /* harmony export */ "au": () => (/* binding */ formDataToBlob) /* harmony export */ }); /* unused harmony export File */ /* harmony import */ var fetch_blob__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(1410); /* harmony import */ var fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(3213); /*! formdata-polyfill. MIT License. Jimmy Wärting */ var {toStringTag:t,iterator:i,hasInstance:h}=Symbol, r=Math.random, m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z([b],c,b):b]:[a,b+'']), e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} append(...a){x('append',arguments,2);this.#d.push(f(...a))} delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)} get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b} has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)} set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b} *entries(){yield*this.#d} *keys(){for(var[a]of this)yield a} *values(){for(var[,a]of this)yield a}} /** @param {FormData} F */ function formDataToBlob (F,B=fetch_blob__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z){ var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="` F.forEach((v,n)=>typeof v=='string' ?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? { /******/ // define getter functions for harmony exports /******/ __nccwpck_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/ensure chunk */ /******/ (() => { /******/ __nccwpck_require__.f = {}; /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __nccwpck_require__.e = (chunkId) => { /******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => { /******/ __nccwpck_require__.f[key](chunkId, promises); /******/ return promises; /******/ }, [])); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/get javascript chunk filename */ /******/ (() => { /******/ // This function allow to reference async chunks /******/ __nccwpck_require__.u = (chunkId) => { /******/ // return url for filenames based on template /******/ return "" + chunkId + ".index.js"; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __nccwpck_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; /******/ /******/ /* webpack/runtime/import chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 179: 0 /******/ }; /******/ /******/ var installChunk = (data) => { /******/ var {ids, modules, runtime} = data; /******/ // add "modules" to the modules object, /******/ // then flag all "ids" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ for(moduleId in modules) { /******/ if(__nccwpck_require__.o(modules, moduleId)) { /******/ __nccwpck_require__.m[moduleId] = modules[moduleId]; /******/ } /******/ } /******/ if(runtime) runtime(__nccwpck_require__); /******/ for(;i < ids.length; i++) { /******/ chunkId = ids[i]; /******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[ids[i]] = 0; /******/ } /******/ /******/ } /******/ /******/ __nccwpck_require__.f.j = (chunkId, promises) => { /******/ // import() chunk loading for javascript /******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[1]); /******/ } else { /******/ if(true) { // all chunks have JS /******/ // setup Promise in chunk cache /******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => { /******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined; /******/ throw e; /******/ }); /******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))]) /******/ promises.push(installedChunkData[1] = promise); /******/ } else installedChunks[chunkId] = 0; /******/ } /******/ } /******/ }; /******/ /******/ // no external install chunk /******/ /******/ // no on chunks loaded /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js var core = __nccwpck_require__(2186); ;// CONCATENATED MODULE: ./node_modules/zod/lib/index.mjs var util; (function (util) { util.assertEqual = (val) => val; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil || (objectUtil = {})); const ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; const ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite", ]); const quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { // eslint-disable-next-line ban/ban Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; // if (typeof el === "string") { // curr[el] = curr[el] || { _errors: [] }; // } else if (typeof el === "number") { // const errorArray: any = []; // errorArray._errors = []; // curr[el] = curr[el] || errorArray; // } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; let overrideErrorMap = errorMap; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; let errorMessage = ""; const maps = errorMaps .filter((m) => !!m) .slice() .reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage, }; }; const EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const issue = makeIssue({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); } class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { syncPairs.push({ key: await pair.key, value: await pair.value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (typeof value.value !== "undefined" || pair.alwaysSet) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } const INVALID = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); const OK = (value) => ({ status: "valid", value }); const isAborted = (x) => x.status === "aborted"; const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } } const handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; }, }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap) return { errorMap: errorMap, description }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined") { return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; } return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; }; return { errorMap: customMap, description }; } class ZodType { constructor(def) { /** Alias of safeParseAsync */ this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return (ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }); } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }, }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val), }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement }, }); } superRefine(refinement) { return this._refinement(refinement); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform }, }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault, }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def), }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch, }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description, }); } pipe(target) { return ZodPipeline.create(this, target); } isOptional() { return this.safeParse(undefined).success; } isNullable() { return this.safeParse(null).success; } } const cuidRegex = /^c[^\s-]{8,}$/i; const cuid2Regex = /^[a-z][a-z0-9]*$/; const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; // from https://stackoverflow.com/a/46181/1550155 // old version: too slow, didn't support unicode // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; //old email regex // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; // eslint-disable-next-line const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; // Adapted from https://stackoverflow.com/a/3143231 const datetimeRegex = (args) => { if (args.precision) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } } else if (args.precision === 0) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); } } else { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); } } }; function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } class ZodString extends ZodType { constructor() { super(...arguments); this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message), }); /** * @deprecated Use z.string().min(1) instead. * @see {@link ZodString.min} */ this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)); this.trim = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }], }); this.toLowerCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }], }); this.toUpperCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }], }); } _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx.parsedType, } // ); return INVALID; } const status = new ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message, }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message, }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check], }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } datetime(options) { var _a; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, message: options, }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex: regex, ...errorUtil.errToObj(message), }); } includes(value, options) { return this._addCheck({ kind: "includes", value: value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value: value, ...errorUtil.errToObj(message), }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value: value, ...errorUtil.errToObj(message), }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message), }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message), }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message), }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodString.create = (params) => { var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params), }); }; // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / Math.pow(10, decCount); } class ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx.parsedType, }); return INVALID; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message, }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check], }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message), }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value: value, message: errorUtil.toString(message), }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message), }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message), })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } } ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; class ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType, }); return INVALID; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check], }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodBigInt.create = (params) => { var _a; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params), }); }; class ZodBoolean extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; class ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx.parsedType, }); return INVALID; } if (isNaN(input.data.getTime())) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_date, }); return INVALID; } const status = new ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date", }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date", }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()), }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check], }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message), }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message), }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } } ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params), }); }; class ZodSymbol extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params), }); }; class ZodUndefined extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; class ZodNull extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params), }); }; class ZodAny extends ZodType { constructor() { super(...arguments); // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. this._any = true; } _parse(input) { return OK(input.data); } } ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params), }); }; class ZodUnknown extends ZodType { constructor() { super(...arguments); // required this._unknown = true; } _parse(input) { return OK(input.data); } } ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params), }); }; class ZodNever extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType, }); return INVALID; } } ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params), }); }; class ZodVoid extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; class ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: (tooSmall ? def.exactLength.value : undefined), maximum: (tooBig ? def.exactLength.value : undefined), type: "array", inclusive: true, exact: true, message: def.exactLength.message, }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message, }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message, }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result) => { return ParseStatus.mergeArray(status, result); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) }, }); } nonempty(message) { return this.min(1, message); } } ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape, }); } else if (schema instanceof ZodArray) { return new ZodArray({ ...schema._def, type: deepPartialify(schema.element), }); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } class ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; /** * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. * If you want to pass through unknown properties, use `.passthrough()` instead. */ this.nonstrict = this.passthrough; // extend< // Augmentation extends ZodRawShape, // NewOutput extends util.flatten<{ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }>, // NewInput extends util.flatten<{ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // }> // >( // augmentation: Augmentation // ): ZodObject< // extendShape, // UnknownKeys, // Catchall, // NewOutput, // NewInput // > { // return new ZodObject({ // ...this._def, // shape: () => ({ // ...this._def.shape(), // ...augmentation, // }), // }) as any; // } /** * @deprecated Use `.extend` instead * */ this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); return (this._cached = { shape, keys }); } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] }, }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys, }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { // run catchall validation const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data, }); } } if (ctx.common.async) { return Promise.resolve() .then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet, }); } return syncPairs; }) .then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...(message !== undefined ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, }; return { message: defaultError, }; }, } : {}), }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip", }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough", }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation, }), }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape(), }), typeName: ZodFirstPartyTypeKind.ZodObject, }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new ZodObject({ ...this._def, catchall: index, }); } pick(mask) { const shape = {}; util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } required(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } } ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; class ZodUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { // return first issue-free validation if it exists for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { // add issues from dirty option ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } // return invalid const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx, }), ctx: childCtx, }; })).then(handleResults); } else { let dirty = undefined; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx, }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues) => new ZodError(issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } } get options() { return this._def.options; } } ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ////////// ////////// ////////// ZodDiscriminatedUnion ////////// ////////// ////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// const getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { // eslint-disable-next-line ban/ban return Object.keys(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [undefined]; } else if (type instanceof ZodNull) { return [null]; } else { return null; } }; class ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator], }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { // Get all the valid discriminator values const optionsMap = new Map(); // try { for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params), }); } } function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util .objectKeys(a) .filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } class ZodIntersection extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types, }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, })); } } } ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left: left, right: right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; class ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array", }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array", }); status.dirty(); } const items = [...ctx.data] .map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }) .filter((x) => !!x); // filter nulls if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest, }); } } ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params), }); }; class ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third), }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second), }); } } class ZodMap extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType, }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; class ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType, }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message, }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message, }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements) { const parsedSet = new Set(); for (const element of elements) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements) => finalizeSet(elements)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) }, }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; class ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType, }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error, }, }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error, }, }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { return OK(async (...args) => { const error = new ZodError([]); const parsedArgs = await this._def.args .parseAsync(args, params) .catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await fn(...parsedArgs); const parsedReturns = await this._def.returns._def.type .parseAsync(result, params) .catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { return OK((...args) => { const parsedArgs = this._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = fn(...parsedArgs.data); const parsedReturns = this._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType, }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params), }); } } class ZodLazy extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } ZodLazy.create = (getter, params) => { return new ZodLazy({ getter: getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; class ZodLiteral extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value, }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } ZodLiteral.create = (value, params) => { return new ZodLiteral({ value: value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; function createZodEnum(values, params) { return new ZodEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params), }); } class ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (this._def.values.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values) { return ZodEnum.create(values); } exclude(values) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); } } ZodEnum.create = createZodEnum; class ZodNativeEnum extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (nativeEnumValues.indexOf(input.data) === -1) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } } ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params), }); }; class ZodPromise extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType, }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap, }); })); } } ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params), }); }; class ZodEffects extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; if (effect.type === "preprocess") { const processed = effect.transform(ctx.data); if (ctx.common.async) { return Promise.resolve(processed).then((processed) => { return this._def.schema._parseAsync({ data: processed, path: ctx.path, parent: ctx, }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx, }); } } const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; }, }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "refinement") { const executeRefinement = (acc // effect: RefinementEffect ) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); // return value is ignored executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (!isValid(base)) return base; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((base) => { if (!isValid(base)) return base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } } ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params), }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params), }); }; class ZodOptional extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class ZodNullable extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params), }); }; class ZodDefault extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx, }); } removeDefault() { return this._def.innerType; } } ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params), }); }; class ZodCatch extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); // newCtx is used to not collect issues from inner types in ctx const newCtx = { ...ctx, common: { ...ctx.common, issues: [], }, }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx, }, }); if (isAsync(result)) { return result.then((result) => { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; } } removeCatch() { return this._def.innerType; } } ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params), }); }; class ZodNaN extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType, }); return INVALID; } return { status: "valid", value: input.data }; } } ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; const BRAND = Symbol("zod_brand"); class ZodBranded extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx, }); } unwrap() { return this._def.type; } } class ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx, }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value, }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx, }); } } } static create(a, b) { return new ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline, }); } } const custom = (check, params = {}, /* * @deprecated * * Pass `fatal` into the params object instead: * * ```ts * z.string().custom((val) => val.length > 5, { fatal: false }) * ``` * */ fatal) => { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a, _b; if (!check(data)) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; const p2 = typeof p === "string" ? { message: p } : p; ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); } }); return ZodAny.create(); }; const late = { object: ZodObject.lazycreate, }; var ZodFirstPartyTypeKind; (function (ZodFirstPartyTypeKind) { ZodFirstPartyTypeKind["ZodString"] = "ZodString"; ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); const instanceOfType = ( // const instanceOfType = any>( cls, params = { message: `Input not instance of ${cls.name}`, }) => custom((data) => data instanceof cls, params); const stringType = ZodString.create; const numberType = ZodNumber.create; const nanType = ZodNaN.create; const bigIntType = ZodBigInt.create; const booleanType = ZodBoolean.create; const dateType = ZodDate.create; const symbolType = ZodSymbol.create; const undefinedType = ZodUndefined.create; const nullType = ZodNull.create; const anyType = ZodAny.create; const unknownType = ZodUnknown.create; const neverType = ZodNever.create; const voidType = ZodVoid.create; const arrayType = ZodArray.create; const objectType = ZodObject.create; const strictObjectType = ZodObject.strictCreate; const unionType = ZodUnion.create; const discriminatedUnionType = ZodDiscriminatedUnion.create; const intersectionType = ZodIntersection.create; const tupleType = ZodTuple.create; const recordType = ZodRecord.create; const mapType = ZodMap.create; const setType = ZodSet.create; const functionType = ZodFunction.create; const lazyType = ZodLazy.create; const literalType = ZodLiteral.create; const enumType = ZodEnum.create; const nativeEnumType = ZodNativeEnum.create; const promiseType = ZodPromise.create; const effectsType = ZodEffects.create; const optionalType = ZodOptional.create; const nullableType = ZodNullable.create; const preprocessType = ZodEffects.createWithPreprocess; const pipelineType = ZodPipeline.create; const ostring = () => stringType().optional(); const onumber = () => numberType().optional(); const oboolean = () => booleanType().optional(); const coerce = { string: ((arg) => ZodString.create({ ...arg, coerce: true })), number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), boolean: ((arg) => ZodBoolean.create({ ...arg, coerce: true, })), bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), date: ((arg) => ZodDate.create({ ...arg, coerce: true })), }; const NEVER = INVALID; var z = /*#__PURE__*/Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap: setErrorMap, getErrorMap: getErrorMap, makeIssue: makeIssue, EMPTY_PATH: EMPTY_PATH, addIssueToContext: addIssueToContext, ParseStatus: ParseStatus, INVALID: INVALID, DIRTY: DIRTY, OK: OK, isAborted: isAborted, isDirty: isDirty, isValid: isValid, isAsync: isAsync, get util () { return util; }, get objectUtil () { return objectUtil; }, ZodParsedType: ZodParsedType, getParsedType: getParsedType, ZodType: ZodType, ZodString: ZodString, ZodNumber: ZodNumber, ZodBigInt: ZodBigInt, ZodBoolean: ZodBoolean, ZodDate: ZodDate, ZodSymbol: ZodSymbol, ZodUndefined: ZodUndefined, ZodNull: ZodNull, ZodAny: ZodAny, ZodUnknown: ZodUnknown, ZodNever: ZodNever, ZodVoid: ZodVoid, ZodArray: ZodArray, ZodObject: ZodObject, ZodUnion: ZodUnion, ZodDiscriminatedUnion: ZodDiscriminatedUnion, ZodIntersection: ZodIntersection, ZodTuple: ZodTuple, ZodRecord: ZodRecord, ZodMap: ZodMap, ZodSet: ZodSet, ZodFunction: ZodFunction, ZodLazy: ZodLazy, ZodLiteral: ZodLiteral, ZodEnum: ZodEnum, ZodNativeEnum: ZodNativeEnum, ZodPromise: ZodPromise, ZodEffects: ZodEffects, ZodTransformer: ZodEffects, ZodOptional: ZodOptional, ZodNullable: ZodNullable, ZodDefault: ZodDefault, ZodCatch: ZodCatch, ZodNaN: ZodNaN, BRAND: BRAND, ZodBranded: ZodBranded, ZodPipeline: ZodPipeline, custom: custom, Schema: ZodType, ZodSchema: ZodType, late: late, get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, coerce: coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, 'enum': enumType, 'function': functionType, 'instanceof': instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, 'null': nullType, nullable: nullableType, number: numberType, object: objectType, oboolean: oboolean, onumber: onumber, optional: optionalType, ostring: ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, 'undefined': undefinedType, union: unionType, unknown: unknownType, 'void': voidType, NEVER: NEVER, ZodIssueCode: ZodIssueCode, quotelessJson: quotelessJson, ZodError: ZodError }); ;// CONCATENATED MODULE: ./src/schema/specklefunction.ts const SpeckleFunctionKind = 'SpeckleFunction'; const SpeckleFunctionApiVersionV1Alpha1 = 'speckle.systems/v1alpha1'; const SpeckleFunctionAnnotationsSchema = z.object({ 'speckle.systems/v1alpha1/publishing/status': z["enum"](['publish', 'draft', 'archive']) .default('draft'), 'speckle.systems/v1alpha1/author': z.string().optional(), 'speckle.systems/v1alpha1/license': z["enum"](['MIT', 'BSD', 'Apache-2.0', 'MPL', 'CC0', 'Unlicense']) .optional(), 'speckle.systems/v1alpha1/website': z.string().url().optional(), 'speckle.systems/v1alpha1/documentation': z.string().url().optional(), 'speckle.systems/v1alpha1/keywords': z.string().optional(), 'speckle.systems/v1alpha1/description': z.string().optional() }) .optional(); const SpeckleFunctionSchema = z.object({ kind: z.literal(SpeckleFunctionKind), apiVersion: z["enum"]([SpeckleFunctionApiVersionV1Alpha1]), metadata: z.object({ name: z.string().nonempty(), annotations: SpeckleFunctionAnnotationsSchema }), spec: z.object({ inputs: z.array(z.object({ //TODO })) .optional(), results: z.array(z.object({ //TODO })) .optional(), requirements: z.object({ os: z["enum"](['windows', 'linux']).default('linux'), architecture: z["enum"](['amd64']).default('amd64'), infrastructure: z.array(z["enum"](['gpu'])).optional() }) .optional() }) }); ;// CONCATENATED MODULE: ./src/schema/inputs.ts const SpeckleServerUrlSchema = z.string().url().nonempty(); const SpeckleTokenSchema = z.string().nonempty(); const SpeckleFunctionRepositorySchema = z.string().nonempty(); //TODO validate this as a git+https, https, or ssh url const SpeckleFunctionPathSchema = z.string() .nonempty() .refine((value) => !value.startsWith('/'), { message: 'Must not be an absolute path.' }); const SpeckleFunctionIdSchema = z.string().nonempty(); const VersionTagSchema = z.string().nonempty(); const CommitIdSchema = z.string().nonempty(); const SpeckleFunctionInputSchema = z.record(z.string(), z.unknown()); ;// CONCATENATED MODULE: ./src/client/schema.ts const FunctionVersionRequestSchema = z.object({ commitId: CommitIdSchema, versionTag: VersionTagSchema, inputSchema: z.record(z.string(), z.unknown()), command: z.array(z.string().nonempty()), annotations: SpeckleFunctionAnnotationsSchema }); const SpeckleFunctionPostResponseBodySchema = z.object({ versionId: z.string().nonempty() }); ;// CONCATENATED MODULE: external "url" const external_url_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); // EXTERNAL MODULE: ./node_modules/zod-validation-error/dist/cjs/index.js var cjs = __nccwpck_require__(8780); ;// CONCATENATED MODULE: ./src/schema/errors.ts function handleZodError(err, logger) { if (err instanceof ZodError) { const validationError = (0,cjs/* fromZodError */.CC)(err); logger.error(validationError); throw validationError; } throw err; } ;// CONCATENATED MODULE: external "node:http" const external_node_http_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http"); ;// CONCATENATED MODULE: external "node:https" const external_node_https_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https"); ;// CONCATENATED MODULE: external "node:zlib" const external_node_zlib_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib"); ;// CONCATENATED MODULE: external "node:stream" const external_node_stream_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); ;// CONCATENATED MODULE: external "node:buffer" const external_node_buffer_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer"); ;// CONCATENATED MODULE: ./node_modules/data-uri-to-buffer/dist/index.js /** * Returns a `Buffer` instance from the given data URI `uri`. * * @param {String} uri Data URI to turn into a Buffer instance * @returns {Buffer} Buffer instance from Data URI * @api public */ function dataUriToBuffer(uri) { if (!/^data:/i.test(uri)) { throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } // strip newlines uri = uri.replace(/\r?\n/g, ''); // split the URI up into the "metadata" and the "data" portions const firstComma = uri.indexOf(','); if (firstComma === -1 || firstComma <= 4) { throw new TypeError('malformed data: URI'); } // remove the "data:" scheme and parse the metadata const meta = uri.substring(5, firstComma).split(';'); let charset = ''; let base64 = false; const type = meta[0] || 'text/plain'; let typeFull = type; for (let i = 1; i < meta.length; i++) { if (meta[i] === 'base64') { base64 = true; } else if (meta[i]) { typeFull += `;${meta[i]}`; if (meta[i].indexOf('charset=') === 0) { charset = meta[i].substring(8); } } } // defaults to US-ASCII only if type is not provided if (!meta[0] && !charset.length) { typeFull += ';charset=US-ASCII'; charset = 'US-ASCII'; } // get the encoded data portion and decode URI-encoded chars const encoding = base64 ? 'base64' : 'ascii'; const data = unescape(uri.substring(firstComma + 1)); const buffer = Buffer.from(data, encoding); // set `.type` and `.typeFull` properties to MIME type buffer.type = type; buffer.typeFull = typeFull; // set the `.charset` property buffer.charset = charset; return buffer; } /* harmony default export */ const dist = (dataUriToBuffer); //# sourceMappingURL=index.js.map ;// CONCATENATED MODULE: external "node:util" const external_node_util_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); // EXTERNAL MODULE: ./node_modules/fetch-blob/index.js var fetch_blob = __nccwpck_require__(1410); // EXTERNAL MODULE: ./node_modules/formdata-polyfill/esm.min.js var esm_min = __nccwpck_require__(8010); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/base.js class FetchBaseError extends Error { constructor(message, type) { super(message); // Hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); this.type = type; } get name() { return this.constructor.name; } get [Symbol.toStringTag]() { return this.constructor.name; } } ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/fetch-error.js /** * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError */ /** * FetchError interface for operational errors */ class FetchError extends FetchBaseError { /** * @param {string} message - Error message for human * @param {string} [type] - Error type for machine * @param {SystemError} [systemError] - For Node.js system error */ constructor(message, type, systemError) { super(message, type); // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code if (systemError) { // eslint-disable-next-line no-multi-assign this.code = this.errno = systemError.code; this.erroredSysCall = systemError.syscall; } } } ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/is.js /** * Is.js * * Object type checks. */ const NAME = Symbol.toStringTag; /** * Check if `obj` is a URLSearchParams object * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143 * @param {*} object - Object to check for * @return {boolean} */ const isURLSearchParameters = object => { return ( 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' && typeof object.sort === 'function' && object[NAME] === 'URLSearchParams' ); }; /** * Check if `object` is a W3C `Blob` object (which `File` inherits from) * @param {*} object - Object to check for * @return {boolean} */ const isBlob = object => { return ( object && typeof object === 'object' && typeof object.arrayBuffer === 'function' && typeof object.type === 'string' && typeof object.stream === 'function' && typeof object.constructor === 'function' && /^(Blob|File)$/.test(object[NAME]) ); }; /** * Check if `obj` is an instance of AbortSignal. * @param {*} object - Object to check for * @return {boolean} */ const isAbortSignal = object => { return ( typeof object === 'object' && ( object[NAME] === 'AbortSignal' || object[NAME] === 'EventTarget' ) ); }; /** * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of * the parent domain. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isDomainOrSubdomain = (destination, original) => { const orig = new URL(original).hostname; const dest = new URL(destination).hostname; return orig === dest || orig.endsWith(`.${dest}`); }; /** * isSameProtocol reports whether the two provided URLs use the same protocol. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isSameProtocol = (destination, original) => { const orig = new URL(original).protocol; const dest = new URL(destination).protocol; return orig === dest; }; ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/body.js /** * Body.js * * Body interface provides common methods for Request and Response */ const pipeline = (0,external_node_util_namespaceObject.promisify)(external_node_stream_namespaceObject.pipeline); const INTERNALS = Symbol('Body internals'); /** * Body mixin * * Ref: https://fetch.spec.whatwg.org/#body * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Body { constructor(body, { size = 0 } = {}) { let boundary = null; if (body === null) { // Body is undefined or null body = null; } else if (isURLSearchParameters(body)) { // Body is a URLSearchParams body = external_node_buffer_namespaceObject.Buffer.from(body.toString()); } else if (isBlob(body)) { // Body is blob } else if (external_node_buffer_namespaceObject.Buffer.isBuffer(body)) { // Body is Buffer } else if (external_node_util_namespaceObject.types.isAnyArrayBuffer(body)) { // Body is ArrayBuffer body = external_node_buffer_namespaceObject.Buffer.from(body); } else if (ArrayBuffer.isView(body)) { // Body is ArrayBufferView body = external_node_buffer_namespaceObject.Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof external_node_stream_namespaceObject) { // Body is stream } else if (body instanceof esm_min/* FormData */.Ct) { // Body is FormData body = (0,esm_min/* formDataToBlob */.au)(body); boundary = body.type.split('=')[1]; } else { // None of the above // coerce to string then buffer body = external_node_buffer_namespaceObject.Buffer.from(String(body)); } let stream = body; if (external_node_buffer_namespaceObject.Buffer.isBuffer(body)) { stream = external_node_stream_namespaceObject.Readable.from(body); } else if (isBlob(body)) { stream = external_node_stream_namespaceObject.Readable.from(body.stream()); } this[INTERNALS] = { body, stream, boundary, disturbed: false, error: null }; this.size = size; if (body instanceof external_node_stream_namespaceObject) { body.on('error', error_ => { const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); this[INTERNALS].error = error; }); } } get body() { return this[INTERNALS].stream; } get bodyUsed() { return this[INTERNALS].disturbed; } /** * Decode response as ArrayBuffer * * @return Promise */ async arrayBuffer() { const {buffer, byteOffset, byteLength} = await consumeBody(this); return buffer.slice(byteOffset, byteOffset + byteLength); } async formData() { const ct = this.headers.get('content-type'); if (ct.startsWith('application/x-www-form-urlencoded')) { const formData = new esm_min/* FormData */.Ct(); const parameters = new URLSearchParams(await this.text()); for (const [name, value] of parameters) { formData.append(name, value); } return formData; } const {toFormData} = await __nccwpck_require__.e(/* import() */ 37).then(__nccwpck_require__.bind(__nccwpck_require__, 4037)); return toFormData(this.body, ct); } /** * Return raw response as Blob * * @return Promise */ async blob() { const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || ''; const buf = await this.arrayBuffer(); return new fetch_blob/* default */.Z([buf], { type: ct }); } /** * Decode response as json * * @return Promise */ async json() { const text = await this.text(); return JSON.parse(text); } /** * Decode response as text * * @return Promise */ async text() { const buffer = await consumeBody(this); return new TextDecoder().decode(buffer); } /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody(this); } } Body.prototype.buffer = (0,external_node_util_namespaceObject.deprecate)(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); // In browsers, all properties are enumerable. Object.defineProperties(Body.prototype, { body: {enumerable: true}, bodyUsed: {enumerable: true}, arrayBuffer: {enumerable: true}, blob: {enumerable: true}, json: {enumerable: true}, text: {enumerable: true}, data: {get: (0,external_node_util_namespaceObject.deprecate)(() => {}, 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead', 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')} }); /** * Consume and convert an entire Body to a Buffer. * * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body * * @return Promise */ async function consumeBody(data) { if (data[INTERNALS].disturbed) { throw new TypeError(`body used already for: ${data.url}`); } data[INTERNALS].disturbed = true; if (data[INTERNALS].error) { throw data[INTERNALS].error; } const {body} = data; // Body is null if (body === null) { return external_node_buffer_namespaceObject.Buffer.alloc(0); } /* c8 ignore next 3 */ if (!(body instanceof external_node_stream_namespaceObject)) { return external_node_buffer_namespaceObject.Buffer.alloc(0); } // Body is stream // get ready to actually consume the body const accum = []; let accumBytes = 0; try { for await (const chunk of body) { if (data.size > 0 && accumBytes + chunk.length > data.size) { const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size'); body.destroy(error); throw error; } accumBytes += chunk.length; accum.push(chunk); } } catch (error) { const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error); throw error_; } if (body.readableEnded === true || body._readableState.ended === true) { try { if (accum.every(c => typeof c === 'string')) { return external_node_buffer_namespaceObject.Buffer.from(accum.join('')); } return external_node_buffer_namespaceObject.Buffer.concat(accum, accumBytes); } catch (error) { throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); } } else { throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); } } /** * Clone body given Res/Req instance * * @param Mixed instance Response or Request instance * @param String highWaterMark highWaterMark for both PassThrough body streams * @return Mixed */ const clone = (instance, highWaterMark) => { let p1; let p2; let {body} = instance[INTERNALS]; // Don't allow cloning a used body if (instance.bodyUsed) { throw new Error('cannot clone body after it is used'); } // Check that body is a stream and not form-data object // note: we can't clone the form-data object without having it as a dependency if ((body instanceof external_node_stream_namespaceObject) && (typeof body.getBoundary !== 'function')) { // Tee instance body p1 = new external_node_stream_namespaceObject.PassThrough({highWaterMark}); p2 = new external_node_stream_namespaceObject.PassThrough({highWaterMark}); body.pipe(p1); body.pipe(p2); // Set instance body to teed body and return the other teed body instance[INTERNALS].stream = p1; body = p2; } return body; }; const getNonSpecFormDataBoundary = (0,external_node_util_namespaceObject.deprecate)( body => body.getBoundary(), 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package', 'https://github.com/node-fetch/node-fetch/issues/1167' ); /** * Performs the operation "extract a `Content-Type` value from |object|" as * specified in the specification: * https://fetch.spec.whatwg.org/#concept-bodyinit-extract * * This function assumes that instance.body is present. * * @param {any} body Any options.body input * @returns {string | null} */ const extractContentType = (body, request) => { // Body is null or undefined if (body === null) { return null; } // Body is string if (typeof body === 'string') { return 'text/plain;charset=UTF-8'; } // Body is a URLSearchParams if (isURLSearchParameters(body)) { return 'application/x-www-form-urlencoded;charset=UTF-8'; } // Body is blob if (isBlob(body)) { return body.type || null; } // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView) if (external_node_buffer_namespaceObject.Buffer.isBuffer(body) || external_node_util_namespaceObject.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { return null; } if (body instanceof esm_min/* FormData */.Ct) { return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; } // Detect form data input from form-data module if (body && typeof body.getBoundary === 'function') { return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; } // Body is stream - can't really do much about this if (body instanceof external_node_stream_namespaceObject) { return null; } // Body constructor defaults other things to string return 'text/plain;charset=UTF-8'; }; /** * The Fetch Standard treats this as if "total bytes" is a property on the body. * For us, we have to explicitly get it with a function. * * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes * * @param {any} obj.body Body object from the Body instance. * @returns {number | null} */ const getTotalBytes = request => { const {body} = request[INTERNALS]; // Body is null or undefined if (body === null) { return 0; } // Body is Blob if (isBlob(body)) { return body.size; } // Body is Buffer if (external_node_buffer_namespaceObject.Buffer.isBuffer(body)) { return body.length; } // Detect form data input from form-data module if (body && typeof body.getLengthSync === 'function') { return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; } // Body is stream return null; }; /** * Write a Body to a Node.js WritableStream (e.g. http.Request) object. * * @param {Stream.Writable} dest The stream to write to. * @param obj.body Body object from the Body instance. * @returns {Promise} */ const writeToStream = async (dest, {body}) => { if (body === null) { // Body is null dest.end(); } else { // Body is stream await pipeline(body, dest); } }; ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/headers.js /** * Headers.js * * Headers class offers convenient helpers */ /* c8 ignore next 9 */ const validateHeaderName = typeof external_node_http_namespaceObject.validateHeaderName === 'function' ? external_node_http_namespaceObject.validateHeaderName : name => { if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'}); throw error; } }; /* c8 ignore next 9 */ const validateHeaderValue = typeof external_node_http_namespaceObject.validateHeaderValue === 'function' ? external_node_http_namespaceObject.validateHeaderValue : (name, value) => { if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { const error = new TypeError(`Invalid character in header content ["${name}"]`); Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'}); throw error; } }; /** * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit */ /** * This Fetch API interface allows you to perform various actions on HTTP request and response headers. * These actions include retrieving, setting, adding to, and removing. * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. * You can add to this using methods like append() (see Examples.) * In all methods of this interface, header names are matched by case-insensitive byte sequence. * */ class Headers extends URLSearchParams { /** * Headers class * * @constructor * @param {HeadersInit} [init] - Response headers */ constructor(init) { // Validate and normalize init object in [name, value(s)][] /** @type {string[][]} */ let result = []; if (init instanceof Headers) { const raw = init.raw(); for (const [name, values] of Object.entries(raw)) { result.push(...values.map(value => [name, value])); } } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq // No op } else if (typeof init === 'object' && !external_node_util_namespaceObject.types.isBoxedPrimitive(init)) { const method = init[Symbol.iterator]; // eslint-disable-next-line no-eq-null, eqeqeq if (method == null) { // Record result.push(...Object.entries(init)); } else { if (typeof method !== 'function') { throw new TypeError('Header pairs must be iterable'); } // Sequence> // Note: per spec we have to first exhaust the lists then process them result = [...init] .map(pair => { if ( typeof pair !== 'object' || external_node_util_namespaceObject.types.isBoxedPrimitive(pair) ) { throw new TypeError('Each header pair must be an iterable object'); } return [...pair]; }).map(pair => { if (pair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple'); } return [...pair]; }); } } else { throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)'); } // Validate and lowercase result = result.length > 0 ? result.map(([name, value]) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return [String(name).toLowerCase(), String(value)]; }) : undefined; super(result); // Returning a Proxy that will lowercase key names, validate parameters and sort keys // eslint-disable-next-line no-constructor-return return new Proxy(this, { get(target, p, receiver) { switch (p) { case 'append': case 'set': return (name, value) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return URLSearchParams.prototype[p].call( target, String(name).toLowerCase(), String(value) ); }; case 'delete': case 'has': case 'getAll': return name => { validateHeaderName(name); return URLSearchParams.prototype[p].call( target, String(name).toLowerCase() ); }; case 'keys': return () => { target.sort(); return new Set(URLSearchParams.prototype.keys.call(target)).keys(); }; default: return Reflect.get(target, p, receiver); } } }); /* c8 ignore next */ } get [Symbol.toStringTag]() { return this.constructor.name; } toString() { return Object.prototype.toString.call(this); } get(name) { const values = this.getAll(name); if (values.length === 0) { return null; } let value = values.join(', '); if (/^content-encoding$/i.test(name)) { value = value.toLowerCase(); } return value; } forEach(callback, thisArg = undefined) { for (const name of this.keys()) { Reflect.apply(callback, thisArg, [this.get(name), name, this]); } } * values() { for (const name of this.keys()) { yield this.get(name); } } /** * @type {() => IterableIterator<[string, string]>} */ * entries() { for (const name of this.keys()) { yield [name, this.get(name)]; } } [Symbol.iterator]() { return this.entries(); } /** * Node-fetch non-spec method * returning all headers and their values as array * @returns {Record} */ raw() { return [...this.keys()].reduce((result, key) => { result[key] = this.getAll(key); return result; }, {}); } /** * For better console.log(headers) and also to convert Headers into Node.js Request compatible format */ [Symbol.for('nodejs.util.inspect.custom')]() { return [...this.keys()].reduce((result, key) => { const values = this.getAll(key); // Http.request() only supports string as Host header. // This hack makes specifying custom Host header possible. if (key === 'host') { result[key] = values[0]; } else { result[key] = values.length > 1 ? values : values[0]; } return result; }, {}); } } /** * Re-shaping object for Web IDL tests * Only need to do it for overridden methods */ Object.defineProperties( Headers.prototype, ['get', 'entries', 'forEach', 'values'].reduce((result, property) => { result[property] = {enumerable: true}; return result; }, {}) ); /** * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do * not conform to HTTP grammar productions. * @param {import('http').IncomingMessage['rawHeaders']} headers */ function fromRawHeaders(headers = []) { return new Headers( headers // Split into pairs .reduce((result, value, index, array) => { if (index % 2 === 0) { result.push(array.slice(index, index + 2)); } return result; }, []) .filter(([name, value]) => { try { validateHeaderName(name); validateHeaderValue(name, String(value)); return true; } catch { return false; } }) ); } ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/is-redirect.js const redirectStatus = new Set([301, 302, 303, 307, 308]); /** * Redirect code matching * * @param {number} code - Status code * @return {boolean} */ const isRedirect = code => { return redirectStatus.has(code); }; ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/response.js /** * Response.js * * Response class provides content decoding */ const response_INTERNALS = Symbol('Response internals'); /** * Response class * * Ref: https://fetch.spec.whatwg.org/#response-class * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Response extends Body { constructor(body = null, options = {}) { super(body, options); // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition const status = options.status != null ? options.status : 200; const headers = new Headers(options.headers); if (body !== null && !headers.has('Content-Type')) { const contentType = extractContentType(body, this); if (contentType) { headers.append('Content-Type', contentType); } } this[response_INTERNALS] = { type: 'default', url: options.url, status, statusText: options.statusText || '', headers, counter: options.counter, highWaterMark: options.highWaterMark }; } get type() { return this[response_INTERNALS].type; } get url() { return this[response_INTERNALS].url || ''; } get status() { return this[response_INTERNALS].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[response_INTERNALS].status >= 200 && this[response_INTERNALS].status < 300; } get redirected() { return this[response_INTERNALS].counter > 0; } get statusText() { return this[response_INTERNALS].statusText; } get headers() { return this[response_INTERNALS].headers; } get highWaterMark() { return this[response_INTERNALS].highWaterMark; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this, this.highWaterMark), { type: this.type, url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected, size: this.size, highWaterMark: this.highWaterMark }); } /** * @param {string} url The URL that the new response is to originate from. * @param {number} status An optional status code for the response (e.g., 302.) * @returns {Response} A Response object. */ static redirect(url, status = 302) { if (!isRedirect(status)) { throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); } return new Response(null, { headers: { location: new URL(url).toString() }, status }); } static error() { const response = new Response(null, {status: 0, statusText: ''}); response[response_INTERNALS].type = 'error'; return response; } static json(data = undefined, init = {}) { const body = JSON.stringify(data); if (body === undefined) { throw new TypeError('data is not JSON serializable'); } const headers = new Headers(init && init.headers); if (!headers.has('content-type')) { headers.set('content-type', 'application/json'); } return new Response(body, { ...init, headers }); } get [Symbol.toStringTag]() { return 'Response'; } } Object.defineProperties(Response.prototype, { type: {enumerable: true}, url: {enumerable: true}, status: {enumerable: true}, ok: {enumerable: true}, redirected: {enumerable: true}, statusText: {enumerable: true}, headers: {enumerable: true}, clone: {enumerable: true} }); ;// CONCATENATED MODULE: external "node:url" const external_node_url_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url"); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/get-search.js const getSearch = parsedURL => { if (parsedURL.search) { return parsedURL.search; } const lastOffset = parsedURL.href.length - 1; const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : ''); return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : ''; }; ;// CONCATENATED MODULE: external "node:net" const external_node_net_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net"); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/referrer.js /** * @external URL * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL} */ /** * @module utils/referrer * @private */ /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer} * @param {string} URL * @param {boolean} [originOnly=false] */ function stripURLForUseAsAReferrer(url, originOnly = false) { // 1. If url is null, return no referrer. if (url == null) { // eslint-disable-line no-eq-null, eqeqeq return 'no-referrer'; } url = new URL(url); // 2. If url's scheme is a local scheme, then return no referrer. if (/^(about|blob|data):$/.test(url.protocol)) { return 'no-referrer'; } // 3. Set url's username to the empty string. url.username = ''; // 4. Set url's password to null. // Note: `null` appears to be a mistake as this actually results in the password being `"null"`. url.password = ''; // 5. Set url's fragment to null. // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`. url.hash = ''; // 6. If the origin-only flag is true, then: if (originOnly) { // 6.1. Set url's path to null. // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`. url.pathname = ''; // 6.2. Set url's query to null. // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`. url.search = ''; } // 7. Return url. return url; } /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy} */ const ReferrerPolicy = new Set([ '', 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ]); /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy} */ const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'; /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies} * @param {string} referrerPolicy * @returns {string} referrerPolicy */ function validateReferrerPolicy(referrerPolicy) { if (!ReferrerPolicy.has(referrerPolicy)) { throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); } return referrerPolicy; } /** * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?} * @param {external:URL} url * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" */ function isOriginPotentiallyTrustworthy(url) { // 1. If origin is an opaque origin, return "Not Trustworthy". // Not applicable // 2. Assert: origin is a tuple origin. // Not for implementations // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy". if (/^(http|ws)s:$/.test(url.protocol)) { return true; } // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy". const hostIp = url.host.replace(/(^\[)|(]$)/g, ''); const hostIPVersion = (0,external_node_net_namespaceObject.isIP)(hostIp); if (hostIPVersion === 4 && /^127\./.test(hostIp)) { return true; } if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { return true; } // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy". // We are returning FALSE here because we cannot ensure conformance to // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost) if (url.host === 'localhost' || url.host.endsWith('.localhost')) { return false; } // 6. If origin's scheme component is file, return "Potentially Trustworthy". if (url.protocol === 'file:') { return true; } // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy". // Not supported // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy". // Not supported // 9. Return "Not Trustworthy". return false; } /** * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?} * @param {external:URL} url * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" */ function isUrlPotentiallyTrustworthy(url) { // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy". if (/^about:(blank|srcdoc)$/.test(url)) { return true; } // 2. If url's scheme is "data", return "Potentially Trustworthy". if (url.protocol === 'data:') { return true; } // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were // created. Therefore, blobs created in a trustworthy origin will themselves be potentially // trustworthy. if (/^(blob|filesystem):$/.test(url.protocol)) { return true; } // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin. return isOriginPotentiallyTrustworthy(url); } /** * Modifies the referrerURL to enforce any extra security policy considerations. * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 * @callback module:utils/referrer~referrerURLCallback * @param {external:URL} referrerURL * @returns {external:URL} modified referrerURL */ /** * Modifies the referrerOrigin to enforce any extra security policy considerations. * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 * @callback module:utils/referrer~referrerOriginCallback * @param {external:URL} referrerOrigin * @returns {external:URL} modified referrerOrigin */ /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer} * @param {Request} request * @param {object} o * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback * @returns {external:URL} Request's referrer */ function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) { // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for // these cases: // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm. // > Note: If request's referrer policy is the empty string, Fetch will not call into this // > algorithm. if (request.referrer === 'no-referrer' || request.referrerPolicy === '') { return null; } // 1. Let policy be request's associated referrer policy. const policy = request.referrerPolicy; // 2. Let environment be request's client. // not applicable to node.js // 3. Switch on request's referrer: if (request.referrer === 'about:client') { return 'no-referrer'; } // "a URL": Let referrerSource be request's referrer. const referrerSource = request.referrer; // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer. let referrerURL = stripURLForUseAsAReferrer(referrerSource); // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the // origin-only flag set to true. let referrerOrigin = stripURLForUseAsAReferrer(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; } // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary // policy considerations in the interests of minimizing data leakage. For example, the user // agent could strip the URL down to an origin, modify its host, replace it with an empty // string, etc. if (referrerURLCallback) { referrerURL = referrerURLCallback(referrerURL); } if (referrerOriginCallback) { referrerOrigin = referrerOriginCallback(referrerOrigin); } // 8.Execute the statements corresponding to the value of policy: const currentURL = new URL(request.url); switch (policy) { case 'no-referrer': return 'no-referrer'; case 'origin': return referrerOrigin; case 'unsafe-url': return referrerURL; case 'strict-origin': // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a // potentially trustworthy URL, then return no referrer. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return 'no-referrer'; } // 2. Return referrerOrigin. return referrerOrigin.toString(); case 'strict-origin-when-cross-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // 2. If referrerURL is a potentially trustworthy URL and request's 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 'same-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // 2. Return no referrer. return 'no-referrer'; case 'origin-when-cross-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // Return referrerOrigin. return referrerOrigin; case 'no-referrer-when-downgrade': // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a // potentially trustworthy URL, then return no referrer. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return 'no-referrer'; } // 2. Return referrerURL. return referrerURL; default: throw new TypeError(`Invalid referrerPolicy: ${policy}`); } } /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header} * @param {Headers} headers Response headers * @returns {string} policy */ function parseReferrerPolicyFromHeader(headers) { // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` // and response’s header list. const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/); // 2. Let policy be the empty string. let policy = ''; // 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. // Note: This algorithm loops over multiple policy values to allow deployment of new policy // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values. for (const token of policyTokens) { if (token && ReferrerPolicy.has(token)) { policy = token; } } // 4. Return policy. return policy; } ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/request.js /** * Request.js * * Request class contains server only options * * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. */ const request_INTERNALS = Symbol('Request internals'); /** * Check if `obj` is an instance of Request. * * @param {*} object * @return {boolean} */ const isRequest = object => { return ( typeof object === 'object' && typeof object[request_INTERNALS] === 'object' ); }; const doBadDataWarn = (0,external_node_util_namespaceObject.deprecate)(() => {}, '.data is not a valid RequestInit property, use .body instead', 'https://github.com/node-fetch/node-fetch/issues/1000 (request)'); /** * Request class * * Ref: https://fetch.spec.whatwg.org/#request-class * * @param Mixed input Url or Request instance * @param Object init Custom options * @return Void */ class Request extends Body { constructor(input, init = {}) { let parsedURL; // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245) if (isRequest(input)) { parsedURL = new URL(input.url); } else { parsedURL = new URL(input); input = {}; } if (parsedURL.username !== '' || parsedURL.password !== '') { throw new TypeError(`${parsedURL} is an url with embedded credentials.`); } let method = init.method || input.method || 'GET'; if (/^(delete|get|head|options|post|put)$/i.test(method)) { method = method.toUpperCase(); } if (!isRequest(init) && 'data' in init) { doBadDataWarn(); } // eslint-disable-next-line no-eq-null, eqeqeq if ((init.body != null || (isRequest(input) && input.body !== null)) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } const inputBody = init.body ? init.body : (isRequest(input) && input.body !== null ? clone(input) : null); super(inputBody, { size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody !== null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody, this); if (contentType) { headers.set('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) { signal = init.signal; } // eslint-disable-next-line no-eq-null, eqeqeq if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget'); } // §5.4, Request constructor steps, step 15.1 // eslint-disable-next-line no-eq-null, eqeqeq let referrer = init.referrer == null ? input.referrer : init.referrer; if (referrer === '') { // §5.4, Request constructor steps, step 15.2 referrer = 'no-referrer'; } else if (referrer) { // §5.4, Request constructor steps, step 15.3.1, 15.3.2 const parsedReferrer = new URL(referrer); // §5.4, Request constructor steps, step 15.3.3, 15.3.4 referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer; } else { referrer = undefined; } this[request_INTERNALS] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal, referrer }; // Node-fetch-only options this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow; this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; // §5.4, Request constructor steps, step 16. // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ''; } /** @returns {string} */ get method() { return this[request_INTERNALS].method; } /** @returns {string} */ get url() { return (0,external_node_url_namespaceObject.format)(this[request_INTERNALS].parsedURL); } /** @returns {Headers} */ get headers() { return this[request_INTERNALS].headers; } get redirect() { return this[request_INTERNALS].redirect; } /** @returns {AbortSignal} */ get signal() { return this[request_INTERNALS].signal; } // https://fetch.spec.whatwg.org/#dom-request-referrer get referrer() { if (this[request_INTERNALS].referrer === 'no-referrer') { return ''; } if (this[request_INTERNALS].referrer === 'client') { return 'about:client'; } if (this[request_INTERNALS].referrer) { return this[request_INTERNALS].referrer.toString(); } return undefined; } get referrerPolicy() { return this[request_INTERNALS].referrerPolicy; } set referrerPolicy(referrerPolicy) { this[request_INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy); } /** * Clone this request * * @return Request */ clone() { return new Request(this); } get [Symbol.toStringTag]() { return 'Request'; } } Object.defineProperties(Request.prototype, { method: {enumerable: true}, url: {enumerable: true}, headers: {enumerable: true}, redirect: {enumerable: true}, clone: {enumerable: true}, signal: {enumerable: true}, referrer: {enumerable: true}, referrerPolicy: {enumerable: true} }); /** * Convert a Request to Node.js http request options. * * @param {Request} request - A Request instance * @return The options object to be passed to http.request */ const getNodeRequestOptions = request => { const {parsedURL} = request[request_INTERNALS]; const headers = new Headers(request[request_INTERNALS].headers); // Fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*'); } // HTTP-network-or-cache fetch steps 2.4-2.7 let contentLengthValue = null; if (request.body === null && /^(post|put)$/i.test(request.method)) { contentLengthValue = '0'; } if (request.body !== null) { const totalBytes = getTotalBytes(request); // Set Content-Length if totalBytes is a number (that is not NaN) if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set('Content-Length', contentLengthValue); } // 4.1. Main fetch, step 2.6 // > If request's referrer policy is the empty string, then set request's referrer policy to the // > default referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = DEFAULT_REFERRER_POLICY; } // 4.1. Main fetch, step 2.7 // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking // > determine request's referrer. if (request.referrer && request.referrer !== 'no-referrer') { request[request_INTERNALS].referrer = determineRequestsReferrer(request); } else { request[request_INTERNALS].referrer = 'no-referrer'; } // 4.5. HTTP-network-or-cache fetch, step 6.9 // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized // > and isomorphic encoded, to httpRequest's header list. if (request[request_INTERNALS].referrer instanceof URL) { headers.set('Referer', request.referrer); } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', 'node-fetch'); } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip, deflate, br'); } let {agent} = request; if (typeof agent === 'function') { agent = agent(parsedURL); } // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js const search = getSearch(parsedURL); // Pass the full URL directly to request(), but overwrite the following // options: const options = { // Overwrite search to retain trailing ? (issue #776) path: parsedURL.pathname + search, // The following options are not expressed in the URL method: request.method, headers: headers[Symbol.for('nodejs.util.inspect.custom')](), insecureHTTPParser: request.insecureHTTPParser, agent }; return { /** @type {URL} */ parsedURL, options }; }; ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/abort-error.js /** * AbortError interface for cancelled requests */ class AbortError extends FetchBaseError { constructor(message, type = 'aborted') { super(message, type); } } // EXTERNAL MODULE: ./node_modules/fetch-blob/from.js + 2 modules var from = __nccwpck_require__(2777); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/index.js /** * Index.js * * a request API compatible with window.fetch * * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. */ const supportedSchemas = new Set(['data:', 'http:', 'https:']); /** * Fetch function * * @param {string | URL | import('./request').default} url - Absolute url or Request instance * @param {*} [options_] - Fetch options * @return {Promise} */ async function fetch(url, options_) { return new Promise((resolve, reject) => { // Build request object const request = new Request(url, options_); const {parsedURL, options} = getNodeRequestOptions(request); if (!supportedSchemas.has(parsedURL.protocol)) { throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`); } if (parsedURL.protocol === 'data:') { const data = dist(request.url); const response = new Response(data, {headers: {'Content-Type': data.typeFull}}); resolve(response); return; } // Wrap http.request into fetch const send = (parsedURL.protocol === 'https:' ? external_node_https_namespaceObject : external_node_http_namespaceObject).request; const {signal} = request; let response = null; const abort = () => { const error = new AbortError('The operation was aborted.'); reject(error); if (request.body && request.body instanceof external_node_stream_namespaceObject.Readable) { request.body.destroy(error); } if (!response || !response.body) { return; } response.body.emit('error', error); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = () => { abort(); finalize(); }; // Send request const request_ = send(parsedURL.toString(), options); if (signal) { signal.addEventListener('abort', abortAndFinalize); } const finalize = () => { request_.abort(); if (signal) { signal.removeEventListener('abort', abortAndFinalize); } }; request_.on('error', error => { reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error)); finalize(); }); fixResponseChunkedTransferBadEnding(request_, error => { if (response && response.body) { response.body.destroy(error); } }); /* c8 ignore next 18 */ if (process.version < 'v14') { // Before Node.js 14, pipeline() does not fully support async iterators and does not always // properly handle when the socket close/end events are out of order. request_.on('socket', s => { let endedWithEventsCount; s.prependListener('end', () => { endedWithEventsCount = s._eventsCount; }); s.prependListener('close', hadError => { // if end happened before close but the socket didn't emit an error, do it now if (response && endedWithEventsCount < s._eventsCount && !hadError) { const error = new Error('Premature close'); error.code = 'ERR_STREAM_PREMATURE_CLOSE'; response.body.emit('error', error); } }); }); } request_.on('response', response_ => { request_.setTimeout(0); const headers = fromRawHeaders(response_.rawHeaders); // HTTP fetch step 5 if (isRedirect(response_.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location'); // HTTP fetch step 5.3 let locationURL = null; try { locationURL = location === null ? null : new URL(location, request.url); } catch { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); finalize(); return; } } // HTTP fetch step 5.5 switch (request.redirect) { case 'error': reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); finalize(); return; case 'manual': // Nothing to do break; case 'follow': { // HTTP-redirect fetch step 2 if (locationURL === null) { break; } // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); finalize(); return; } // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOptions = { headers: new Headers(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: clone(request), signal: request.signal, size: request.size, referrer: request.referrer, referrerPolicy: request.referrerPolicy }; // when forwarding sensitive headers like "Authorization", // "WWW-Authenticate", and "Cookie" to untrusted targets, // headers will be ignored when following a redirect to a domain // that is not a subdomain match or exact match of the initial domain. // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" // will forward the sensitive headers, but a redirect to "bar.com" will not. // headers will also be ignored when following a redirect to a domain using // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" // will not forward the sensitive headers if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOptions.headers.delete(name); } } // HTTP-redirect fetch step 9 if (response_.statusCode !== 303 && request.body && options_.body instanceof external_node_stream_namespaceObject.Readable) { reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); finalize(); return; } // HTTP-redirect fetch step 11 if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) { requestOptions.method = 'GET'; requestOptions.body = undefined; requestOptions.headers.delete('content-length'); } // HTTP-redirect fetch step 14 const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); if (responseReferrerPolicy) { requestOptions.referrerPolicy = responseReferrerPolicy; } // HTTP-redirect fetch step 15 resolve(fetch(new Request(locationURL, requestOptions))); finalize(); return; } default: return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); } } // Prepare response if (signal) { response_.once('end', () => { signal.removeEventListener('abort', abortAndFinalize); }); } let body = (0,external_node_stream_namespaceObject.pipeline)(response_, new external_node_stream_namespaceObject.PassThrough(), error => { if (error) { reject(error); } }); // see https://github.com/nodejs/node/pull/29376 /* c8 ignore next 3 */ if (process.version < 'v12.10') { response_.on('aborted', abortAndFinalize); } const responseOptions = { url: request.url, status: response_.statusCode, statusText: response_.statusMessage, headers, size: request.size, counter: request.counter, highWaterMark: request.highWaterMark }; // HTTP-network fetch step 12.1.1.3 const codings = headers.get('Content-Encoding'); // HTTP-network fetch step 12.1.1.4: handle content codings // in following scenarios we ignore compression support // 1. compression support is disabled // 2. HEAD request // 3. no Content-Encoding header // 4. no content response (204) // 5. content not modified response (304) if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { response = new Response(body, responseOptions); resolve(response); return; } // For Node v6+ // 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. const zlibOptions = { flush: external_node_zlib_namespaceObject.Z_SYNC_FLUSH, finishFlush: external_node_zlib_namespaceObject.Z_SYNC_FLUSH }; // For gzip if (codings === 'gzip' || codings === 'x-gzip') { body = (0,external_node_stream_namespaceObject.pipeline)(body, external_node_zlib_namespaceObject.createGunzip(zlibOptions), error => { if (error) { reject(error); } }); response = new Response(body, responseOptions); resolve(response); return; } // For deflate if (codings === 'deflate' || codings === 'x-deflate') { // Handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = (0,external_node_stream_namespaceObject.pipeline)(response_, new external_node_stream_namespaceObject.PassThrough(), error => { if (error) { reject(error); } }); raw.once('data', chunk => { // See http://stackoverflow.com/questions/37519828 if ((chunk[0] & 0x0F) === 0x08) { body = (0,external_node_stream_namespaceObject.pipeline)(body, external_node_zlib_namespaceObject.createInflate(), error => { if (error) { reject(error); } }); } else { body = (0,external_node_stream_namespaceObject.pipeline)(body, external_node_zlib_namespaceObject.createInflateRaw(), error => { if (error) { reject(error); } }); } response = new Response(body, responseOptions); resolve(response); }); raw.once('end', () => { // Some old IIS servers return zero-length OK deflate responses, so // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 if (!response) { response = new Response(body, responseOptions); resolve(response); } }); return; } // For br if (codings === 'br') { body = (0,external_node_stream_namespaceObject.pipeline)(body, external_node_zlib_namespaceObject.createBrotliDecompress(), error => { if (error) { reject(error); } }); response = new Response(body, responseOptions); resolve(response); return; } // Otherwise, use response as-is response = new Response(body, responseOptions); resolve(response); }); // eslint-disable-next-line promise/prefer-await-to-then writeToStream(request_, request).catch(reject); }); } function fixResponseChunkedTransferBadEnding(request, errorCallback) { const LAST_CHUNK = external_node_buffer_namespaceObject.Buffer.from('0\r\n\r\n'); let isChunkedTransfer = false; let properLastChunkReceived = false; let previousChunk; request.on('response', response => { const {headers} = response; isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length']; }); request.on('socket', socket => { const onSocketClose = () => { if (isChunkedTransfer && !properLastChunkReceived) { const error = new Error('Premature close'); error.code = 'ERR_STREAM_PREMATURE_CLOSE'; errorCallback(error); } }; const onData = buf => { properLastChunkReceived = external_node_buffer_namespaceObject.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; // Sometimes final 0-length chunk and end of message code are in separate packets if (!properLastChunkReceived && previousChunk) { properLastChunkReceived = ( external_node_buffer_namespaceObject.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && external_node_buffer_namespaceObject.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 ); } previousChunk = buf; }; socket.prependListener('close', onSocketClose); socket.on('data', onData); request.on('close', () => { socket.removeListener('close', onSocketClose); socket.removeListener('data', onData); }); }); } // EXTERNAL MODULE: ./node_modules/@lifeomic/attempt/dist/src/index.js var src = __nccwpck_require__(6494); ;// CONCATENATED MODULE: ./src/client/client.ts /* harmony default export */ const client = ({ postManifest: async (url, token, functionId, body, logger, _fetch = fetch, errorHandler = defaultClientErrorHandler) => { if (!url) throw new Error('Speckle Server URL is required'); if (!token) throw new Error('Speckle Token is required'); const endpointUrl = new external_url_namespaceObject.URL(`/api/v1/functions/${functionId}/versions`, url); let responseBodyStream; try { responseBodyStream = await retryAPIRequest(throwErrorOnClientErrorStatusCode(async () => _fetch(endpointUrl.href, { method: 'POST', headers: { 'Content-Type': 'application/json', authorization: `Bearer ${token}` }, body: JSON.stringify(body) })), errorHandler); } catch (err) { throw new Error(`Failed to register Speckle Function: ${err}`, { cause: err }); //FIXME use a more specific error type } const response = new Response(responseBodyStream); let responseBody; try { responseBody = SpeckleFunctionPostResponseBodySchema.parse(await response.json()); } catch (err) { throw handleZodError(err, logger); } return responseBody; } }); function defaultClientErrorHandler(error, context) { if (isNonRetryableError(error)) { context.abort(); } } function isNonRetryableError(error) { return !(error instanceof RetryableError); } function throwErrorOnClientErrorStatusCode(apiRequest) { return async () => { const response = await apiRequest(); // do not retry our failures if (response.status >= 400 && response.status < 500) throw new NonRetryableError(`Status code indicates a client error. Not retrying. (status: "${response.status}"; body: "${await new Response(response.body).text()}")`); if (response.status >= 500) throw new RetryableError(`Status code indicates a server error. Retrying. (status: "${response.status}"; body: "${await new Response(response.body).text()}")`); return response; }; } async function retryAPIRequest(apiRequest, errorHandler) { const { body } = await (0,src/* retry */.XD)(apiRequest, { delay: 200, factor: 2, maxAttempts: 5, minDelay: 100, maxDelay: 500, jitter: true, handleError: errorHandler }); return body; } class RetryableError extends Error { constructor(message) { super(message); this.name = 'RetryableError'; } } class NonRetryableError extends Error { constructor(message) { super(message); this.name = 'NonRetryableError'; } } ;// CONCATENATED MODULE: ./src/registerspecklefunction.ts async function registerSpeckleFunction(opts) { let speckleServerUrl; let speckleToken; let speckleFunctionPath; let speckleFunctionId; let speckleFunctionCommand; let speckleFunctionInputSchema; let versionTag; let commitId; try { speckleServerUrl = SpeckleServerUrlSchema.parse(opts.speckleServerUrl); speckleToken = SpeckleTokenSchema.parse(opts.speckleToken); speckleFunctionPath = SpeckleFunctionPathSchema.parse(opts.speckleFunctionPath); speckleFunctionId = SpeckleFunctionIdSchema.parse(opts.speckleFunctionId); versionTag = VersionTagSchema.parse(opts.versionTag); commitId = CommitIdSchema.parse(opts.commitId); speckleFunctionInputSchema = opts.speckleFunctionInputSchema ? SpeckleFunctionInputSchema.parse(JSON.parse(opts.speckleFunctionInputSchema)) : {}; speckleFunctionCommand = opts.speckleFunctionCommand.split(' '); } catch (err) { throw handleZodError(err, opts.logger); } opts.logger.info(`Speckle Server URL: '${speckleServerUrl}'`); //token is masked in the logs, so no need to print it here. opts.logger.info(`Speckle Function Path: '${speckleFunctionPath}'`); opts.logger.info(`Speckle Function ID: '${speckleFunctionId}'`); // const manifest = await findAndParseManifest(speckleFunctionPath, { // logger: opts.logger, // fileSystem: opts.fileSystem // }) const body = { commitId, versionTag, command: speckleFunctionCommand, inputSchema: speckleFunctionInputSchema }; const response = await client.postManifest(speckleServerUrl, speckleToken, speckleFunctionId, body, opts.logger); opts.logger.info(`Successfully registered version ${response.versionId} of Speckle Function ${speckleFunctionId}`); return response; } // EXTERNAL MODULE: external "fs" var external_fs_ = __nccwpck_require__(7147); ;// CONCATENATED MODULE: ./node_modules/js-yaml/dist/js-yaml.mjs /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; // YAML error class. http://stackoverflow.com/questions/8458984 function formatError(exception, compact) { var where = '', message = exception.reason || '(unknown reason)'; if (!exception.mark) return message; if (exception.mark.name) { where += 'in "' + exception.mark.name + '" '; } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet; } return message + ' ' + where; } function YAMLException$1(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = formatError(this, false); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException$1.prototype = Object.create(Error.prototype); YAMLException$1.prototype.constructor = YAMLException$1; YAMLException$1.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; var exception = YAMLException$1; // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ''; var tail = ''; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = ' ... '; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = ' ...'; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string, max) { return common.repeat(' ', max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== 'number') options.indent = 1; if (typeof options.linesBefore !== 'number') options.linesBefore = 3; if (typeof options.linesAfter !== 'number') options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [ 0 ]; var lineEnds = []; var match; var foundLineNo = -1; while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = '', i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; } return result.replace(/\n$/, ''); } var snippet = makeSnippet; var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.representName = options['representName'] || null; this.defaultStyle = options['defaultStyle'] || null; this.multi = options['multi'] || false; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } var type = Type$1; /*eslint-disable max-len*/ function compileList(schema, name) { var result = []; schema[name].forEach(function (currentType) { var newIndex = result.length; result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi['fallback'].push(type); } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema$1(definition) { return this.extend(definition); } Schema$1.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; if (definition instanceof type) { // Schema.extend(type) explicit.push(definition); } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new exception('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } implicit.forEach(function (type$1) { if (!(type$1 instanceof type)) { throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } if (type$1.loadKind && type$1.loadKind !== 'scalar') { throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } if (type$1.multi) { throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } }); explicit.forEach(function (type$1) { if (!(type$1 instanceof type)) { throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } }); var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, 'implicit'); result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; var schema = Schema$1; var str = new type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); var seq = new type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); var map = new type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } var _null = new type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; }, empty: function () { return ''; } }, defaultStyle: 'lowercase' }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } var bool = new type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'o') { // base 8 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } } // base 10 (except 0) // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } var js_yaml_int = new type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } var js_yaml_float = new type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); var json = failsafe.extend({ implicit: [ _null, bool, js_yaml_int, js_yaml_float ] }); var js_yaml_core = json; var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } var timestamp = new type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === '<<' || data === null; } var merge = new type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /*eslint-disable no-bitwise*/ // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } return new Uint8Array(result); } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } var binary = new type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString$2.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty$3.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } var omap = new type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString$1.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } var pairs = new type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } var set = new type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); var _default = js_yaml_core.extend({ implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); /*eslint-disable max-len,no-use-before-define*/ var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State$1(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || _default; this.onWarning = options['onWarning'] || null; // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = snippet(mark); return new exception(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } // used for this specific key only because Object.defineProperty is slow if (keyNode === '__proto__') { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; // Save the current line. _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, 'tag name is malformed: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== '!') { if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type type = null; typeList = state.typeMap.multi[state.kind || 'fallback']; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>'); } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State$1(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll$1(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load$1(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new exception('expected a single document in the stream, but found more'); } var loadAll_1 = loadAll$1; var load_1 = load$1; var loader = { loadAll: loadAll_1, load: load_1 }; /*eslint-disable no-use-before-define*/ var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 0xFEFF; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_EQUALS = 0x3D; /* = */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (map === null) return {}; result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap['fallback'][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options['schema'] || _default; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.sortKeys = options['sortKeys'] || false; this.lineWidth = options['lineWidth'] || 80; this.noRefs = options['noRefs'] || false; this.noCompatMode = options['noCompatMode'] || false; this.condenseFlow = options['condenseFlow'] || false; this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options['forceQuotes'] || false; this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString(string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') result += ind; result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } // [33] s-white ::= s-space | s-tab function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable(c) { return (0x00020 <= c && c <= 0x00007E) || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) || (0x10000 <= c && c <= 0x10FFFF); } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // Including s-white (for some reason, examples doesn't match specs in this aspect) // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM // - b-char && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out // c = flow-in ⇒ ns-plain-safe-in // c = block-key ⇒ ns-plain-safe-out // c = flow-key ⇒ ns-plain-safe-in // [128] ns-plain-safe-out ::= ns-char // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) // | ( /* An ns-char preceding */ “#” ) // | ( “:” /* Followed by an ns-plain-safe(c) */ ) function isPlainSafe(c, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return ( // ns-plain-safe inblock ? // c = flow-in cIsNsCharOrWhitespace : cIsNsCharOrWhitespace // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET ) // ns-plain-char && c !== CHAR_SHARP // false on '#' && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) // - s-white // - (c-indicator ::= // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } // Simplified test for values allowed as the last character in plain style. function isPlainSafeLast(c) { // just not whitespace or colon, it will be checked to be plain character later return !isWhitespace(c) && c !== CHAR_COLON; } // Same as 'string'.codePointAt(pos), but works in older browsers. function codePointAt(string, pos) { var first = string.charCodeAt(pos), second; if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } // Determines whether block indentation indicator is required. function needIndentIndicator(string) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string); } var STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; // only checked if shouldTrackWidth var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; // count the first line correctly var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { // Case: block styles permitted. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' '); previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')); } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. if (plain && !forceQuotes && !testAmbiguousType(string)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE; } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar(state, string, level, iskey, inblock) { state.dump = (function () { if (string.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); } } var indent = state.indent * Math.max(1, level); // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety. var singleLineOnly = iskey // No block styles in flow mode. || (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string) + '"'; default: throw new exception('impossible error: invalid scalar style'); } }()); } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader(string, indentPerLevel) { var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line. var clip = string[string.length - 1] === '\n'; var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); var chomp = keep ? '+' : (clip ? '' : '-'); return indentIndicator + chomp + '\n'; } // (See the note for writeScalar.) function dropEndingNewline(string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString(string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line) var result = (function () { var nextLF = string.indexOf('\n'); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }()); // If we haven't reached the first content line yet, don't add an extra \n. var prevMoreIndented = string[0] === '\n' || string[0] === ' '; var moreIndented; // rest of the lines var match; while ((match = lineRe.exec(string))) { var prefix = match[1], line = match[2]; moreIndented = (line[0] === ' '); result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine(line, width) { if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. var match; // start is an inclusive index. end, curr, and next are exclusive. var start = 0, end, curr = 0, next = 0; var result = ''; // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index; // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next; // derive end <= length-2 result += '\n' + line.slice(start, end); // skip the space that was output as \n start = end + 1; // derive start <= length-1 } curr = next; } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n'; // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); // drop extra \n joiner } // Escapes a double-quoted string. function escapeString(string) { var result = ''; var char = 0; var escapeSeq; for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 0x10000) result += string[i + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level, value, false, false) || (typeof value === 'undefined' && writeNode(state, level, null, false, false))) { if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level + 1, value, true, true, false, true) || (typeof value === 'undefined' && writeNode(state, level + 1, null, true, true, false, true))) { if (!compact || _result !== '') { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-'; } else { _result += '- '; } _result += state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (_result !== '') pairBuffer += ', '; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort(); } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { // Something is wrong throw new exception('sortKeys must be a boolean or a function'); } for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || _result !== '') { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { if (explicit) { if (type.multi && type.representName) { state.tag = type.representName(object); } else { state.tag = type.tag; } } else { state.tag = '?'; } if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style); } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = (state.flowLevel < 0 || state.flowLevel > level); } var objectOrArray = type === '[object Object]' || type === '[object Array]', duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object Array]') { if (block && (state.dump.length !== 0)) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type === '[object Undefined]') { return false; } else { if (state.skipInvalid) return false; throw new exception('unacceptable kind of an object to dump ' + type); } if (state.tag !== null && state.tag !== '?') { // Need to encode all characters except those allowed by the spec: // // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ // [36] ns-hex-digit ::= ns-dec-digit // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” // // Also need to encode '!' because it has special meaning (end of tag prefix). // tagStr = encodeURI( state.tag[0] === '!' ? state.tag.slice(1) : state.tag ).replace(/!/g, '%21'); if (state.tag[0] === '!') { tagStr = '!' + tagStr; } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { tagStr = '!!' + tagStr.slice(18); } else { tagStr = '!<' + tagStr + '>'; } state.dump = tagStr + ' ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length; if (object !== null && typeof object === 'object') { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump$1(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ '': value }, '', value); } if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; return ''; } var dump_1 = dump$1; var dumper = { dump: dump_1 }; function renamed(from, to) { return function () { throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + 'Use yaml.' + to + ' instead, which is now safe by default.'); }; } var Type = type; var Schema = schema; var FAILSAFE_SCHEMA = failsafe; var JSON_SCHEMA = json; var CORE_SCHEMA = js_yaml_core; var DEFAULT_SCHEMA = _default; var load = loader.load; var loadAll = loader.loadAll; var dump = dumper.dump; var YAMLException = exception; // Re-export all types in case user wants to create custom schema var types = { binary: binary, float: js_yaml_float, map: map, null: _null, pairs: pairs, set: set, timestamp: timestamp, bool: bool, int: js_yaml_int, merge: merge, omap: omap, seq: seq, str: str }; // Removed functions from JS-YAML 3.0.x var safeLoad = renamed('safeLoad', 'load'); var safeLoadAll = renamed('safeLoadAll', 'loadAll'); var safeDump = renamed('safeDump', 'dump'); var jsYaml = { Type: Type, Schema: Schema, FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, JSON_SCHEMA: JSON_SCHEMA, CORE_SCHEMA: CORE_SCHEMA, DEFAULT_SCHEMA: DEFAULT_SCHEMA, load: load, loadAll: loadAll, dump: dump, YAMLException: YAMLException, types: types, safeLoad: safeLoad, safeLoadAll: safeLoadAll, safeDump: safeDump }; /* harmony default export */ const js_yaml = (jsYaml); ;// CONCATENATED MODULE: ./src/filesystem/files.ts const fileUtil = { loadYaml: async (filePath) => { return js_yaml.load(await external_fs_.promises.readFile(filePath, 'utf8')); } }; /* harmony default export */ const files = (fileUtil); ;// CONCATENATED MODULE: ./src/main.ts async function run() { try { const speckleServerUrlRaw = core.getInput('speckle_server_url'); const speckleTokenRaw = core.getInput('speckle_token'); core.setSecret(speckleTokenRaw); const speckleFunctionPathRaw = core.getInput('speckle_function_path'); const speckleFunctionIdRaw = core.getInput('speckle_function_id'); const speckleFunctionInputSchema = core.getInput('speckle_function_input_schema'); const speckleFunctionCommand = core.getInput('speckle_function_command'); const gitRefName = process.env.GITHUB_REF_NAME; const gitRefType = process.env.GITHUB_REF_TYPE; const gitCommitShaRaw = process.env.GITHUB_SHA; if (!gitCommitShaRaw) throw new Error('GITHUB_REF_NAME is not defined'); if (!gitRefName) throw new Error('GITHUB_REF_NAME is not defined'); if (!gitRefType) throw new Error('GITHUB_REF_TYPE is not defined'); const { versionId } = await registerSpeckleFunction({ speckleServerUrl: speckleServerUrlRaw, speckleToken: speckleTokenRaw, speckleFunctionPath: speckleFunctionPathRaw, speckleFunctionId: speckleFunctionIdRaw, speckleFunctionInputSchema, speckleFunctionCommand, versionTag: gitRefType === 'tag' ? gitRefName : gitCommitShaRaw, commitId: gitCommitShaRaw, logger: core, fileSystem: files }); core.setOutput('version_id', versionId); } catch (error) { if (error instanceof Error) core.setFailed(error.message); } } run(); })(); //# sourceMappingURL=index.js.map