mc-publish/dist/index.js

28719 lines
1.2 MiB
JavaScript
Raw Normal View History

2021-09-26 15:31:45 -04:00
require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 3823:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",
/***/ }),
/***/ 7351:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.issue = exports.issueCommand = void 0;
const os = __importStar(__nccwpck_require__(2087));
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__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
2021-10-01 09:38:36 -04:00
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;
2021-09-26 15:31:45 -04:00
const command_1 = __nccwpck_require__(7351);
const file_command_1 = __nccwpck_require__(717);
const utils_1 = __nccwpck_require__(5278);
const os = __importStar(__nccwpck_require__(2087));
const path = __importStar(__nccwpck_require__(5622));
2021-10-01 09:38:36 -04:00
const oidc_utils_1 = __nccwpck_require__(8041);
2021-09-26 15:31:45 -04:00
/**
* The code to exit an action
*/
var ExitCode;
(function (ExitCode) {
/**
* A code indicating that the action was successful
*/
ExitCode[ExitCode["Success"] = 0] = "Success";
/**
* A code indicating that the action was a failure
*/
ExitCode[ExitCode["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
//-----------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------
/**
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function exportVariable(name, val) {
const convertedVal = utils_1.toCommandValue(val);
process.env[name] = convertedVal;
const filePath = process.env['GITHUB_ENV'] || '';
if (filePath) {
const delimiter = '_GitHubActionsFileCommandDelimeter_';
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;
file_command_1.issueCommand('ENV', commandValue);
}
else {
command_1.issueCommand('set-env', { name }, convertedVal);
}
}
exports.exportVariable = exportVariable;
/**
* Registers a secret which will get masked from logs
* @param secret value of the secret
*/
function setSecret(secret) {
command_1.issueCommand('add-mask', {}, secret);
}
exports.setSecret = setSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
function addPath(inputPath) {
const filePath = process.env['GITHUB_PATH'] || '';
if (filePath) {
file_command_1.issueCommand('PATH', inputPath);
}
else {
command_1.issueCommand('add-path', {}, inputPath);
}
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
exports.addPath = addPath;
/**
* Gets the value of an input.
* 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 !== '');
return inputs;
}
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) {
process.stdout.write(os.EOL);
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
/**
* Enables or disables the echoing of commands into stdout for the rest of the step.
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
*
*/
function setCommandEcho(enabled) {
command_1.issue('echo', enabled ? 'on' : 'off');
}
exports.setCommandEcho = setCommandEcho;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
function setFailed(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Gets whether Actions Step Debug is on or not
*/
function isDebug() {
return process.env['RUNNER_DEBUG'] === '1';
}
exports.isDebug = isDebug;
/**
* Writes debug message to user log
* @param message debug message
*/
function debug(message) {
command_1.issueCommand('debug', {}, message);
}
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message. Errors will be converted to string via toString()
* @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) {
command_1.issueCommand('save-state', { name }, value);
}
exports.saveState = saveState;
/**
* Gets the value of an state set by this action's main execution.
*
* @param name name of the state to get
* @returns string
*/
function getState(name) {
return process.env[`STATE_${name}`] || '';
}
exports.getState = getState;
2021-10-01 09:38:36 -04:00
function getIDToken(aud) {
return __awaiter(this, void 0, void 0, function* () {
return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
}
exports.getIDToken = getIDToken;
2021-09-26 15:31:45 -04:00
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 717:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
// For internal use, subject to change.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.issueCommand = void 0;
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
const fs = __importStar(__nccwpck_require__(5747));
const os = __importStar(__nccwpck_require__(2087));
const utils_1 = __nccwpck_require__(5278);
function issueCommand(command, message) {
const filePath = process.env[`GITHUB_${command}`];
if (!filePath) {
throw new Error(`Unable to find environment variable for file command ${command}`);
}
if (!fs.existsSync(filePath)) {
throw new Error(`Missing file at path: ${filePath}`);
}
fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
encoding: 'utf8'
});
}
exports.issueCommand = issueCommand;
//# sourceMappingURL=file-command.js.map
/***/ }),
2021-10-01 09:38:36 -04:00
/***/ 8041:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OidcClient = void 0;
const http_client_1 = __nccwpck_require__(9925);
const auth_1 = __nccwpck_require__(3702);
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
/***/ }),
2021-09-26 15:31:45 -04:00
/***/ 5278:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toCommandProperties = exports.toCommandValue = void 0;
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
/**
*
* @param annotationProperties
* @returns The command properties to send with the actual annotation command
* See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
*/
function toCommandProperties(annotationProperties) {
if (!Object.keys(annotationProperties).length) {
return {};
}
return {
title: annotationProperties.title,
2021-10-01 09:38:36 -04:00
file: annotationProperties.file,
2021-09-26 15:31:45 -04:00
line: annotationProperties.startLine,
endLine: annotationProperties.endLine,
col: annotationProperties.startColumn,
endColumn: annotationProperties.endColumn
};
}
exports.toCommandProperties = toCommandProperties;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 4087:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Context = void 0;
const fs_1 = __nccwpck_require__(5747);
const os_1 = __nccwpck_require__(2087);
class Context {
/**
* Hydrate the context from the environment
*/
constructor() {
var _a, _b, _c;
this.payload = {};
if (process.env.GITHUB_EVENT_PATH) {
if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {
this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));
}
else {
const path = process.env.GITHUB_EVENT_PATH;
process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);
}
}
this.eventName = process.env.GITHUB_EVENT_NAME;
this.sha = process.env.GITHUB_SHA;
this.ref = process.env.GITHUB_REF;
this.workflow = process.env.GITHUB_WORKFLOW;
this.action = process.env.GITHUB_ACTION;
this.actor = process.env.GITHUB_ACTOR;
this.job = process.env.GITHUB_JOB;
this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);
this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);
this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`;
this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`;
this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`;
}
get issue() {
const payload = this.payload;
return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });
}
get repo() {
if (process.env.GITHUB_REPOSITORY) {
const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');
return { owner, repo };
}
if (this.payload.repository) {
return {
owner: this.payload.repository.owner.login,
repo: this.payload.repository.name
};
}
throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'");
}
}
exports.Context = Context;
//# sourceMappingURL=context.js.map
/***/ }),
/***/ 5438:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getOctokit = exports.context = void 0;
const Context = __importStar(__nccwpck_require__(4087));
const utils_1 = __nccwpck_require__(3030);
exports.context = new Context.Context();
/**
* Returns a hydrated octokit ready to use for GitHub Actions
*
* @param token the repo PAT or GITHUB_TOKEN
* @param options other options to set
*/
function getOctokit(token, options) {
return new utils_1.GitHub(utils_1.getOctokitOptions(token, options));
}
exports.getOctokit = getOctokit;
//# sourceMappingURL=github.js.map
/***/ }),
/***/ 7914:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;
const httpClient = __importStar(__nccwpck_require__(9925));
function getAuthString(token, options) {
if (!token && !options.auth) {
throw new Error('Parameter token or opts.auth is required');
}
else if (token && options.auth) {
throw new Error('Parameters token and opts.auth may not both be specified');
}
return typeof options.auth === 'string' ? options.auth : `token ${token}`;
}
exports.getAuthString = getAuthString;
function getProxyAgent(destinationUrl) {
const hc = new httpClient.HttpClient();
return hc.getAgent(destinationUrl);
}
exports.getProxyAgent = getProxyAgent;
function getApiBaseUrl() {
return process.env['GITHUB_API_URL'] || 'https://api.github.com';
}
exports.getApiBaseUrl = getApiBaseUrl;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 3030:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getOctokitOptions = exports.GitHub = exports.context = void 0;
const Context = __importStar(__nccwpck_require__(4087));
const Utils = __importStar(__nccwpck_require__(7914));
// octokit + plugins
const core_1 = __nccwpck_require__(6762);
const plugin_rest_endpoint_methods_1 = __nccwpck_require__(3044);
const plugin_paginate_rest_1 = __nccwpck_require__(4193);
exports.context = new Context.Context();
const baseUrl = Utils.getApiBaseUrl();
const defaults = {
baseUrl,
request: {
agent: Utils.getProxyAgent(baseUrl)
}
};
exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults);
/**
* Convience function to correctly format Octokit Options to pass into the constructor.
*
* @param token the repo PAT or GITHUB_TOKEN
* @param options other options to set
*/
function getOctokitOptions(token, options) {
const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller
// Auth
const auth = Utils.getAuthString(token, opts);
if (auth) {
opts.auth = auth;
}
return opts;
}
exports.getOctokitOptions = getOctokitOptions;
//# sourceMappingURL=utils.js.map
2021-10-01 09:38:36 -04:00
/***/ }),
/***/ 3702:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class BasicCredentialHandler {
constructor(username, password) {
this.username = username;
this.password = password;
}
prepareRequest(options) {
options.headers['Authorization'] =
'Basic ' +
Buffer.from(this.username + ':' + this.password).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
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) {
options.headers['Authorization'] = 'Bearer ' + this.token;
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
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) {
options.headers['Authorization'] =
'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
2021-09-26 15:31:45 -04:00
/***/ }),
/***/ 9925:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const http = __nccwpck_require__(8605);
const https = __nccwpck_require__(7211);
const pm = __nccwpck_require__(6443);
let tunnel;
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) {
let 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 new Promise(async (resolve, reject) => {
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) {
let 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 this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
}
get(requestUrl, additionalHeaders) {
return this.request('GET', requestUrl, null, additionalHeaders || {});
}
del(requestUrl, additionalHeaders) {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
}
post(requestUrl, data, additionalHeaders) {
return this.request('POST', requestUrl, data, additionalHeaders || {});
}
patch(requestUrl, data, additionalHeaders) {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
}
put(requestUrl, data, additionalHeaders) {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
}
head(requestUrl, additionalHeaders) {
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
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
*/
async getJson(requestUrl, additionalHeaders = {}) {
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
let res = await this.get(requestUrl, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async postJson(requestUrl, obj, additionalHeaders = {}) {
let 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);
let res = await this.post(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async putJson(requestUrl, obj, additionalHeaders = {}) {
let 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);
let res = await this.put(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async patchJson(requestUrl, obj, additionalHeaders = {}) {
let 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);
let res = await 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
*/
async request(verb, requestUrl, data, headers) {
if (this._disposed) {
throw new Error('Client has already been disposed.');
}
let parsedUrl = new URL(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
? this._maxRetries + 1
: 1;
let numTries = 0;
let response;
while (numTries < maxTries) {
response = await this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) {
authenticationHandler = this.handlers[i];
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 (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
this._allowRedirects &&
redirectsRemaining > 0) {
const redirectUrl = response.message.headers['location'];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
let 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.
await response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (let 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 = await this.requestRaw(info, data);
redirectsRemaining--;
}
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
await response.readBody();
await this._performExponentialBackoff(numTries);
}
}
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 new Promise((resolve, reject) => {
let callbackForResult = function (err, res) {
if (err) {
reject(err);
}
resolve(res);
};
this.requestRawWithCallback(info, data, callbackForResult);
});
}
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info, data, onResult) {
let socket;
if (typeof data === 'string') {
info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
let callbackCalled = false;
let handleResult = (err, res) => {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
};
let req = info.httpModule.request(info.options, (msg) => {
let res = new HttpClientResponse(msg);
handleResult(null, res);
});
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), null);
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err, null);
});
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) {
let 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) {
this.handlers.forEach(handler => {
handler.prepareRequest(info.options);
});
}
return info;
}
_mergeHeaders(headers) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
let proxyUrl = pm.getProxyUrl(parsedUrl);
let 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;
}
if (useProxy) {
// If using proxy, need tunnel
if (!tunnel) {
tunnel = __nccwpck_require__(4294);
}
const agentOptions = {
maxSockets: maxSockets,
keepAlive: this._keepAlive,
proxy: {
...((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: 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) {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
}
static dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
async _processResponse(res, options) {
return new Promise(async (resolve, reject) => {
const statusCode = res.message.statusCode;
const response = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == HttpCodes.NotFound) {
resolve(response);
}
let obj;
let contents;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, HttpClient.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 + ')';
}
let err = new HttpClientError(msg, statusCode);
err.result = response.result;
reject(err);
}
else {
resolve(response);
}
});
}
}
exports.HttpClient = HttpClient;
/***/ }),
/***/ 6443:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function getProxyUrl(reqUrl) {
let usingSsl = reqUrl.protocol === 'https:';
let proxyUrl;
if (checkBypass(reqUrl)) {
return proxyUrl;
}
let proxyVar;
if (usingSsl) {
proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
}
else {
proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
}
if (proxyVar) {
proxyUrl = new URL(proxyVar);
}
return proxyUrl;
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
let 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
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
// Compare request host against noproxy
for (let upperNoProxyItem of noProxy
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
/***/ }),
/***/ 3803:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
const fs = __nccwpck_require__(5747);
exports.FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
stat: fs.stat,
lstatSync: fs.lstatSync,
statSync: fs.statSync,
readdir: fs.readdir,
readdirSync: fs.readdirSync
};
function createFileSystemAdapter(fsMethods) {
if (fsMethods === undefined) {
return exports.FILE_SYSTEM_ADAPTER;
}
return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
}
exports.createFileSystemAdapter = createFileSystemAdapter;
/***/ }),
/***/ 8838:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
}
const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
const SUPPORTED_MAJOR_VERSION = 10;
const SUPPORTED_MINOR_VERSION = 10;
const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
/**
* IS `true` for Node.js 10.10 and greater.
*/
exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
/***/ }),
/***/ 5667:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Settings = exports.scandirSync = exports.scandir = void 0;
const async = __nccwpck_require__(4507);
const sync = __nccwpck_require__(9560);
const settings_1 = __nccwpck_require__(8662);
exports.Settings = settings_1.default;
function scandir(path, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === 'function') {
async.read(path, getSettings(), optionsOrSettingsOrCallback);
return;
}
async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
}
exports.scandir = scandir;
function scandirSync(path, optionsOrSettings) {
const settings = getSettings(optionsOrSettings);
return sync.read(path, settings);
}
exports.scandirSync = scandirSync;
function getSettings(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1.default) {
return settingsOrOptions;
}
return new settings_1.default(settingsOrOptions);
}
/***/ }),
/***/ 4507:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
const fsStat = __nccwpck_require__(109);
const rpl = __nccwpck_require__(5288);
const constants_1 = __nccwpck_require__(8838);
const utils = __nccwpck_require__(6297);
const common = __nccwpck_require__(3847);
function read(directory, settings, callback) {
if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
readdirWithFileTypes(directory, settings, callback);
return;
}
readdir(directory, settings, callback);
}
exports.read = read;
function readdirWithFileTypes(directory, settings, callback) {
settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
if (readdirError !== null) {
callFailureCallback(callback, readdirError);
return;
}
const entries = dirents.map((dirent) => ({
dirent,
name: dirent.name,
path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
}));
if (!settings.followSymbolicLinks) {
callSuccessCallback(callback, entries);
return;
}
const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
rpl(tasks, (rplError, rplEntries) => {
if (rplError !== null) {
callFailureCallback(callback, rplError);
return;
}
callSuccessCallback(callback, rplEntries);
});
});
}
exports.readdirWithFileTypes = readdirWithFileTypes;
function makeRplTaskEntry(entry, settings) {
return (done) => {
if (!entry.dirent.isSymbolicLink()) {
done(null, entry);
return;
}
settings.fs.stat(entry.path, (statError, stats) => {
if (statError !== null) {
if (settings.throwErrorOnBrokenSymbolicLink) {
done(statError);
return;
}
done(null, entry);
return;
}
entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
done(null, entry);
});
};
}
function readdir(directory, settings, callback) {
settings.fs.readdir(directory, (readdirError, names) => {
if (readdirError !== null) {
callFailureCallback(callback, readdirError);
return;
}
const tasks = names.map((name) => {
const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
return (done) => {
fsStat.stat(path, settings.fsStatSettings, (error, stats) => {
if (error !== null) {
done(error);
return;
}
const entry = {
name,
path,
dirent: utils.fs.createDirentFromStats(name, stats)
};
if (settings.stats) {
entry.stats = stats;
}
done(null, entry);
});
};
});
rpl(tasks, (rplError, entries) => {
if (rplError !== null) {
callFailureCallback(callback, rplError);
return;
}
callSuccessCallback(callback, entries);
});
});
}
exports.readdir = readdir;
function callFailureCallback(callback, error) {
callback(error);
}
function callSuccessCallback(callback, result) {
callback(null, result);
}
/***/ }),
/***/ 3847:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.joinPathSegments = void 0;
function joinPathSegments(a, b, separator) {
/**
* The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
*/
if (a.endsWith(separator)) {
return a + b;
}
return a + separator + b;
}
exports.joinPathSegments = joinPathSegments;
/***/ }),
/***/ 9560:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
const fsStat = __nccwpck_require__(109);
const constants_1 = __nccwpck_require__(8838);
const utils = __nccwpck_require__(6297);
const common = __nccwpck_require__(3847);
function read(directory, settings) {
if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
return readdirWithFileTypes(directory, settings);
}
return readdir(directory, settings);
}
exports.read = read;
function readdirWithFileTypes(directory, settings) {
const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
return dirents.map((dirent) => {
const entry = {
dirent,
name: dirent.name,
path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
};
if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
try {
const stats = settings.fs.statSync(entry.path);
entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
}
catch (error) {
if (settings.throwErrorOnBrokenSymbolicLink) {
throw error;
}
}
}
return entry;
});
}
exports.readdirWithFileTypes = readdirWithFileTypes;
function readdir(directory, settings) {
const names = settings.fs.readdirSync(directory);
return names.map((name) => {
const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
const stats = fsStat.statSync(entryPath, settings.fsStatSettings);
const entry = {
name,
path: entryPath,
dirent: utils.fs.createDirentFromStats(name, stats)
};
if (settings.stats) {
entry.stats = stats;
}
return entry;
});
}
exports.readdir = readdir;
/***/ }),
/***/ 8662:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const path = __nccwpck_require__(5622);
const fsStat = __nccwpck_require__(109);
const fs = __nccwpck_require__(3803);
class Settings {
constructor(_options = {}) {
this._options = _options;
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
this.fs = fs.createFileSystemAdapter(this._options.fs);
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
this.stats = this._getValue(this._options.stats, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
this.fsStatSettings = new fsStat.Settings({
followSymbolicLink: this.followSymbolicLinks,
fs: this.fs,
throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
});
}
_getValue(option, value) {
return option !== null && option !== void 0 ? option : value;
}
}
exports.default = Settings;
/***/ }),
/***/ 883:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDirentFromStats = void 0;
class DirentFromStats {
constructor(name, stats) {
this.name = name;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
}
function createDirentFromStats(name, stats) {
return new DirentFromStats(name, stats);
}
exports.createDirentFromStats = createDirentFromStats;
/***/ }),
/***/ 6297:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fs = void 0;
const fs = __nccwpck_require__(883);
exports.fs = fs;
/***/ }),
/***/ 2987:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
const fs = __nccwpck_require__(5747);
exports.FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
stat: fs.stat,
lstatSync: fs.lstatSync,
statSync: fs.statSync
};
function createFileSystemAdapter(fsMethods) {
if (fsMethods === undefined) {
return exports.FILE_SYSTEM_ADAPTER;
}
return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
}
exports.createFileSystemAdapter = createFileSystemAdapter;
/***/ }),
/***/ 109:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.statSync = exports.stat = exports.Settings = void 0;
const async = __nccwpck_require__(4147);
const sync = __nccwpck_require__(4527);
const settings_1 = __nccwpck_require__(2410);
exports.Settings = settings_1.default;
function stat(path, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === 'function') {
async.read(path, getSettings(), optionsOrSettingsOrCallback);
return;
}
async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
}
exports.stat = stat;
function statSync(path, optionsOrSettings) {
const settings = getSettings(optionsOrSettings);
return sync.read(path, settings);
}
exports.statSync = statSync;
function getSettings(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1.default) {
return settingsOrOptions;
}
return new settings_1.default(settingsOrOptions);
}
/***/ }),
/***/ 4147:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.read = void 0;
function read(path, settings, callback) {
settings.fs.lstat(path, (lstatError, lstat) => {
if (lstatError !== null) {
callFailureCallback(callback, lstatError);
return;
}
if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
callSuccessCallback(callback, lstat);
return;
}
settings.fs.stat(path, (statError, stat) => {
if (statError !== null) {
if (settings.throwErrorOnBrokenSymbolicLink) {
callFailureCallback(callback, statError);
return;
}
callSuccessCallback(callback, lstat);
return;
}
if (settings.markSymbolicLink) {
stat.isSymbolicLink = () => true;
}
callSuccessCallback(callback, stat);
});
});
}
exports.read = read;
function callFailureCallback(callback, error) {
callback(error);
}
function callSuccessCallback(callback, result) {
callback(null, result);
}
/***/ }),
/***/ 4527:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.read = void 0;
function read(path, settings) {
const lstat = settings.fs.lstatSync(path);
if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
return lstat;
}
try {
const stat = settings.fs.statSync(path);
if (settings.markSymbolicLink) {
stat.isSymbolicLink = () => true;
}
return stat;
}
catch (error) {
if (!settings.throwErrorOnBrokenSymbolicLink) {
return lstat;
}
throw error;
}
}
exports.read = read;
/***/ }),
/***/ 2410:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const fs = __nccwpck_require__(2987);
class Settings {
constructor(_options = {}) {
this._options = _options;
this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
this.fs = fs.createFileSystemAdapter(this._options.fs);
this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
}
_getValue(option, value) {
return option !== null && option !== void 0 ? option : value;
}
}
exports.default = Settings;
/***/ }),
/***/ 6026:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0;
const async_1 = __nccwpck_require__(7523);
const stream_1 = __nccwpck_require__(6737);
const sync_1 = __nccwpck_require__(3068);
const settings_1 = __nccwpck_require__(141);
exports.Settings = settings_1.default;
function walk(directory, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === 'function') {
new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
return;
}
new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
}
exports.walk = walk;
function walkSync(directory, optionsOrSettings) {
const settings = getSettings(optionsOrSettings);
const provider = new sync_1.default(directory, settings);
return provider.read();
}
exports.walkSync = walkSync;
function walkStream(directory, optionsOrSettings) {
const settings = getSettings(optionsOrSettings);
const provider = new stream_1.default(directory, settings);
return provider.read();
}
exports.walkStream = walkStream;
function getSettings(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1.default) {
return settingsOrOptions;
}
return new settings_1.default(settingsOrOptions);
}
/***/ }),
/***/ 7523:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const async_1 = __nccwpck_require__(5732);
class AsyncProvider {
constructor(_root, _settings) {
this._root = _root;
this._settings = _settings;
this._reader = new async_1.default(this._root, this._settings);
this._storage = [];
}
read(callback) {
this._reader.onError((error) => {
callFailureCallback(callback, error);
});
this._reader.onEntry((entry) => {
this._storage.push(entry);
});
this._reader.onEnd(() => {
callSuccessCallback(callback, this._storage);
});
this._reader.read();
}
}
exports.default = AsyncProvider;
function callFailureCallback(callback, error) {
callback(error);
}
function callSuccessCallback(callback, entries) {
callback(null, entries);
}
/***/ }),
/***/ 6737:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const stream_1 = __nccwpck_require__(2413);
const async_1 = __nccwpck_require__(5732);
class StreamProvider {
constructor(_root, _settings) {
this._root = _root;
this._settings = _settings;
this._reader = new async_1.default(this._root, this._settings);
this._stream = new stream_1.Readable({
objectMode: true,
read: () => { },
destroy: () => {
if (!this._reader.isDestroyed) {
this._reader.destroy();
}
}
});
}
read() {
this._reader.onError((error) => {
this._stream.emit('error', error);
});
this._reader.onEntry((entry) => {
this._stream.push(entry);
});
this._reader.onEnd(() => {
this._stream.push(null);
});
this._reader.read();
return this._stream;
}
}
exports.default = StreamProvider;
/***/ }),
/***/ 3068:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const sync_1 = __nccwpck_require__(3595);
class SyncProvider {
constructor(_root, _settings) {
this._root = _root;
this._settings = _settings;
this._reader = new sync_1.default(this._root, this._settings);
}
read() {
return this._reader.read();
}
}
exports.default = SyncProvider;
/***/ }),
/***/ 5732:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const events_1 = __nccwpck_require__(8614);
const fsScandir = __nccwpck_require__(5667);
const fastq = __nccwpck_require__(7340);
const common = __nccwpck_require__(7988);
const reader_1 = __nccwpck_require__(8311);
class AsyncReader extends reader_1.default {
constructor(_root, _settings) {
super(_root, _settings);
this._settings = _settings;
this._scandir = fsScandir.scandir;
this._emitter = new events_1.EventEmitter();
this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
this._isFatalError = false;
this._isDestroyed = false;
this._queue.drain = () => {
if (!this._isFatalError) {
this._emitter.emit('end');
}
};
}
read() {
this._isFatalError = false;
this._isDestroyed = false;
setImmediate(() => {
this._pushToQueue(this._root, this._settings.basePath);
});
return this._emitter;
}
get isDestroyed() {
return this._isDestroyed;
}
destroy() {
if (this._isDestroyed) {
throw new Error('The reader is already destroyed');
}
this._isDestroyed = true;
this._queue.killAndDrain();
}
onEntry(callback) {
this._emitter.on('entry', callback);
}
onError(callback) {
this._emitter.once('error', callback);
}
onEnd(callback) {
this._emitter.once('end', callback);
}
_pushToQueue(directory, base) {
const queueItem = { directory, base };
this._queue.push(queueItem, (error) => {
if (error !== null) {
this._handleError(error);
}
});
}
_worker(item, done) {
this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
if (error !== null) {
done(error, undefined);
return;
}
for (const entry of entries) {
this._handleEntry(entry, item.base);
}
done(null, undefined);
});
}
_handleError(error) {
if (this._isDestroyed || !common.isFatalError(this._settings, error)) {
return;
}
this._isFatalError = true;
this._isDestroyed = true;
this._emitter.emit('error', error);
}
_handleEntry(entry, base) {
if (this._isDestroyed || this._isFatalError) {
return;
}
const fullpath = entry.path;
if (base !== undefined) {
entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
}
if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
this._emitEntry(entry);
}
if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
}
}
_emitEntry(entry) {
this._emitter.emit('entry', entry);
}
}
exports.default = AsyncReader;
/***/ }),
/***/ 7988:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0;
function isFatalError(settings, error) {
if (settings.errorFilter === null) {
return true;
}
return !settings.errorFilter(error);
}
exports.isFatalError = isFatalError;
function isAppliedFilter(filter, value) {
return filter === null || filter(value);
}
exports.isAppliedFilter = isAppliedFilter;
function replacePathSegmentSeparator(filepath, separator) {
return filepath.split(/[/\\]/).join(separator);
}
exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
function joinPathSegments(a, b, separator) {
if (a === '') {
return b;
}
/**
* The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
*/
if (a.endsWith(separator)) {
return a + b;
}
return a + separator + b;
}
exports.joinPathSegments = joinPathSegments;
/***/ }),
/***/ 8311:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const common = __nccwpck_require__(7988);
class Reader {
constructor(_root, _settings) {
this._root = _root;
this._settings = _settings;
this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
}
}
exports.default = Reader;
/***/ }),
/***/ 3595:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const fsScandir = __nccwpck_require__(5667);
const common = __nccwpck_require__(7988);
const reader_1 = __nccwpck_require__(8311);
class SyncReader extends reader_1.default {
constructor() {
super(...arguments);
this._scandir = fsScandir.scandirSync;
this._storage = [];
this._queue = new Set();
}
read() {
this._pushToQueue(this._root, this._settings.basePath);
this._handleQueue();
return this._storage;
}
_pushToQueue(directory, base) {
this._queue.add({ directory, base });
}
_handleQueue() {
for (const item of this._queue.values()) {
this._handleDirectory(item.directory, item.base);
}
}
_handleDirectory(directory, base) {
try {
const entries = this._scandir(directory, this._settings.fsScandirSettings);
for (const entry of entries) {
this._handleEntry(entry, base);
}
}
catch (error) {
this._handleError(error);
}
}
_handleError(error) {
if (!common.isFatalError(this._settings, error)) {
return;
}
throw error;
}
_handleEntry(entry, base) {
const fullpath = entry.path;
if (base !== undefined) {
entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
}
if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
this._pushToStorage(entry);
}
if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
}
}
_pushToStorage(entry) {
this._storage.push(entry);
}
}
exports.default = SyncReader;
/***/ }),
/***/ 141:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const path = __nccwpck_require__(5622);
const fsScandir = __nccwpck_require__(5667);
class Settings {
constructor(_options = {}) {
this._options = _options;
this.basePath = this._getValue(this._options.basePath, undefined);
this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
this.deepFilter = this._getValue(this._options.deepFilter, null);
this.entryFilter = this._getValue(this._options.entryFilter, null);
this.errorFilter = this._getValue(this._options.errorFilter, null);
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
this.fsScandirSettings = new fsScandir.Settings({
followSymbolicLinks: this._options.followSymbolicLinks,
fs: this._options.fs,
pathSegmentSeparator: this._options.pathSegmentSeparator,
stats: this._options.stats,
throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
});
}
_getValue(option, value) {
return option !== null && option !== void 0 ? option : value;
}
}
exports.default = Settings;
/***/ }),
/***/ 334:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
return {
type: "token",
token: token,
tokenType
};
}
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
const createTokenAuth = function createTokenAuth(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
});
};
exports.createTokenAuth = createTokenAuth;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 6762:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
var universalUserAgent = __nccwpck_require__(5030);
var beforeAfterHook = __nccwpck_require__(3682);
2021-10-01 09:38:36 -04:00
var request = __nccwpck_require__(5712);
2021-09-26 15:31:45 -04:00
var graphql = __nccwpck_require__(8467);
var authToken = __nccwpck_require__(334);
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const VERSION = "3.5.1";
const _excluded = ["authStrategy"];
class Octokit {
constructor(options = {}) {
const hook = new beforeAfterHook.Collection();
const requestDefaults = {
baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
}; // prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.request.defaults(requestDefaults);
this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign({
debug: () => {},
info: () => {},
warn: console.warn.bind(console),
error: console.error.bind(console)
}, options.log);
this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
// (2) If only `options.auth` is set, use the default token authentication strategy.
// (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
// TODO: type `options.auth` based on `options.authStrategy`.
if (!options.authStrategy) {
if (!options.auth) {
// (1)
this.auth = async () => ({
type: "unauthenticated"
});
} else {
// (2)
const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
} else {
const {
authStrategy
} = options,
otherOptions = _objectWithoutProperties(options, _excluded);
const auth = authStrategy(Object.assign({
request: this.request,
log: this.log,
// we pass the current octokit instance as well as its constructor options
// to allow for authentication strategies that return a new octokit instance
// that shares the same internal state as the current one. The original
// requirement for this was the "event-octokit" authentication strategy
// of https://github.com/probot/octokit-auth-probot.
octokit: this,
octokitOptions: otherOptions
}, options.auth)); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
} // apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor;
classConstructor.plugins.forEach(plugin => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
userAgent: `${options.userAgent} ${defaults.userAgent}`
} : null));
}
};
return OctokitWithDefaults;
}
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);
return NewOctokit;
}
}
Octokit.VERSION = VERSION;
Octokit.plugins = [];
exports.Octokit = Octokit;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 9440:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
var isPlainObject = __nccwpck_require__(3287);
var universalUserAgent = __nccwpck_require__(5030);
function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach(key => {
if (isPlainObject.isPlainObject(options[key])) {
if (!(key in defaults)) Object.assign(result, {
[key]: options[key]
});else result[key] = mergeDeep(defaults[key], options[key]);
} else {
Object.assign(result, {
[key]: options[key]
});
}
});
return result;
}
function removeUndefinedProperties(obj) {
for (const key in obj) {
if (obj[key] === undefined) {
delete obj[key];
}
}
return obj;
}
function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? {
method,
url
} : {
url: method
}, options);
} else {
options = Object.assign({}, route);
} // lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
removeUndefinedProperties(options);
removeUndefinedProperties(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
return mergedOptions;
}
function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return url + separator + names.map(name => {
if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
}
return `${name}=${encodeURIComponent(parameters[name])}`;
}).join("&");
}
const urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
function omit(object, keysToOmit) {
return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
}
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key],
result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
} else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
} else {
return values.join(",");
}
} else {
return encodeReserved(literal);
}
});
}
function parse(options) {
// https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
let headers = Object.assign({}, options.headers);
let body;
let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url);
url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) {
url = options.baseUrl + url;
}
const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequest) {
if (options.mediaType.format) {
// e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
}
if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
return `application/vnd.github.${preview}-preview${format}`;
}).join(",");
}
} // for GET/HEAD requests, set URL query parameters from remaining parameters
// for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
} else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
} else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
} else {
headers["content-length"] = 0;
}
}
} // default content-type for JSON if body is set
if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8";
} // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
// fetch does not allow to set `content-length` header, but we can set body to an empty string
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = "";
} // Only return body/request keys if present
return Object.assign({
method,
url,
headers
}, typeof body !== "undefined" ? {
body
} : null, options.request ? {
request: options.request
} : null);
}
function endpointWithDefaults(defaults, route, options) {
return parse(merge(defaults, route, options));
}
function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS = merge(oldDefaults, newDefaults);
const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
return Object.assign(endpoint, {
DEFAULTS,
defaults: withDefaults.bind(null, DEFAULTS),
merge: merge.bind(null, DEFAULTS),
parse
});
}
const VERSION = "6.0.12";
const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property.
const DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: "",
previews: []
}
};
const endpoint = withDefaults(null, DEFAULTS);
exports.endpoint = endpoint;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 8467:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
2021-10-01 09:38:36 -04:00
var request = __nccwpck_require__(5712);
2021-09-26 15:31:45 -04:00
var universalUserAgent = __nccwpck_require__(5030);
const VERSION = "4.8.0";
function _buildMessageForResponseErrors(data) {
return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n");
}
class GraphqlResponseError extends Error {
constructor(request, headers, response) {
super(_buildMessageForResponseErrors(response));
this.request = request;
this.headers = headers;
this.response = response;
this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties.
this.errors = response.errors;
this.data = response.data; // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (options) {
if (typeof query === "string" && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
for (const key in options) {
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
}
}
const parsedOptions = typeof query === "string" ? Object.assign({
query
}, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
// https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
}
return request(requestOptions).then(response => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlResponseError(requestOptions, headers, response.data);
}
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.request.endpoint
});
}
const graphql$1 = withDefaults(request.request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`
},
method: "POST",
url: "/graphql"
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql"
});
}
exports.GraphqlResponseError = GraphqlResponseError;
exports.graphql = graphql$1;
exports.withCustomRequest = withCustomRequest;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 4193:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const VERSION = "2.16.5";
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Some list response that can be paginated have a different response structure
*
* They have a `total_count` key in the response (search also has `incomplete_results`,
* /installation/repositories also has `repository_selection`), as well as a key with
* the list of the items which name varies from endpoint to endpoint.
*
* Octokit normalizes these responses so that paginated results are always returned following
* the same structure. One challenge is that if the list response has only one page, no Link
* header is provided, so this header alone is not sufficient to check wether a response is
* paginated or not.
*
* We check if a "total_count" key is present in the response data, but also make sure that
* a "url" property is not, as the "Get the combined status for a specific ref" endpoint would
* otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
*/
function normalizePaginatedListResponse(response) {
// endpoints can respond with 204 if repository is empty
if (!response.data) {
return _objectSpread2(_objectSpread2({}, response), {}, {
data: []
});
}
const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way
// to retrieve the same information.
const incompleteResults = response.data.incomplete_results;
const repositorySelection = response.data.repository_selection;
const totalCount = response.data.total_count;
delete response.data.incomplete_results;
delete response.data.repository_selection;
delete response.data.total_count;
const namespaceKey = Object.keys(response.data)[0];
const data = response.data[namespaceKey];
response.data = data;
if (typeof incompleteResults !== "undefined") {
response.data.incomplete_results = incompleteResults;
}
if (typeof repositorySelection !== "undefined") {
response.data.repository_selection = repositorySelection;
}
response.data.total_count = totalCount;
return response;
}
function iterator(octokit, route, parameters) {
const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
const requestMethod = typeof route === "function" ? route : octokit.request;
const method = options.method;
const headers = options.headers;
let url = options.url;
return {
[Symbol.asyncIterator]: () => ({
async next() {
if (!url) return {
done: true
};
try {
const response = await requestMethod({
method,
url,
headers
});
const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return {
value: normalizedResponse
};
} catch (error) {
if (error.status !== 409) throw error;
url = "";
return {
value: {
status: 200,
headers: {},
data: []
}
};
}
}
})
};
}
function paginate(octokit, route, parameters, mapFn) {
if (typeof parameters === "function") {
mapFn = parameters;
parameters = undefined;
}
return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);
}
function gather(octokit, results, iterator, mapFn) {
return iterator.next().then(result => {
if (result.done) {
return results;
}
let earlyExit = false;
function done() {
earlyExit = true;
}
results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);
if (earlyExit) {
return results;
}
return gather(octokit, results, iterator, mapFn);
});
}
const composePaginateRest = Object.assign(paginate, {
iterator
});
const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{own
function isPaginatingEndpoint(arg) {
if (typeof arg === "string") {
return paginatingEndpoints.includes(arg);
} else {
return false;
}
}
/**
* @param octokit Octokit instance
* @param options Options passed to Octokit constructor
*/
function paginateRest(octokit) {
return {
paginate: Object.assign(paginate.bind(null, octokit), {
iterator: iterator.bind(null, octokit)
})
};
}
paginateRest.VERSION = VERSION;
exports.composePaginateRest = composePaginateRest;
exports.isPaginatingEndpoint = isPaginatingEndpoint;
exports.paginateRest = paginateRest;
exports.paginatingEndpoints = paginatingEndpoints;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 3044:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const Endpoints = {
actions: {
addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],
cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"],
createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],
deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],
disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],
downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],
downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],
downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],
enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],
getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"],
getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],
getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"],
getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"],
getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"],
getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, {
renamed: ["actions", "getGithubActionsPermissionsRepository"]
}],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],
getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"],
listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"],
listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],
listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"],
listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],
listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],
listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
retryWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/retry"],
reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"],
setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],
setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"],
setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"],
setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],
setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"]
},
activity: {
checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"],
getFeeds: ["GET /feeds"],
getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
getThread: ["GET /notifications/threads/{thread_id}"],
getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"],
listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
listNotificationsForAuthenticatedUser: ["GET /notifications"],
listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"],
listPublicEvents: ["GET /events"],
listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
listPublicEventsForUser: ["GET /users/{username}/events/public"],
listPublicOrgEvents: ["GET /orgs/{org}/events"],
listReceivedEventsForUser: ["GET /users/{username}/received_events"],
listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"],
listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"],
listReposStarredByAuthenticatedUser: ["GET /user/starred"],
listReposStarredByUser: ["GET /users/{username}/starred"],
listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
markNotificationsAsRead: ["PUT /notifications"],
markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"],
starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
},
apps: {
addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"],
checkToken: ["POST /applications/{client_id}/token"],
createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", {
mediaType: {
previews: ["corsair"]
}
}],
createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", {
mediaType: {
previews: ["corsair"]
}
}],
createFromManifest: ["POST /app-manifests/{code}/conversions"],
createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"],
deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
deleteInstallation: ["DELETE /app/installations/{installation_id}"],
deleteToken: ["DELETE /applications/{client_id}/token"],
getAuthenticated: ["GET /app"],
getBySlug: ["GET /apps/{app_slug}"],
getInstallation: ["GET /app/installations/{installation_id}"],
getOrgInstallation: ["GET /orgs/{org}/installation"],
getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"],
getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"],
getUserInstallation: ["GET /users/{username}/installation"],
getWebhookConfigForApp: ["GET /app/hook/config"],
getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],
listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"],
listInstallations: ["GET /app/installations"],
listInstallationsForAuthenticatedUser: ["GET /user/installations"],
listPlans: ["GET /marketplace_listing/plans"],
listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
listReposAccessibleToInstallation: ["GET /installation/repositories"],
listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"],
listWebhookDeliveries: ["GET /app/hook/deliveries"],
redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"],
removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],
resetToken: ["PATCH /applications/{client_id}/token"],
revokeInstallationAccessToken: ["DELETE /installation/token"],
scopeToken: ["POST /applications/{client_id}/token/scoped"],
suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"],
updateWebhookConfigForApp: ["PATCH /app/hook/config"]
},
billing: {
getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"],
getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"],
getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"],
getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"]
},
checks: {
create: ["POST /repos/{owner}/{repo}/check-runs"],
createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],
listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],
listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],
setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"],
update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
},
codeScanning: {
deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],
getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, {
renamedParameters: {
alert_id: "alert_number"
}
}],
getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],
getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],
listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, {
renamed: ["codeScanning", "listAlertInstances"]
}],
listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],
uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
},
codesOfConduct: {
getAllCodesOfConduct: ["GET /codes_of_conduct"],
getConductCode: ["GET /codes_of_conduct/{key}"],
getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", {
mediaType: {
previews: ["scarlet-witch"]
}
}]
},
emojis: {
get: ["GET /emojis"]
},
enterpriseAdmin: {
disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"],
getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"],
listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"],
setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"],
setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"],
setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"]
},
gists: {
checkIsStarred: ["GET /gists/{gist_id}/star"],
create: ["POST /gists"],
createComment: ["POST /gists/{gist_id}/comments"],
delete: ["DELETE /gists/{gist_id}"],
deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
fork: ["POST /gists/{gist_id}/forks"],
get: ["GET /gists/{gist_id}"],
getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
getRevision: ["GET /gists/{gist_id}/{sha}"],
list: ["GET /gists"],
listComments: ["GET /gists/{gist_id}/comments"],
listCommits: ["GET /gists/{gist_id}/commits"],
listForUser: ["GET /users/{username}/gists"],
listForks: ["GET /gists/{gist_id}/forks"],
listPublic: ["GET /gists/public"],
listStarred: ["GET /gists/starred"],
star: ["PUT /gists/{gist_id}/star"],
unstar: ["DELETE /gists/{gist_id}/star"],
update: ["PATCH /gists/{gist_id}"],
updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
},
git: {
createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
createRef: ["POST /repos/{owner}/{repo}/git/refs"],
createTag: ["POST /repos/{owner}/{repo}/git/tags"],
createTree: ["POST /repos/{owner}/{repo}/git/trees"],
deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
},
gitignore: {
getAllTemplates: ["GET /gitignore/templates"],
getTemplate: ["GET /gitignore/templates/{name}"]
},
interactions: {
getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, {
renamed: ["interactions", "getRestrictionsForAuthenticatedUser"]
}],
removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"],
removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, {
renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"]
}],
setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, {
renamed: ["interactions", "setRestrictionsForAuthenticatedUser"]
}]
},
issues: {
addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
create: ["POST /repos/{owner}/{repo}/issues"],
createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],
createLabel: ["POST /repos/{owner}/{repo}/labels"],
createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],
deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],
get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
list: ["GET /issues"],
listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],
listForAuthenticatedUser: ["GET /user/issues"],
listForOrg: ["GET /orgs/{org}/issues"],
listForRepo: ["GET /repos/{owner}/{repo}/issues"],
listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],
listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],
listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],
removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],
setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]
},
licenses: {
get: ["GET /licenses/{license}"],
getAllCommonlyUsed: ["GET /licenses"],
getForRepo: ["GET /repos/{owner}/{repo}/license"]
},
markdown: {
render: ["POST /markdown"],
renderRaw: ["POST /markdown/raw", {
headers: {
"content-type": "text/plain; charset=utf-8"
}
}]
},
meta: {
get: ["GET /meta"],
getOctocat: ["GET /octocat"],
getZen: ["GET /zen"],
root: ["GET /"]
},
migrations: {
cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"],
deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"],
downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"],
getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"],
getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
getImportStatus: ["GET /repos/{owner}/{repo}/import"],
getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
listForAuthenticatedUser: ["GET /user/migrations"],
listForOrg: ["GET /orgs/{org}/migrations"],
listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
listReposForUser: ["GET /user/migrations/{migration_id}/repositories"],
mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
startForAuthenticatedUser: ["POST /user/migrations"],
startForOrg: ["POST /orgs/{org}/migrations"],
startImport: ["PUT /repos/{owner}/{repo}/import"],
unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],
unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"],
updateImport: ["PATCH /repos/{owner}/{repo}/import"]
},
orgs: {
blockUser: ["PUT /orgs/{org}/blocks/{username}"],
cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"],
createInvitation: ["POST /orgs/{org}/invitations"],
createWebhook: ["POST /orgs/{org}/hooks"],
deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
get: ["GET /orgs/{org}"],
getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],
list: ["GET /organizations"],
listAppInstallations: ["GET /orgs/{org}/installations"],
listBlockedUsers: ["GET /orgs/{org}/blocks"],
listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
listForAuthenticatedUser: ["GET /user/orgs"],
listForUser: ["GET /users/{username}/orgs"],
listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
listMembers: ["GET /orgs/{org}/members"],
listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
listPendingInvitations: ["GET /orgs/{org}/invitations"],
listPublicMembers: ["GET /orgs/{org}/public_members"],
listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
listWebhooks: ["GET /orgs/{org}/hooks"],
pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
removeMember: ["DELETE /orgs/{org}/members/{username}"],
removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"],
removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"],
setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"],
unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
update: ["PATCH /orgs/{org}"],
updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"],
updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
},
packages: {
deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"],
deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],
deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"],
deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"]
}],
getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]
}],
getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"],
getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"],
getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"],
getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"],
getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
listPackagesForAuthenticatedUser: ["GET /user/packages"],
listPackagesForOrganization: ["GET /orgs/{org}/packages"],
listPackagesForUser: ["GET /users/{username}/packages"],
restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]
},
projects: {
addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
createCard: ["POST /projects/columns/{column_id}/cards"],
createColumn: ["POST /projects/{project_id}/columns"],
createForAuthenticatedUser: ["POST /user/projects"],
createForOrg: ["POST /orgs/{org}/projects"],
createForRepo: ["POST /repos/{owner}/{repo}/projects"],
delete: ["DELETE /projects/{project_id}"],
deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
deleteColumn: ["DELETE /projects/columns/{column_id}"],
get: ["GET /projects/{project_id}"],
getCard: ["GET /projects/columns/cards/{card_id}"],
getColumn: ["GET /projects/columns/{column_id}"],
getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"],
listCards: ["GET /projects/columns/{column_id}/cards"],
listCollaborators: ["GET /projects/{project_id}/collaborators"],
listColumns: ["GET /projects/{project_id}/columns"],
listForOrg: ["GET /orgs/{org}/projects"],
listForRepo: ["GET /repos/{owner}/{repo}/projects"],
listForUser: ["GET /users/{username}/projects"],
moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
moveColumn: ["POST /projects/columns/{column_id}/moves"],
removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"],
update: ["PATCH /projects/{project_id}"],
updateCard: ["PATCH /projects/columns/cards/{card_id}"],
updateColumn: ["PATCH /projects/columns/{column_id}"]
},
pulls: {
checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
create: ["POST /repos/{owner}/{repo}/pulls"],
createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],
createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],
get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
list: ["GET /repos/{owner}/{repo}/pulls"],
listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],
listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],
update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],
updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]
},
rateLimit: {
get: ["GET /rate_limit"]
},
reactions: {
createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteLegacy: ["DELETE /reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}, {
deprecated: "octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy"
}],
listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}]
},
repos: {
acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"],
addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"],
compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"],
createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
createForAuthenticatedUser: ["POST /user/repos"],
createFork: ["POST /repos/{owner}/{repo}/forks"],
createInOrg: ["POST /orgs/{org}/repos"],
createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"],
createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
createPagesSite: ["POST /repos/{owner}/{repo}/pages", {
mediaType: {
previews: ["switcheroo"]
}
}],
createRelease: ["POST /repos/{owner}/{repo}/releases"],
createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", {
mediaType: {
previews: ["baptiste"]
}
}],
createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"],
delete: ["DELETE /repos/{owner}/{repo}"],
deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],
deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],
deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],
deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", {
mediaType: {
previews: ["switcheroo"]
}
}],
deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],
deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"],
disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"],
disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],
downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, {
renamed: ["repos", "downloadZipballArchive"]
}],
downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"],
enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"],
enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"],
get: ["GET /repos/{owner}/{repo}"],
getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
getAllTopics: ["GET /repos/{owner}/{repo}/topics", {
mediaType: {
previews: ["mercy"]
}
}],
getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],
getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"],
getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],
getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"],
getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
getPages: ["GET /repos/{owner}/{repo}/pages"],
getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
getReadme: ["GET /repos/{owner}/{repo}/readme"],
getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],
getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],
getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],
getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],
listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
listBranches: ["GET /repos/{owner}/{repo}/branches"],
listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],
listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],
listCommits: ["GET /repos/{owner}/{repo}/commits"],
listContributors: ["GET /repos/{owner}/{repo}/contributors"],
listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
listForAuthenticatedUser: ["GET /user/repos"],
listForOrg: ["GET /orgs/{org}/repos"],
listForUser: ["GET /users/{username}/repos"],
listForks: ["GET /repos/{owner}/{repo}/forks"],
listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
listLanguages: ["GET /repos/{owner}/{repo}/languages"],
listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
listPublic: ["GET /repositories"],
listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],
listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],
listReleases: ["GET /repos/{owner}/{repo}/releases"],
listTags: ["GET /repos/{owner}/{repo}/tags"],
listTeams: ["GET /repos/{owner}/{repo}/teams"],
listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],
listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
merge: ["POST /repos/{owner}/{repo}/merges"],
mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"],
removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", {
mediaType: {
previews: ["mercy"]
}
}],
requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
transfer: ["POST /repos/{owner}/{repo}/transfer"],
update: ["PATCH /repos/{owner}/{repo}"],
updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],
updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],
updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],
updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, {
renamed: ["repos", "updateStatusCheckProtection"]
}],
updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],
uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", {
baseUrl: "https://uploads.github.com"
}]
},
search: {
code: ["GET /search/code"],
commits: ["GET /search/commits", {
mediaType: {
previews: ["cloak"]
}
}],
issuesAndPullRequests: ["GET /search/issues"],
labels: ["GET /search/labels"],
repos: ["GET /search/repositories"],
topics: ["GET /search/topics", {
mediaType: {
previews: ["mercy"]
}
}],
users: ["GET /search/users"]
},
secretScanning: {
getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],
listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"]
},
teams: {
addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],
addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
create: ["POST /orgs/{org}/teams"],
createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
getByName: ["GET /orgs/{org}/teams/{team_slug}"],
getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],
list: ["GET /orgs/{org}/teams"],
listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
listForAuthenticatedUser: ["GET /user/teams"],
listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"],
listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],
removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
},
users: {
addEmailForAuthenticated: ["POST /user/emails"],
block: ["PUT /user/blocks/{username}"],
checkBlocked: ["GET /user/blocks/{username}"],
checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
createGpgKeyForAuthenticated: ["POST /user/gpg_keys"],
createPublicSshKeyForAuthenticated: ["POST /user/keys"],
deleteEmailForAuthenticated: ["DELETE /user/emails"],
deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"],
deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"],
follow: ["PUT /user/following/{username}"],
getAuthenticated: ["GET /user"],
getByUsername: ["GET /users/{username}"],
getContextForUser: ["GET /users/{username}/hovercard"],
getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"],
getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"],
list: ["GET /users"],
listBlockedByAuthenticated: ["GET /user/blocks"],
listEmailsForAuthenticated: ["GET /user/emails"],
listFollowedByAuthenticated: ["GET /user/following"],
listFollowersForAuthenticatedUser: ["GET /user/followers"],
listFollowersForUser: ["GET /users/{username}/followers"],
listFollowingForUser: ["GET /users/{username}/following"],
listGpgKeysForAuthenticated: ["GET /user/gpg_keys"],
listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
listPublicEmailsForAuthenticated: ["GET /user/public_emails"],
listPublicKeysForUser: ["GET /users/{username}/keys"],
listPublicSshKeysForAuthenticated: ["GET /user/keys"],
setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"],
unblock: ["DELETE /user/blocks/{username}"],
unfollow: ["DELETE /user/following/{username}"],
updateAuthenticated: ["PATCH /user"]
}
};
const VERSION = "5.11.2";
function endpointsToMethods(octokit, endpointsMap) {
const newMethods = {};
for (const [scope, endpoints] of Object.entries(endpointsMap)) {
for (const [methodName, endpoint] of Object.entries(endpoints)) {
const [route, defaults, decorations] = endpoint;
const [method, url] = route.split(/ /);
const endpointDefaults = Object.assign({
method,
url
}, defaults);
if (!newMethods[scope]) {
newMethods[scope] = {};
}
const scopeMethods = newMethods[scope];
if (decorations) {
scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);
continue;
}
scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);
}
}
return newMethods;
}
function decorate(octokit, scope, methodName, defaults, decorations) {
const requestWithDefaults = octokit.request.defaults(defaults);
/* istanbul ignore next */
function withDecorations(...args) {
// @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`
if (decorations.mapToData) {
options = Object.assign({}, options, {
data: options[decorations.mapToData],
[decorations.mapToData]: undefined
});
return requestWithDefaults(options);
}
if (decorations.renamed) {
const [newScope, newMethodName] = decorations.renamed;
octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);
}
if (decorations.deprecated) {
octokit.log.warn(decorations.deprecated);
}
if (decorations.renamedParameters) {
// @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
const options = requestWithDefaults.endpoint.merge(...args);
for (const [name, alias] of Object.entries(decorations.renamedParameters)) {
if (name in options) {
octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`);
if (!(alias in options)) {
options[alias] = options[name];
}
delete options[name];
}
}
return requestWithDefaults(options);
} // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
return requestWithDefaults(...args);
}
return Object.assign(withDecorations, requestWithDefaults);
}
function restEndpointMethods(octokit) {
const api = endpointsToMethods(octokit, Endpoints);
return {
rest: api
};
}
restEndpointMethods.VERSION = VERSION;
function legacyRestEndpointMethods(octokit) {
const api = endpointsToMethods(octokit, Endpoints);
return _objectSpread2(_objectSpread2({}, api), {}, {
rest: api
});
}
legacyRestEndpointMethods.VERSION = VERSION;
exports.legacyRestEndpointMethods = legacyRestEndpointMethods;
exports.restEndpointMethods = restEndpointMethods;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 537:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deprecation = __nccwpck_require__(8932);
var once = _interopDefault(__nccwpck_require__(1223));
const logOnceCode = once(deprecation => console.warn(deprecation));
const logOnceHeaders = once(deprecation => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
let headers;
if ("headers" in options && typeof options.headers !== "undefined") {
headers = options.headers;
}
if ("response" in options) {
this.response = options.response;
headers = options.response.headers;
} // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy; // deprecations
Object.defineProperty(this, "code", {
get() {
logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
Object.defineProperty(this, "headers", {
get() {
logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
return headers || {};
}
});
}
}
exports.RequestError = RequestError;
//# sourceMappingURL=index.js.map
/***/ }),
2021-10-01 09:38:36 -04:00
/***/ 5712:
2021-09-26 15:31:45 -04:00
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var endpoint = __nccwpck_require__(9440);
var universalUserAgent = __nccwpck_require__(5030);
var isPlainObject = __nccwpck_require__(3287);
var nodeFetch = _interopDefault(__nccwpck_require__(1768));
var requestError = __nccwpck_require__(537);
const VERSION = "5.6.1";
function getBufferResponse(response) {
return response.arrayBuffer();
}
function fetchWrapper(requestOptions) {
const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
requestOptions.body = JSON.stringify(requestOptions.body);
}
let headers = {};
let status;
let url;
const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;
return fetch(requestOptions.url, Object.assign({
method: requestOptions.method,
body: requestOptions.body,
headers: requestOptions.headers,
redirect: requestOptions.redirect
}, // `requestOptions.request.agent` type is incompatible
// see https://github.com/octokit/types.ts/pull/264
requestOptions.request)).then(async response => {
url = response.url;
status = response.status;
for (const keyAndValue of response.headers) {
headers[keyAndValue[0]] = keyAndValue[1];
}
if ("deprecation" in headers) {
const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
const deprecationLink = matches && matches.pop();
log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
}
if (status === 204 || status === 205) {
return;
} // GitHub API returns 200 for HEAD requests
if (requestOptions.method === "HEAD") {
if (status < 400) {
return;
}
throw new requestError.RequestError(response.statusText, status, {
response: {
url,
status,
headers,
data: undefined
},
request: requestOptions
});
}
if (status === 304) {
throw new requestError.RequestError("Not modified", status, {
response: {
url,
status,
headers,
data: await getResponseData(response)
},
request: requestOptions
});
}
if (status >= 400) {
const data = await getResponseData(response);
const error = new requestError.RequestError(toErrorMessage(data), status, {
response: {
url,
status,
headers,
data
},
request: requestOptions
});
throw error;
}
return getResponseData(response);
}).then(data => {
return {
status,
url,
headers,
data
};
}).catch(error => {
if (error instanceof requestError.RequestError) throw error;
throw new requestError.RequestError(error.message, 500, {
request: requestOptions
});
});
}
async function getResponseData(response) {
const contentType = response.headers.get("content-type");
if (/application\/json/.test(contentType)) {
return response.json();
}
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
return response.text();
}
return getBufferResponse(response);
}
function toErrorMessage(data) {
if (typeof data === "string") return data; // istanbul ignore else - just in case
if ("message" in data) {
if (Array.isArray(data.errors)) {
return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
}
return data.message;
} // istanbul ignore next - just in case
return `Unknown error: ${JSON.stringify(data)}`;
}
function withDefaults(oldEndpoint, newDefaults) {
const endpoint = oldEndpoint.defaults(newDefaults);
const newApi = function (route, parameters) {
const endpointOptions = endpoint.merge(route, parameters);
if (!endpointOptions.request || !endpointOptions.request.hook) {
return fetchWrapper(endpoint.parse(endpointOptions));
}
const request = (route, parameters) => {
return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
};
Object.assign(request, {
endpoint,
defaults: withDefaults.bind(null, endpoint)
});
return endpointOptions.request.hook(request, endpointOptions);
};
return Object.assign(newApi, {
endpoint,
defaults: withDefaults.bind(null, endpoint)
});
}
const request = withDefaults(endpoint.endpoint, {
headers: {
"user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
}
});
exports.request = request;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 1768:
/***/ ((module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Stream = _interopDefault(__nccwpck_require__(2413));
var http = _interopDefault(__nccwpck_require__(8605));
var Url = _interopDefault(__nccwpck_require__(8835));
var whatwgUrl = _interopDefault(__nccwpck_require__(301));
var https = _interopDefault(__nccwpck_require__(7211));
var zlib = _interopDefault(__nccwpck_require__(8761));
// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
// fix for "Readable" isn't a named export issue
const Readable = Stream.Readable;
const BUFFER = Symbol('buffer');
const TYPE = Symbol('type');
class Blob {
constructor() {
this[TYPE] = '';
const blobParts = arguments[0];
const options = arguments[1];
const buffers = [];
let size = 0;
if (blobParts) {
const a = blobParts;
const length = Number(a.length);
for (let i = 0; i < length; i++) {
const element = a[i];
let buffer;
if (element instanceof Buffer) {
buffer = element;
} else if (ArrayBuffer.isView(element)) {
buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
} else if (element instanceof ArrayBuffer) {
buffer = Buffer.from(element);
} else if (element instanceof Blob) {
buffer = element[BUFFER];
} else {
buffer = Buffer.from(typeof element === 'string' ? element : String(element));
}
size += buffer.length;
buffers.push(buffer);
}
}
this[BUFFER] = Buffer.concat(buffers);
let type = options && options.type !== undefined && String(options.type).toLowerCase();
if (type && !/[^\u0020-\u007E]/.test(type)) {
this[TYPE] = type;
}
}
get size() {
return this[BUFFER].length;
}
get type() {
return this[TYPE];
}
text() {
return Promise.resolve(this[BUFFER].toString());
}
arrayBuffer() {
const buf = this[BUFFER];
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
return Promise.resolve(ab);
}
stream() {
const readable = new Readable();
readable._read = function () {};
readable.push(this[BUFFER]);
readable.push(null);
return readable;
}
toString() {
return '[object Blob]';
}
slice() {
const size = this.size;
const start = arguments[0];
const end = arguments[1];
let relativeStart, relativeEnd;
if (start === undefined) {
relativeStart = 0;
} else if (start < 0) {
relativeStart = Math.max(size + start, 0);
} else {
relativeStart = Math.min(start, size);
}
if (end === undefined) {
relativeEnd = size;
} else if (end < 0) {
relativeEnd = Math.max(size + end, 0);
} else {
relativeEnd = Math.min(end, size);
}
const span = Math.max(relativeEnd - relativeStart, 0);
const buffer = this[BUFFER];
const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
const blob = new Blob([], { type: arguments[2] });
blob[BUFFER] = slicedBuffer;
return blob;
}
}
Object.defineProperties(Blob.prototype, {
size: { enumerable: true },
type: { enumerable: true },
slice: { enumerable: true }
});
Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
value: 'Blob',
writable: false,
enumerable: false,
configurable: true
});
/**
* fetch-error.js
*
* FetchError interface for operational errors
*/
/**
* Create FetchError instance
*
* @param String message Error message for human
* @param String type Error type for machine
* @param String systemError For Node.js system error
* @return FetchError
*/
function FetchError(message, type, systemError) {
Error.call(this, message);
this.message = message;
this.type = type;
// when err.type is `system`, err.code contains system error code
if (systemError) {
this.code = this.errno = systemError.code;
}
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
}
FetchError.prototype = Object.create(Error.prototype);
FetchError.prototype.constructor = FetchError;
FetchError.prototype.name = 'FetchError';
let convert;
try {
convert = __nccwpck_require__(2877).convert;
} catch (e) {}
const INTERNALS = Symbol('Body internals');
// fix an issue where "PassThrough" isn't a named export for node <10
const PassThrough = Stream.PassThrough;
/**
* Body mixin
*
* Ref: https://fetch.spec.whatwg.org/#body
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
function Body(body) {
var _this = this;
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$size = _ref.size;
let size = _ref$size === undefined ? 0 : _ref$size;
var _ref$timeout = _ref.timeout;
let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
if (body == null) {
// body is undefined or null
body = null;
} else if (isURLSearchParams(body)) {
// body is a URLSearchParams
body = Buffer.from(body.toString());
} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
// body is ArrayBuffer
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
// body is ArrayBufferView
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream) ; else {
// none of the above
// coerce to string then buffer
body = Buffer.from(String(body));
}
this[INTERNALS] = {
body,
disturbed: false,
error: null
};
this.size = size;
this.timeout = timeout;
if (body instanceof Stream) {
body.on('error', function (err) {
const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
_this[INTERNALS].error = error;
});
}
}
Body.prototype = {
get body() {
return this[INTERNALS].body;
},
get bodyUsed() {
return this[INTERNALS].disturbed;
},
/**
* Decode response as ArrayBuffer
*
* @return Promise
*/
arrayBuffer() {
return consumeBody.call(this).then(function (buf) {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
});
},
/**
* Return raw response as Blob
*
* @return Promise
*/
blob() {
let ct = this.headers && this.headers.get('content-type') || '';
return consumeBody.call(this).then(function (buf) {
return Object.assign(
// Prevent copying
new Blob([], {
type: ct.toLowerCase()
}), {
[BUFFER]: buf
});
});
},
/**
* Decode response as json
*
* @return Promise
*/
json() {
var _this2 = this;
return consumeBody.call(this).then(function (buffer) {
try {
return JSON.parse(buffer.toString());
} catch (err) {
return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
}
});
},
/**
* Decode response as text
*
* @return Promise
*/
text() {
return consumeBody.call(this).then(function (buffer) {
return buffer.toString();
});
},
/**
* Decode response as buffer (non-spec api)
*
* @return Promise
*/
buffer() {
return consumeBody.call(this);
},
/**
* Decode response as text, while automatically detecting the encoding and
* trying to decode to UTF-8 (non-spec api)
*
* @return Promise
*/
textConverted() {
var _this3 = this;
return consumeBody.call(this).then(function (buffer) {
return convertBody(buffer, _this3.headers);
});
}
};
// 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 }
});
Body.mixIn = function (proto) {
for (const name of Object.getOwnPropertyNames(Body.prototype)) {
// istanbul ignore else: future proof
if (!(name in proto)) {
const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
Object.defineProperty(proto, name, desc);
}
}
};
/**
* Consume and convert an entire Body to a Buffer.
*
* Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
*
* @return Promise
*/
function consumeBody() {
var _this4 = this;
if (this[INTERNALS].disturbed) {
return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
}
this[INTERNALS].disturbed = true;
if (this[INTERNALS].error) {
return Body.Promise.reject(this[INTERNALS].error);
}
let body = this.body;
// body is null
if (body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is blob
if (isBlob(body)) {
body = body.stream();
}
// body is buffer
if (Buffer.isBuffer(body)) {
return Body.Promise.resolve(body);
}
// istanbul ignore if: should never happen
if (!(body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise(function (resolve, reject) {
let resTimeout;
// allow timeout on slow response body
if (_this4.timeout) {
resTimeout = setTimeout(function () {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
}, _this4.timeout);
}
// handle stream errors
body.on('error', function (err) {
if (err.name === 'AbortError') {
// if the request was aborted, reject with this Error
abort = true;
reject(err);
} else {
// other errors, such as incorrect content-encoding
reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
}
});
body.on('data', function (chunk) {
if (abort || chunk === null) {
return;
}
if (_this4.size && accumBytes + chunk.length > _this4.size) {
abort = true;
reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
body.on('end', function () {
if (abort) {
return;
}
clearTimeout(resTimeout);
try {
resolve(Buffer.concat(accum, accumBytes));
} catch (err) {
// handle streams that have accumulated too much data (issue #414)
reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
}
});
});
}
/**
* Detect buffer encoding and convert to target encoding
* ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
*
* @param Buffer buffer Incoming buffer
* @param String encoding Target encoding
* @return String
*/
function convertBody(buffer, headers) {
if (typeof convert !== 'function') {
throw new Error('The package `encoding` must be installed to use the textConverted() function');
}
const ct = headers.get('content-type');
let charset = 'utf-8';
let res, str;
// header
if (ct) {
res = /charset=([^;]*)/i.exec(ct);
}
// no charset in content type, peek at response body for at most 1024 bytes
str = buffer.slice(0, 1024).toString();
// html5
if (!res && str) {
res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
}
// html4
if (!res && str) {
res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
if (!res) {
res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
if (res) {
res.pop(); // drop last quote
}
}
if (res) {
res = /charset=(.*)/i.exec(res.pop());
}
}
// xml
if (!res && str) {
res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
}
// found charset
if (res) {
charset = res.pop();
// prevent decode issues when sites use incorrect encoding
// ref: https://hsivonen.fi/encoding-menu/
if (charset === 'gb2312' || charset === 'gbk') {
charset = 'gb18030';
}
}
// turn raw buffers into a single utf-8 buffer
return convert(buffer, 'UTF-8', charset).toString();
}
/**
* Detect a URLSearchParams object
* ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
*
* @param Object obj Object to detect by type or brand
* @return String
*/
function isURLSearchParams(obj) {
// Duck-typing as a necessary condition.
if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
return false;
}
// Brand-checking and more duck-typing as optional condition.
return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
}
/**
* Check if `obj` is a W3C `Blob` object (which `File` inherits from)
* @param {*} obj
* @return {boolean}
*/
function isBlob(obj) {
return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
}
/**
* Clone body given Res/Req instance
*
* @param Mixed instance Response or Request instance
* @return Mixed
*/
function clone(instance) {
let p1, p2;
let body = instance.body;
// 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 Stream && typeof body.getBoundary !== 'function') {
// tee instance body
p1 = new PassThrough();
p2 = new PassThrough();
body.pipe(p1);
body.pipe(p2);
// set instance body to teed body and return the other teed body
instance[INTERNALS].body = p1;
body = p2;
}
return body;
}
/**
* 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 Mixed instance Any options.body input
*/
function extractContentType(body) {
if (body === null) {
// body is null
return null;
} else if (typeof body === 'string') {
// body is string
return 'text/plain;charset=UTF-8';
} else if (isURLSearchParams(body)) {
// body is a URLSearchParams
return 'application/x-www-form-urlencoded;charset=UTF-8';
} else if (isBlob(body)) {
// body is blob
return body.type || null;
} else if (Buffer.isBuffer(body)) {
// body is buffer
return null;
} else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
// body is ArrayBuffer
return null;
} else if (ArrayBuffer.isView(body)) {
// body is ArrayBufferView
return null;
} else if (typeof body.getBoundary === 'function') {
// detect form data input from form-data module
return `multipart/form-data;boundary=${body.getBoundary()}`;
} else if (body instanceof Stream) {
// body is stream
// can't really do much about this
return null;
} else {
// 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 Body instance Instance of Body
* @return Number? Number of bytes, or null if not possible
*/
function getTotalBytes(instance) {
const body = instance.body;
if (body === null) {
// body is null
return 0;
} else if (isBlob(body)) {
return body.size;
} else if (Buffer.isBuffer(body)) {
// body is buffer
return body.length;
} else if (body && typeof body.getLengthSync === 'function') {
// detect form data input from form-data module
if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
body.hasKnownLength && body.hasKnownLength()) {
// 2.x
return body.getLengthSync();
}
return null;
} else {
// body is stream
return null;
}
}
/**
* Write a Body to a Node.js WritableStream (e.g. http.Request) object.
*
* @param Body instance Instance of Body
* @return Void
*/
function writeToStream(dest, instance) {
const body = instance.body;
if (body === null) {
// body is null
dest.end();
} else if (isBlob(body)) {
body.stream().pipe(dest);
} else if (Buffer.isBuffer(body)) {
// body is buffer
dest.write(body);
dest.end();
} else {
// body is stream
body.pipe(dest);
}
}
// expose Promise
Body.Promise = global.Promise;
/**
* headers.js
*
* Headers class offers convenient helpers
*/
const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
function validateName(name) {
name = `${name}`;
if (invalidTokenRegex.test(name) || name === '') {
throw new TypeError(`${name} is not a legal HTTP header name`);
}
}
function validateValue(value) {
value = `${value}`;
if (invalidHeaderCharRegex.test(value)) {
throw new TypeError(`${value} is not a legal HTTP header value`);
}
}
/**
* Find the key in the map object given a header name.
*
* Returns undefined if not found.
*
* @param String name Header name
* @return String|Undefined
*/
function find(map, name) {
name = name.toLowerCase();
for (const key in map) {
if (key.toLowerCase() === name) {
return key;
}
}
return undefined;
}
const MAP = Symbol('map');
class Headers {
/**
* Headers class
*
* @param Object headers Response headers
* @return Void
*/
constructor() {
let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
this[MAP] = Object.create(null);
if (init instanceof Headers) {
const rawHeaders = init.raw();
const headerNames = Object.keys(rawHeaders);
for (const headerName of headerNames) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value);
}
}
return;
}
// We don't worry about converting prop to ByteString here as append()
// will handle it.
if (init == null) ; else if (typeof init === 'object') {
const method = init[Symbol.iterator];
if (method != null) {
if (typeof method !== 'function') {
throw new TypeError('Header pairs must be iterable');
}
// sequence<sequence<ByteString>>
// Note: per spec we have to first exhaust the lists then process them
const pairs = [];
for (const pair of init) {
if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
throw new TypeError('Each header pair must be iterable');
}
pairs.push(Array.from(pair));
}
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError('Each header pair must be a name/value tuple');
}
this.append(pair[0], pair[1]);
}
} else {
// record<ByteString, ByteString>
for (const key of Object.keys(init)) {
const value = init[key];
this.append(key, value);
}
}
} else {
throw new TypeError('Provided initializer must be an object');
}
}
/**
* Return combined header value given name
*
* @param String name Header name
* @return Mixed
*/
get(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key === undefined) {
return null;
}
return this[MAP][key].join(', ');
}
/**
* Iterate over all headers
*
* @param Function callback Executed for each item with parameters (value, name, thisArg)
* @param Boolean thisArg `this` context for callback function
* @return Void
*/
forEach(callback) {
let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
let pairs = getHeaders(this);
let i = 0;
while (i < pairs.length) {
var _pairs$i = pairs[i];
const name = _pairs$i[0],
value = _pairs$i[1];
callback.call(thisArg, value, name, this);
pairs = getHeaders(this);
i++;
}
}
/**
* Overwrite header values given name
*
* @param String name Header name
* @param String value Header value
* @return Void
*/
set(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
this[MAP][key !== undefined ? key : name] = [value];
}
/**
* Append a value onto existing header
*
* @param String name Header name
* @param String value Header value
* @return Void
*/
append(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
if (key !== undefined) {
this[MAP][key].push(value);
} else {
this[MAP][name] = [value];
}
}
/**
* Check for header name existence
*
* @param String name Header name
* @return Boolean
*/
has(name) {
name = `${name}`;
validateName(name);
return find(this[MAP], name) !== undefined;
}
/**
* Delete all header values given name
*
* @param String name Header name
* @return Void
*/
delete(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key !== undefined) {
delete this[MAP][key];
}
}
/**
* Return raw headers (non-spec api)
*
* @return Object
*/
raw() {
return this[MAP];
}
/**
* Get an iterator on keys.
*
* @return Iterator
*/
keys() {
return createHeadersIterator(this, 'key');
}
/**
* Get an iterator on values.
*
* @return Iterator
*/
values() {
return createHeadersIterator(this, 'value');
}
/**
* Get an iterator on entries.
*
* This is the default iterator of the Headers object.
*
* @return Iterator
*/
[Symbol.iterator]() {
return createHeadersIterator(this, 'key+value');
}
}
Headers.prototype.entries = Headers.prototype[Symbol.iterator];
Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
value: 'Headers',
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Headers.prototype, {
get: { enumerable: true },
forEach: { enumerable: true },
set: { enumerable: true },
append: { enumerable: true },
has: { enumerable: true },
delete: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true }
});
function getHeaders(headers) {
let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
const keys = Object.keys(headers[MAP]).sort();
return keys.map(kind === 'key' ? function (k) {
return k.toLowerCase();
} : kind === 'value' ? function (k) {
return headers[MAP][k].join(', ');
} : function (k) {
return [k.toLowerCase(), headers[MAP][k].join(', ')];
});
}
const INTERNAL = Symbol('internal');
function createHeadersIterator(target, kind) {
const iterator = Object.create(HeadersIteratorPrototype);
iterator[INTERNAL] = {
target,
kind,
index: 0
};
return iterator;
}
const HeadersIteratorPrototype = Object.setPrototypeOf({
next() {
// istanbul ignore if
if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
throw new TypeError('Value of `this` is not a HeadersIterator');
}
var _INTERNAL = this[INTERNAL];
const target = _INTERNAL.target,
kind = _INTERNAL.kind,
index = _INTERNAL.index;
const values = getHeaders(target, kind);
const len = values.length;
if (index >= len) {
return {
value: undefined,
done: true
};
}
this[INTERNAL].index = index + 1;
return {
value: values[index],
done: false
};
}
}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
value: 'HeadersIterator',
writable: false,
enumerable: false,
configurable: true
});
/**
* Export the Headers object in a form that Node.js can consume.
*
* @param Headers headers
* @return Object
*/
function exportNodeCompatibleHeaders(headers) {
const obj = Object.assign({ __proto__: null }, headers[MAP]);
// http.request() only supports string as Host header. This hack makes
// specifying custom Host header possible.
const hostHeaderKey = find(headers[MAP], 'Host');
if (hostHeaderKey !== undefined) {
obj[hostHeaderKey] = obj[hostHeaderKey][0];
}
return obj;
}
/**
* Create a Headers object from an object of headers, ignoring those that do
* not conform to HTTP grammar productions.
*
* @param Object obj Object of headers
* @return Headers
*/
function createHeadersLenient(obj) {
const headers = new Headers();
for (const name of Object.keys(obj)) {
if (invalidTokenRegex.test(name)) {
continue;
}
if (Array.isArray(obj[name])) {
for (const val of obj[name]) {
if (invalidHeaderCharRegex.test(val)) {
continue;
}
if (headers[MAP][name] === undefined) {
headers[MAP][name] = [val];
} else {
headers[MAP][name].push(val);
}
}
} else if (!invalidHeaderCharRegex.test(obj[name])) {
headers[MAP][name] = [obj[name]];
}
}
return headers;
}
const INTERNALS$1 = Symbol('Response internals');
// fix an issue where "STATUS_CODES" aren't a named export for node <10
const STATUS_CODES = http.STATUS_CODES;
/**
* Response class
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
}
Body.mixIn(Response.prototype);
Object.defineProperties(Response.prototype, {
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
redirected: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
Object.defineProperty(Response.prototype, Symbol.toStringTag, {
value: 'Response',
writable: false,
enumerable: false,
configurable: true
});
const INTERNALS$2 = Symbol('Request internals');
const URL = whatwgUrl.URL;
// fix an issue where "format", "parse" aren't a named export for node <10
const parse_url = Url.parse;
const format_url = Url.format;
/**
* Wrapper around `new URL` to handle arbitrary URLs
*
* @param {string} urlStr
* @return {void}
*/
function parseURL(urlStr) {
/*
Check whether the URL is absolute or not
Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
*/
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
urlStr = new URL(urlStr).toString();
}
// Fallback to old implementation for arbitrary URLs
return parse_url(urlStr);
}
const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
/**
* Check if a value is an instance of Request.
*
* @param Mixed input
* @return Boolean
*/
function isRequest(input) {
return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
}
function isAbortSignal(signal) {
const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
return !!(proto && proto.constructor.name === 'AbortSignal');
}
/**
* Request class
*
* @param Mixed input Url or Request instance
* @param Object init Custom options
* @return Void
*/
class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parseURL(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parseURL(`${input}`);
}
input = {};
} else {
parsedURL = parseURL(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
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);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
}
Body.mixIn(Request.prototype);
Object.defineProperty(Request.prototype, Symbol.toStringTag, {
value: 'Request',
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Request.prototype, {
method: { enumerable: true },
url: { enumerable: true },
headers: { enumerable: true },
redirect: { enumerable: true },
clone: { enumerable: true },
signal: { enumerable: true }
});
/**
* Convert a Request to Node.js http request options.
*
* @param Request A Request instance
* @return Object The options object to be passed to http.request
*/
function getNodeRequestOptions(request) {
const parsedURL = request[INTERNALS$2].parsedURL;
const headers = new Headers(request[INTERNALS$2].headers);
// fetch step 1.3
if (!headers.has('Accept')) {
headers.set('Accept', '*/*');
}
// Basic fetch
if (!parsedURL.protocol || !parsedURL.hostname) {
throw new TypeError('Only absolute URLs are supported');
}
if (!/^https?:$/.test(parsedURL.protocol)) {
throw new TypeError('Only HTTP(S) protocols are supported');
}
if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
}
// 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);
if (typeof totalBytes === 'number') {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set('Content-Length', contentLengthValue);
}
// HTTP-network-or-cache fetch step 2.11
if (!headers.has('User-Agent')) {
headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
}
// HTTP-network-or-cache fetch step 2.15
if (request.compress && !headers.has('Accept-Encoding')) {
headers.set('Accept-Encoding', 'gzip,deflate');
}
let agent = request.agent;
if (typeof agent === 'function') {
agent = agent(parsedURL);
}
if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}
// HTTP-network fetch step 4.2
// chunked encoding is handled by Node.js
return Object.assign({}, parsedURL, {
method: request.method,
headers: exportNodeCompatibleHeaders(headers),
agent
});
}
/**
* abort-error.js
*
* AbortError interface for cancelled requests
*/
/**
* Create AbortError instance
*
* @param String message Error message for human
* @return AbortError
*/
function AbortError(message) {
Error.call(this, message);
this.type = 'aborted';
this.message = message;
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
}
AbortError.prototype = Object.create(Error.prototype);
AbortError.prototype.constructor = AbortError;
AbortError.prototype.name = 'AbortError';
// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
const PassThrough$1 = Stream.PassThrough;
const resolve_url = Url.resolve;
/**
* Fetch function
*
* @param Mixed url Absolute url or Request instance
* @param Object opts Fetch options
* @return Promise
*/
function fetch(url, opts) {
// allow custom promise
if (!fetch.Promise) {
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
}
Body.Promise = fetch.Promise;
// wrap http.request into fetch
return new fetch.Promise(function (resolve, reject) {
// build request object
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);
const send = (options.protocol === 'https:' ? https : http).request;
const signal = request.signal;
let response = null;
const abort = function abort() {
let error = new AbortError('The user aborted a request.');
reject(error);
if (request.body && request.body instanceof Stream.Readable) {
request.body.destroy(error);
}
if (!response || !response.body) return;
response.body.emit('error', error);
};
if (signal && signal.aborted) {
abort();
return;
}
const abortAndFinalize = function abortAndFinalize() {
abort();
finalize();
};
// send request
const req = send(options);
let reqTimeout;
if (signal) {
signal.addEventListener('abort', abortAndFinalize);
}
function finalize() {
req.abort();
if (signal) signal.removeEventListener('abort', abortAndFinalize);
clearTimeout(reqTimeout);
}
if (request.timeout) {
req.once('socket', function (socket) {
reqTimeout = setTimeout(function () {
reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
finalize();
}, request.timeout);
});
}
req.on('error', function (err) {
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
finalize();
});
req.on('response', function (res) {
clearTimeout(reqTimeout);
const headers = createHeadersLenient(res.headers);
// HTTP fetch step 5
if (fetch.isRedirect(res.statusCode)) {
// HTTP fetch step 5.2
const location = headers.get('Location');
// HTTP fetch step 5.3
const locationURL = location === null ? null : resolve_url(request.url, location);
// 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':
// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
if (locationURL !== null) {
// handle corrupted header
try {
headers.set('Location', locationURL);
} catch (err) {
// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
reject(err);
}
}
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 requestOpts = {
headers: new Headers(request.headers),
follow: request.follow,
counter: request.counter + 1,
agent: request.agent,
compress: request.compress,
method: request.method,
body: request.body,
signal: request.signal,
timeout: request.timeout,
size: request.size
};
// HTTP-redirect fetch step 9
if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
finalize();
return;
}
// HTTP-redirect fetch step 11
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
requestOpts.method = 'GET';
requestOpts.body = undefined;
requestOpts.headers.delete('content-length');
}
// HTTP-redirect fetch step 15
resolve(fetch(new Request(locationURL, requestOpts)));
finalize();
return;
}
}
// prepare response
res.once('end', function () {
if (signal) signal.removeEventListener('abort', abortAndFinalize);
});
let body = res.pipe(new PassThrough$1());
const response_options = {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers: headers,
size: request.size,
timeout: request.timeout,
counter: request.counter
};
// 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 || res.statusCode === 204 || res.statusCode === 304) {
response = new Response(body, response_options);
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: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
};
// for gzip
if (codings == 'gzip' || codings == 'x-gzip') {
body = body.pipe(zlib.createGunzip(zlibOptions));
response = new Response(body, response_options);
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 = res.pipe(new PassThrough$1());
raw.once('data', function (chunk) {
// see http://stackoverflow.com/questions/37519828
if ((chunk[0] & 0x0F) === 0x08) {
body = body.pipe(zlib.createInflate());
} else {
body = body.pipe(zlib.createInflateRaw());
}
response = new Response(body, response_options);
resolve(response);
});
return;
}
// for br
if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
body = body.pipe(zlib.createBrotliDecompress());
response = new Response(body, response_options);
resolve(response);
return;
}
// otherwise, use response as-is
response = new Response(body, response_options);
resolve(response);
});
writeToStream(req, request);
});
}
/**
* Redirect code matching
*
* @param Number code Status code
* @return Boolean
*/
fetch.isRedirect = function (code) {
return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
};
// expose Promise
fetch.Promise = global.Promise;
module.exports = exports = fetch;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.default = exports;
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.FetchError = FetchError;
/***/ }),
/***/ 3039:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
var punycode = __nccwpck_require__(4213);
var mappingTable = __nccwpck_require__(3823);
var PROCESSING_OPTIONS = {
TRANSITIONAL: 0,
NONTRANSITIONAL: 1
};
function normalize(str) { // fix bug in v8
return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000');
}
function findStatus(val) {
var start = 0;
var end = mappingTable.length - 1;
while (start <= end) {
var mid = Math.floor((start + end) / 2);
var target = mappingTable[mid];
if (target[0][0] <= val && target[0][1] >= val) {
return target;
} else if (target[0][0] > val) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return null;
}
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
function countSymbols(string) {
return string
// replace every surrogate pair with a BMP symbol
.replace(regexAstralSymbols, '_')
// then get the length
.length;
}
function mapChars(domain_name, useSTD3, processing_option) {
var hasError = false;
var processed = "";
var len = countSymbols(domain_name);
for (var i = 0; i < len; ++i) {
var codePoint = domain_name.codePointAt(i);
var status = findStatus(codePoint);
switch (status[1]) {
case "disallowed":
hasError = true;
processed += String.fromCodePoint(codePoint);
break;
case "ignored":
break;
case "mapped":
processed += String.fromCodePoint.apply(String, status[2]);
break;
case "deviation":
if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
processed += String.fromCodePoint.apply(String, status[2]);
} else {
processed += String.fromCodePoint(codePoint);
}
break;
case "valid":
processed += String.fromCodePoint(codePoint);
break;
case "disallowed_STD3_mapped":
if (useSTD3) {
hasError = true;
processed += String.fromCodePoint(codePoint);
} else {
processed += String.fromCodePoint.apply(String, status[2]);
}
break;
case "disallowed_STD3_valid":
if (useSTD3) {
hasError = true;
}
processed += String.fromCodePoint(codePoint);
break;
}
}
return {
string: processed,
error: hasError
};
}
var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
function validateLabel(label, processing_option) {
if (label.substr(0, 4) === "xn--") {
label = punycode.toUnicode(label);
processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
}
var error = false;
if (normalize(label) !== label ||
(label[3] === "-" && label[4] === "-") ||
label[0] === "-" || label[label.length - 1] === "-" ||
label.indexOf(".") !== -1 ||
label.search(combiningMarksRegex) === 0) {
error = true;
}
var len = countSymbols(label);
for (var i = 0; i < len; ++i) {
var status = findStatus(label.codePointAt(i));
if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||
(processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&
status[1] !== "valid" && status[1] !== "deviation")) {
error = true;
break;
}
}
return {
label: label,
error: error
};
}
function processing(domain_name, useSTD3, processing_option) {
var result = mapChars(domain_name, useSTD3, processing_option);
result.string = normalize(result.string);
var labels = result.string.split(".");
for (var i = 0; i < labels.length; ++i) {
try {
var validation = validateLabel(labels[i]);
labels[i] = validation.label;
result.error = result.error || validation.error;
} catch(e) {
result.error = true;
}
}
return {
string: labels.join("."),
error: result.error
};
}
module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
var result = processing(domain_name, useSTD3, processing_option);
var labels = result.string.split(".");
labels = labels.map(function(l) {
try {
return punycode.toASCII(l);
} catch(e) {
result.error = true;
return l;
}
});
if (verifyDnsLength) {
var total = labels.slice(0, labels.length - 1).join(".").length;
if (total.length > 253 || total.length === 0) {
result.error = true;
}
for (var i=0; i < labels.length; ++i) {
if (labels.length > 63 || labels.length === 0) {
result.error = true;
break;
}
}
}
if (result.error) return null;
return labels.join(".");
};
module.exports.toUnicode = function(domain_name, useSTD3) {
var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
return {
domain: result.string,
error: result.error
};
};
module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
/***/ }),
/***/ 6542:
/***/ ((module) => {
"use strict";
var conversions = {};
module.exports = conversions;
function sign(x) {
return x < 0 ? -1 : 1;
}
function evenRound(x) {
// Round x to the nearest integer, choosing the even integer if it lies halfway between two.
if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)
return Math.floor(x);
} else {
return Math.round(x);
}
}
function createNumberConversion(bitLength, typeOpts) {
if (!typeOpts.unsigned) {
--bitLength;
}
const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
const upperBound = Math.pow(2, bitLength) - 1;
const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
return function(V, opts) {
if (!opts) opts = {};
let x = +V;
if (opts.enforceRange) {
if (!Number.isFinite(x)) {
throw new TypeError("Argument is not a finite number");
}
x = sign(x) * Math.floor(Math.abs(x));
if (x < lowerBound || x > upperBound) {
throw new TypeError("Argument is not in byte range");
}
return x;
}
if (!isNaN(x) && opts.clamp) {
x = evenRound(x);
if (x < lowerBound) x = lowerBound;
if (x > upperBound) x = upperBound;
return x;
}
if (!Number.isFinite(x) || x === 0) {
return 0;
}
x = sign(x) * Math.floor(Math.abs(x));
x = x % moduloVal;
if (!typeOpts.unsigned && x >= moduloBound) {
return x - moduloVal;
} else if (typeOpts.unsigned) {
if (x < 0) {
x += moduloVal;
} else if (x === -0) { // don't return negative zero
return 0;
}
}
return x;
}
}
conversions["void"] = function () {
return undefined;
};
conversions["boolean"] = function (val) {
return !!val;
};
conversions["byte"] = createNumberConversion(8, { unsigned: false });
conversions["octet"] = createNumberConversion(8, { unsigned: true });
conversions["short"] = createNumberConversion(16, { unsigned: false });
conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
conversions["long"] = createNumberConversion(32, { unsigned: false });
conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
conversions["double"] = function (V) {
const x = +V;
if (!Number.isFinite(x)) {
throw new TypeError("Argument is not a finite floating-point value");
}
return x;
};
conversions["unrestricted double"] = function (V) {
const x = +V;
if (isNaN(x)) {
throw new TypeError("Argument is NaN");
}
return x;
};
// not quite valid, but good enough for JS
conversions["float"] = conversions["double"];
conversions["unrestricted float"] = conversions["unrestricted double"];
conversions["DOMString"] = function (V, opts) {
if (!opts) opts = {};
if (opts.treatNullAsEmptyString && V === null) {
return "";
}
return String(V);
};
conversions["ByteString"] = function (V, opts) {
const x = String(V);
let c = undefined;
for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
if (c > 255) {
throw new TypeError("Argument is not a valid bytestring");
}
}
return x;
};
conversions["USVString"] = function (V) {
const S = String(V);
const n = S.length;
const U = [];
for (let i = 0; i < n; ++i) {
const c = S.charCodeAt(i);
if (c < 0xD800 || c > 0xDFFF) {
U.push(String.fromCodePoint(c));
} else if (0xDC00 <= c && c <= 0xDFFF) {
U.push(String.fromCodePoint(0xFFFD));
} else {
if (i === n - 1) {
U.push(String.fromCodePoint(0xFFFD));
} else {
const d = S.charCodeAt(i + 1);
if (0xDC00 <= d && d <= 0xDFFF) {
const a = c & 0x3FF;
const b = d & 0x3FF;
U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
++i;
} else {
U.push(String.fromCodePoint(0xFFFD));
}
}
}
}
return U.join('');
};
conversions["Date"] = function (V, opts) {
if (!(V instanceof Date)) {
throw new TypeError("Argument is not a Date object");
}
if (isNaN(V)) {
return undefined;
}
return V;
};
conversions["RegExp"] = function (V, opts) {
if (!(V instanceof RegExp)) {
V = new RegExp(V);
}
return V;
};
/***/ }),
/***/ 394:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
const usm = __nccwpck_require__(1234);
exports.implementation = class URLImpl {
constructor(constructorArgs) {
const url = constructorArgs[0];
const base = constructorArgs[1];
let parsedBase = null;
if (base !== undefined) {
parsedBase = usm.basicURLParse(base);
if (parsedBase === "failure") {
throw new TypeError("Invalid base URL");
}
}
const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
if (parsedURL === "failure") {
throw new TypeError("Invalid URL");
}
this._url = parsedURL;
// TODO: query stuff
}
get href() {
return usm.serializeURL(this._url);
}
set href(v) {
const parsedURL = usm.basicURLParse(v);
if (parsedURL === "failure") {
throw new TypeError("Invalid URL");
}
this._url = parsedURL;
}
get origin() {
return usm.serializeURLOrigin(this._url);
}
get protocol() {
return this._url.scheme + ":";
}
set protocol(v) {
usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
}
get username() {
return this._url.username;
}
set username(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setTheUsername(this._url, v);
}
get password() {
return this._url.password;
}
set password(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setThePassword(this._url, v);
}
get host() {
const url = this._url;
if (url.host === null) {
return "";
}
if (url.port === null) {
return usm.serializeHost(url.host);
}
return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
}
set host(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
}
get hostname() {
if (this._url.host === null) {
return "";
}
return usm.serializeHost(this._url.host);
}
set hostname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
}
get port() {
if (this._url.port === null) {
return "";
}
return usm.serializeInteger(this._url.port);
}
set port(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
if (v === "") {
this._url.port = null;
} else {
usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
}
}
get pathname() {
if (this._url.cannotBeABaseURL) {
return this._url.path[0];
}
if (this._url.path.length === 0) {
return "";
}
return "/" + this._url.path.join("/");
}
set pathname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
this._url.path = [];
usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
}
get search() {
if (this._url.query === null || this._url.query === "") {
return "";
}
return "?" + this._url.query;
}
set search(v) {
// TODO: query stuff
const url = this._url;
if (v === "") {
url.query = null;
return;
}
const input = v[0] === "?" ? v.substring(1) : v;
url.query = "";
usm.basicURLParse(input, { url, stateOverride: "query" });
}
get hash() {
if (this._url.fragment === null || this._url.fragment === "") {
return "";
}
return "#" + this._url.fragment;
}
set hash(v) {
if (v === "") {
this._url.fragment = null;
return;
}
const input = v[0] === "#" ? v.substring(1) : v;
this._url.fragment = "";
usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
}
toJSON() {
return this.href;
}
};
/***/ }),
/***/ 2047:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const conversions = __nccwpck_require__(6542);
const utils = __nccwpck_require__(3387);
const Impl = __nccwpck_require__(394);
const impl = utils.implSymbol;
function URL(url) {
if (!this || this[impl] || !(this instanceof URL)) {
throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
}
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 2; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["USVString"](args[0]);
if (args[1] !== undefined) {
args[1] = conversions["USVString"](args[1]);
}
module.exports.setup(this, args);
}
URL.prototype.toJSON = function toJSON() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
const args = [];
for (let i = 0; i < arguments.length && i < 0; ++i) {
args[i] = arguments[i];
}
return this[impl].toJSON.apply(this[impl], args);
};
Object.defineProperty(URL.prototype, "href", {
get() {
return this[impl].href;
},
set(V) {
V = conversions["USVString"](V);
this[impl].href = V;
},
enumerable: true,
configurable: true
});
URL.prototype.toString = function () {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this.href;
};
Object.defineProperty(URL.prototype, "origin", {
get() {
return this[impl].origin;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "protocol", {
get() {
return this[impl].protocol;
},
set(V) {
V = conversions["USVString"](V);
this[impl].protocol = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "username", {
get() {
return this[impl].username;
},
set(V) {
V = conversions["USVString"](V);
this[impl].username = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "password", {
get() {
return this[impl].password;
},
set(V) {
V = conversions["USVString"](V);
this[impl].password = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "host", {
get() {
return this[impl].host;
},
set(V) {
V = conversions["USVString"](V);
this[impl].host = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "hostname", {
get() {
return this[impl].hostname;
},
set(V) {
V = conversions["USVString"](V);
this[impl].hostname = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "port", {
get() {
return this[impl].port;
},
set(V) {
V = conversions["USVString"](V);
this[impl].port = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "pathname", {
get() {
return this[impl].pathname;
},
set(V) {
V = conversions["USVString"](V);
this[impl].pathname = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "search", {
get() {
return this[impl].search;
},
set(V) {
V = conversions["USVString"](V);
this[impl].search = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL.prototype, "hash", {
get() {
return this[impl].hash;
},
set(V) {
V = conversions["USVString"](V);
this[impl].hash = V;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(URL.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: URL,
expose: {
Window: { URL: URL },
Worker: { URL: URL }
}
};
/***/ }),
/***/ 301:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
exports.URL = __nccwpck_require__(2047).interface;
exports.serializeURL = __nccwpck_require__(1234).serializeURL;
exports.serializeURLOrigin = __nccwpck_require__(1234).serializeURLOrigin;
exports.basicURLParse = __nccwpck_require__(1234).basicURLParse;
exports.setTheUsername = __nccwpck_require__(1234).setTheUsername;
exports.setThePassword = __nccwpck_require__(1234).setThePassword;
exports.serializeHost = __nccwpck_require__(1234).serializeHost;
exports.serializeInteger = __nccwpck_require__(1234).serializeInteger;
exports.parseURL = __nccwpck_require__(1234).parseURL;
/***/ }),
/***/ 1234:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const punycode = __nccwpck_require__(4213);
const tr46 = __nccwpck_require__(3039);
const specialSchemes = {
ftp: 21,
file: null,
gopher: 70,
http: 80,
https: 443,
ws: 80,
wss: 443
};
const failure = Symbol("failure");
function countSymbols(str) {
return punycode.ucs2.decode(str).length;
}
function at(input, idx) {
const c = input[idx];
return isNaN(c) ? undefined : String.fromCodePoint(c);
}
function isASCIIDigit(c) {
return c >= 0x30 && c <= 0x39;
}
function isASCIIAlpha(c) {
return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
}
function isASCIIAlphanumeric(c) {
return isASCIIAlpha(c) || isASCIIDigit(c);
}
function isASCIIHex(c) {
return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
}
function isSingleDot(buffer) {
return buffer === "." || buffer.toLowerCase() === "%2e";
}
function isDoubleDot(buffer) {
buffer = buffer.toLowerCase();
return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
}
function isWindowsDriveLetterCodePoints(cp1, cp2) {
return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
}
function isWindowsDriveLetterString(string) {
return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
}
function isNormalizedWindowsDriveLetterString(string) {
return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
}
function containsForbiddenHostCodePoint(string) {
return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
}
function containsForbiddenHostCodePointExcludingPercent(string) {
return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
}
function isSpecialScheme(scheme) {
return specialSchemes[scheme] !== undefined;
}
function isSpecial(url) {
return isSpecialScheme(url.scheme);
}
function defaultPort(scheme) {
return specialSchemes[scheme];
}
function percentEncode(c) {
let hex = c.toString(16).toUpperCase();
if (hex.length === 1) {
hex = "0" + hex;
}
return "%" + hex;
}
function utf8PercentEncode(c) {
2021-12-11 08:00:14 -05:00
const buf = Buffer.from(c);
2021-09-26 15:31:45 -04:00
let str = "";
for (let i = 0; i < buf.length; ++i) {
str += percentEncode(buf[i]);
}
return str;
}
function utf8PercentDecode(str) {
2021-12-11 08:00:14 -05:00
const input = Buffer.from(str);
2021-09-26 15:31:45 -04:00
const output = [];
for (let i = 0; i < input.length; ++i) {
if (input[i] !== 37) {
output.push(input[i]);
} else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
i += 2;
} else {
output.push(input[i]);
}
}
2021-12-11 08:00:14 -05:00
return Buffer.from(output).toString();
2021-09-26 15:31:45 -04:00
}
function isC0ControlPercentEncode(c) {
return c <= 0x1F || c > 0x7E;
}
const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
function isPathPercentEncode(c) {
return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);
}
const extraUserinfoPercentEncodeSet =
new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
function isUserinfoPercentEncode(c) {
return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
}
function percentEncodeChar(c, encodeSetPredicate) {
const cStr = String.fromCodePoint(c);
if (encodeSetPredicate(c)) {
return utf8PercentEncode(cStr);
}
return cStr;
}
function parseIPv4Number(input) {
let R = 10;
if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
input = input.substring(2);
R = 16;
} else if (input.length >= 2 && input.charAt(0) === "0") {
input = input.substring(1);
R = 8;
}
if (input === "") {
return 0;
}
const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/);
if (regex.test(input)) {
return failure;
}
return parseInt(input, R);
}
function parseIPv4(input) {
const parts = input.split(".");
if (parts[parts.length - 1] === "") {
if (parts.length > 1) {
parts.pop();
}
}
if (parts.length > 4) {
return input;
}
const numbers = [];
for (const part of parts) {
if (part === "") {
return input;
}
const n = parseIPv4Number(part);
if (n === failure) {
return input;
}
numbers.push(n);
}
for (let i = 0; i < numbers.length - 1; ++i) {
if (numbers[i] > 255) {
return failure;
}
}
if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
return failure;
}
let ipv4 = numbers.pop();
let counter = 0;
for (const n of numbers) {
ipv4 += n * Math.pow(256, 3 - counter);
++counter;
}
return ipv4;
}
function serializeIPv4(address) {
let output = "";
let n = address;
for (let i = 1; i <= 4; ++i) {
output = String(n % 256) + output;
if (i !== 4) {
output = "." + output;
}
n = Math.floor(n / 256);
}
return output;
}
function parseIPv6(input) {
const address = [0, 0, 0, 0, 0, 0, 0, 0];
let pieceIndex = 0;
let compress = null;
let pointer = 0;
input = punycode.ucs2.decode(input);
if (input[pointer] === 58) {
if (input[pointer + 1] !== 58) {
return failure;
}
pointer += 2;
++pieceIndex;
compress = pieceIndex;
}
while (pointer < input.length) {
if (pieceIndex === 8) {
return failure;
}
if (input[pointer] === 58) {
if (compress !== null) {
return failure;
}
++pointer;
++pieceIndex;
compress = pieceIndex;
continue;
}
let value = 0;
let length = 0;
while (length < 4 && isASCIIHex(input[pointer])) {
value = value * 0x10 + parseInt(at(input, pointer), 16);
++pointer;
++length;
}
if (input[pointer] === 46) {
if (length === 0) {
return failure;
}
pointer -= length;
if (pieceIndex > 6) {
return failure;
}
let numbersSeen = 0;
while (input[pointer] !== undefined) {
let ipv4Piece = null;
if (numbersSeen > 0) {
if (input[pointer] === 46 && numbersSeen < 4) {
++pointer;
} else {
return failure;
}
}
if (!isASCIIDigit(input[pointer])) {
return failure;
}
while (isASCIIDigit(input[pointer])) {
const number = parseInt(at(input, pointer));
if (ipv4Piece === null) {
ipv4Piece = number;
} else if (ipv4Piece === 0) {
return failure;
} else {
ipv4Piece = ipv4Piece * 10 + number;
}
if (ipv4Piece > 255) {
return failure;
}
++pointer;
}
address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;
++numbersSeen;
if (numbersSeen === 2 || numbersSeen === 4) {
++pieceIndex;
}
}
if (numbersSeen !== 4) {
return failure;
}
break;
} else if (input[pointer] === 58) {
++pointer;
if (input[pointer] === undefined) {
return failure;
}
} else if (input[pointer] !== undefined) {
return failure;
}
address[pieceIndex] = value;
++pieceIndex;
}
if (compress !== null) {
let swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex !== 0 && swaps > 0) {
const temp = address[compress + swaps - 1];
address[compress + swaps - 1] = address[pieceIndex];
address[pieceIndex] = temp;
--pieceIndex;
--swaps;
}
} else if (compress === null && pieceIndex !== 8) {
return failure;
}
return address;
}
function serializeIPv6(address) {
let output = "";
const seqResult = findLongestZeroSequence(address);
const compress = seqResult.idx;
let ignore0 = false;
for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
if (ignore0 && address[pieceIndex] === 0) {
continue;
} else if (ignore0) {
ignore0 = false;
}
if (compress === pieceIndex) {
const separator = pieceIndex === 0 ? "::" : ":";
output += separator;
ignore0 = true;
continue;
}
output += address[pieceIndex].toString(16);
if (pieceIndex !== 7) {
output += ":";
}
}
return output;
}
function parseHost(input, isSpecialArg) {
if (input[0] === "[") {
if (input[input.length - 1] !== "]") {
return failure;
}
return parseIPv6(input.substring(1, input.length - 1));
}
if (!isSpecialArg) {
return parseOpaqueHost(input);
}
const domain = utf8PercentDecode(input);
const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
if (asciiDomain === null) {
return failure;
}
if (containsForbiddenHostCodePoint(asciiDomain)) {
return failure;
}
const ipv4Host = parseIPv4(asciiDomain);
if (typeof ipv4Host === "number" || ipv4Host === failure) {
return ipv4Host;
}
return asciiDomain;
}
function parseOpaqueHost(input) {
if (containsForbiddenHostCodePointExcludingPercent(input)) {
return failure;
}
let output = "";
const decoded = punycode.ucs2.decode(input);
for (let i = 0; i < decoded.length; ++i) {
output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
}
return output;
}
function findLongestZeroSequence(arr) {
let maxIdx = null;
let maxLen = 1; // only find elements > 1
let currStart = null;
let currLen = 0;
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== 0) {
if (currLen > maxLen) {
maxIdx = currStart;
maxLen = currLen;
}
currStart = null;
currLen = 0;
} else {
if (currStart === null) {
currStart = i;
}
++currLen;
}
}
// if trailing zeros
if (currLen > maxLen) {
maxIdx = currStart;
maxLen = currLen;
}
return {
idx: maxIdx,
len: maxLen
};
}
function serializeHost(host) {
if (typeof host === "number") {
return serializeIPv4(host);
}
// IPv6 serializer
if (host instanceof Array) {
return "[" + serializeIPv6(host) + "]";
}
return host;
}
function trimControlChars(url) {
return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
}
function trimTabAndNewline(url) {
return url.replace(/\u0009|\u000A|\u000D/g, "");
}
function shortenPath(url) {
const path = url.path;
if (path.length === 0) {
return;
}
if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
return;
}
path.pop();
}
function includesCredentials(url) {
return url.username !== "" || url.password !== "";
}
function cannotHaveAUsernamePasswordPort(url) {
return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
}
function isNormalizedWindowsDriveLetter(string) {
return /^[A-Za-z]:$/.test(string);
}
function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
this.pointer = 0;
this.input = input;
this.base = base || null;
this.encodingOverride = encodingOverride || "utf-8";
this.stateOverride = stateOverride;
this.url = url;
this.failure = false;
this.parseError = false;
if (!this.url) {
this.url = {
scheme: "",
username: "",
password: "",
host: null,
port: null,
path: [],
query: null,
fragment: null,
cannotBeABaseURL: false
};
const res = trimControlChars(this.input);
if (res !== this.input) {
this.parseError = true;
}
this.input = res;
}
const res = trimTabAndNewline(this.input);
if (res !== this.input) {
this.parseError = true;
}
this.input = res;
this.state = stateOverride || "scheme start";
this.buffer = "";
this.atFlag = false;
this.arrFlag = false;
this.passwordTokenSeenFlag = false;
this.input = punycode.ucs2.decode(this.input);
for (; this.pointer <= this.input.length; ++this.pointer) {
const c = this.input[this.pointer];
const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);
// exec state machine
const ret = this["parse " + this.state](c, cStr);
if (!ret) {
break; // terminate algorithm
} else if (ret === failure) {
this.failure = true;
break;
}
}
}
URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
if (isASCIIAlpha(c)) {
this.buffer += cStr.toLowerCase();
this.state = "scheme";
} else if (!this.stateOverride) {
this.state = "no scheme";
--this.pointer;
} else {
this.parseError = true;
return failure;
}
return true;
};
URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
this.buffer += cStr.toLowerCase();
} else if (c === 58) {
if (this.stateOverride) {
if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
return false;
}
if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
return false;
}
if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
return false;
}
if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
return false;
}
}
this.url.scheme = this.buffer;
this.buffer = "";
if (this.stateOverride) {
return false;
}
if (this.url.scheme === "file") {
if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
this.parseError = true;
}
this.state = "file";
} else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
this.state = "special relative or authority";
} else if (isSpecial(this.url)) {
this.state = "special authority slashes";
} else if (this.input[this.pointer + 1] === 47) {
this.state = "path or authority";
++this.pointer;
} else {
this.url.cannotBeABaseURL = true;
this.url.path.push("");
this.state = "cannot-be-a-base-URL path";
}
} else if (!this.stateOverride) {
this.buffer = "";
this.state = "no scheme";
this.pointer = -1;
} else {
this.parseError = true;
return failure;
}
return true;
};
URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {
return failure;
} else if (this.base.cannotBeABaseURL && c === 35) {
this.url.scheme = this.base.scheme;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.url.cannotBeABaseURL = true;
this.state = "fragment";
} else if (this.base.scheme === "file") {
this.state = "file";
--this.pointer;
} else {
this.state = "relative";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
if (c === 47 && this.input[this.pointer + 1] === 47) {
this.state = "special authority ignore slashes";
++this.pointer;
} else {
this.parseError = true;
this.state = "relative";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
if (c === 47) {
this.state = "authority";
} else {
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
this.url.scheme = this.base.scheme;
if (isNaN(c)) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
} else if (c === 47) {
this.state = "relative slash";
} else if (c === 63) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.state = "fragment";
} else if (isSpecial(this.url) && c === 92) {
this.parseError = true;
this.state = "relative slash";
} else {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice(0, this.base.path.length - 1);
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
if (isSpecial(this.url) && (c === 47 || c === 92)) {
if (c === 92) {
this.parseError = true;
}
this.state = "special authority ignore slashes";
} else if (c === 47) {
this.state = "authority";
} else {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
if (c === 47 && this.input[this.pointer + 1] === 47) {
this.state = "special authority ignore slashes";
++this.pointer;
} else {
this.parseError = true;
this.state = "special authority ignore slashes";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
if (c !== 47 && c !== 92) {
this.state = "authority";
--this.pointer;
} else {
this.parseError = true;
}
return true;
};
URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
if (c === 64) {
this.parseError = true;
if (this.atFlag) {
this.buffer = "%40" + this.buffer;
}
this.atFlag = true;
// careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars
const len = countSymbols(this.buffer);
for (let pointer = 0; pointer < len; ++pointer) {
const codePoint = this.buffer.codePointAt(pointer);
if (codePoint === 58 && !this.passwordTokenSeenFlag) {
this.passwordTokenSeenFlag = true;
continue;
}
const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
if (this.passwordTokenSeenFlag) {
this.url.password += encodedCodePoints;
} else {
this.url.username += encodedCodePoints;
}
}
this.buffer = "";
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
(isSpecial(this.url) && c === 92)) {
if (this.atFlag && this.buffer === "") {
this.parseError = true;
return failure;
}
this.pointer -= countSymbols(this.buffer) + 1;
this.buffer = "";
this.state = "host";
} else {
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse hostname"] =
URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
if (this.stateOverride && this.url.scheme === "file") {
--this.pointer;
this.state = "file host";
} else if (c === 58 && !this.arrFlag) {
if (this.buffer === "") {
this.parseError = true;
return failure;
}
const host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
this.url.host = host;
this.buffer = "";
this.state = "port";
if (this.stateOverride === "hostname") {
return false;
}
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
(isSpecial(this.url) && c === 92)) {
--this.pointer;
if (isSpecial(this.url) && this.buffer === "") {
this.parseError = true;
return failure;
} else if (this.stateOverride && this.buffer === "" &&
(includesCredentials(this.url) || this.url.port !== null)) {
this.parseError = true;
return false;
}
const host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
this.url.host = host;
this.buffer = "";
this.state = "path start";
if (this.stateOverride) {
return false;
}
} else {
if (c === 91) {
this.arrFlag = true;
} else if (c === 93) {
this.arrFlag = false;
}
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
if (isASCIIDigit(c)) {
this.buffer += cStr;
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
(isSpecial(this.url) && c === 92) ||
this.stateOverride) {
if (this.buffer !== "") {
const port = parseInt(this.buffer);
if (port > Math.pow(2, 16) - 1) {
this.parseError = true;
return failure;
}
this.url.port = port === defaultPort(this.url.scheme) ? null : port;
this.buffer = "";
}
if (this.stateOverride) {
return false;
}
this.state = "path start";
--this.pointer;
} else {
this.parseError = true;
return failure;
}
return true;
};
const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);
URLStateMachine.prototype["parse file"] = function parseFile(c) {
this.url.scheme = "file";
if (c === 47 || c === 92) {
if (c === 92) {
this.parseError = true;
}
this.state = "file slash";
} else if (this.base !== null && this.base.scheme === "file") {
if (isNaN(c)) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
} else if (c === 63) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.state = "fragment";
} else {
if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points
!isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) ||
(this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points
!fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
shortenPath(this.url);
} else {
this.parseError = true;
}
this.state = "path";
--this.pointer;
}
} else {
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
if (c === 47 || c === 92) {
if (c === 92) {
this.parseError = true;
}
this.state = "file host";
} else {
if (this.base !== null && this.base.scheme === "file") {
if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
this.url.path.push(this.base.path[0]);
} else {
this.url.host = this.base.host;
}
}
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
--this.pointer;
if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
this.parseError = true;
this.state = "path";
} else if (this.buffer === "") {
this.url.host = "";
if (this.stateOverride) {
return false;
}
this.state = "path start";
} else {
let host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
if (host === "localhost") {
host = "";
}
this.url.host = host;
if (this.stateOverride) {
return false;
}
this.buffer = "";
this.state = "path start";
}
} else {
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
if (isSpecial(this.url)) {
if (c === 92) {
this.parseError = true;
}
this.state = "path";
if (c !== 47 && c !== 92) {
--this.pointer;
}
} else if (!this.stateOverride && c === 63) {
this.url.query = "";
this.state = "query";
} else if (!this.stateOverride && c === 35) {
this.url.fragment = "";
this.state = "fragment";
} else if (c !== undefined) {
this.state = "path";
if (c !== 47) {
--this.pointer;
}
}
return true;
};
URLStateMachine.prototype["parse path"] = function parsePath(c) {
if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) ||
(!this.stateOverride && (c === 63 || c === 35))) {
if (isSpecial(this.url) && c === 92) {
this.parseError = true;
}
if (isDoubleDot(this.buffer)) {
shortenPath(this.url);
if (c !== 47 && !(isSpecial(this.url) && c === 92)) {
this.url.path.push("");
}
} else if (isSingleDot(this.buffer) && c !== 47 &&
!(isSpecial(this.url) && c === 92)) {
this.url.path.push("");
} else if (!isSingleDot(this.buffer)) {
if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
if (this.url.host !== "" && this.url.host !== null) {
this.parseError = true;
this.url.host = "";
}
this.buffer = this.buffer[0] + ":";
}
this.url.path.push(this.buffer);
}
this.buffer = "";
if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) {
while (this.url.path.length > 1 && this.url.path[0] === "") {
this.parseError = true;
this.url.path.shift();
}
}
if (c === 63) {
this.url.query = "";
this.state = "query";
}
if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
}
} else {
// TODO: If c is not a URL code point and not "%", parse error.
if (c === 37 &&
(!isASCIIHex(this.input[this.pointer + 1]) ||
!isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.buffer += percentEncodeChar(c, isPathPercentEncode);
}
return true;
};
URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {
if (c === 63) {
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
} else {
// TODO: Add: not a URL code point
if (!isNaN(c) && c !== 37) {
this.parseError = true;
}
if (c === 37 &&
(!isASCIIHex(this.input[this.pointer + 1]) ||
!isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
if (!isNaN(c)) {
this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);
}
}
return true;
};
URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
if (isNaN(c) || (!this.stateOverride && c === 35)) {
if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
this.encodingOverride = "utf-8";
}
2021-12-11 08:00:14 -05:00
const buffer = Buffer.from(this.buffer); // TODO: Use encoding override instead
2021-09-26 15:31:45 -04:00
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 ||
buffer[i] === 0x3C || buffer[i] === 0x3E) {
this.url.query += percentEncode(buffer[i]);
} else {
this.url.query += String.fromCodePoint(buffer[i]);
}
}
this.buffer = "";
if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
}
} else {
// TODO: If c is not a URL code point and not "%", parse error.
if (c === 37 &&
(!isASCIIHex(this.input[this.pointer + 1]) ||
!isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
if (isNaN(c)) { // do nothing
} else if (c === 0x0) {
this.parseError = true;
} else {
// TODO: If c is not a URL code point and not "%", parse error.
if (c === 37 &&
(!isASCIIHex(this.input[this.pointer + 1]) ||
!isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);
}
return true;
};
function serializeURL(url, excludeFragment) {
let output = url.scheme + ":";
if (url.host !== null) {
output += "//";
if (url.username !== "" || url.password !== "") {
output += url.username;
if (url.password !== "") {
output += ":" + url.password;
}
output += "@";
}
output += serializeHost(url.host);
if (url.port !== null) {
output += ":" + url.port;
}
} else if (url.host === null && url.scheme === "file") {
output += "//";
}
if (url.cannotBeABaseURL) {
output += url.path[0];
} else {
for (const string of url.path) {
output += "/" + string;
}
}
if (url.query !== null) {
output += "?" + url.query;
}
if (!excludeFragment && url.fragment !== null) {
output += "#" + url.fragment;
}
return output;
}
function serializeOrigin(tuple) {
let result = tuple.scheme + "://";
result += serializeHost(tuple.host);
if (tuple.port !== null) {
result += ":" + tuple.port;
}
return result;
}
module.exports.serializeURL = serializeURL;
module.exports.serializeURLOrigin = function (url) {
// https://url.spec.whatwg.org/#concept-url-origin
switch (url.scheme) {
case "blob":
try {
return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0]));
} catch (e) {
// serializing an opaque origin returns "null"
return "null";
}
case "ftp":
case "gopher":
case "http":
case "https":
case "ws":
case "wss":
return serializeOrigin({
scheme: url.scheme,
host: url.host,
port: url.port
});
case "file":
// spec says "exercise to the reader", chrome says "file://"
return "file://";
default:
// serializing an opaque origin returns "null"
return "null";
}
};
module.exports.basicURLParse = function (input, options) {
if (options === undefined) {
options = {};
}
const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
if (usm.failure) {
return "failure";
}
return usm.url;
};
module.exports.setTheUsername = function (url, username) {
url.username = "";
const decoded = punycode.ucs2.decode(username);
for (let i = 0; i < decoded.length; ++i) {
url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
}
};
module.exports.setThePassword = function (url, password) {
url.password = "";
const decoded = punycode.ucs2.decode(password);
for (let i = 0; i < decoded.length; ++i) {
url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
}
};
module.exports.serializeHost = serializeHost;
module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
module.exports.serializeInteger = function (integer) {
return String(integer);
};
module.exports.parseURL = function (input, options) {
if (options === undefined) {
options = {};
}
// We don't handle blobs, so this just delegates:
return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
};
/***/ }),
/***/ 3387:
/***/ ((module) => {
"use strict";
module.exports.mixin = function mixin(target, source) {
const keys = Object.getOwnPropertyNames(source);
for (let i = 0; i < keys.length; ++i) {
Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
}
};
module.exports.wrapperSymbol = Symbol("wrapper");
module.exports.implSymbol = Symbol("impl");
module.exports.wrapperForImpl = function (impl) {
return impl[module.exports.wrapperSymbol];
};
module.exports.implForWrapper = function (wrapper) {
return wrapper[module.exports.implSymbol];
};
/***/ }),
/***/ 3682:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var register = __nccwpck_require__(4670)
var addHook = __nccwpck_require__(5549)
var removeHook = __nccwpck_require__(6819)
// bind with array of arguments: https://stackoverflow.com/a/21792913
var bind = Function.bind
var bindable = bind.bind(bind)
function bindApi (hook, state, name) {
var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])
hook.api = { remove: removeHookRef }
hook.remove = removeHookRef
;['before', 'error', 'after', 'wrap'].forEach(function (kind) {
var args = name ? [state, kind, name] : [state, kind]
hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)
})
}
function HookSingular () {
var singularHookName = 'h'
var singularHookState = {
registry: {}
}
var singularHook = register.bind(null, singularHookState, singularHookName)
bindApi(singularHook, singularHookState, singularHookName)
return singularHook
}
function HookCollection () {
var state = {
registry: {}
}
var hook = register.bind(null, state)
bindApi(hook, state)
return hook
}
var collectionHookDeprecationMessageDisplayed = false
function Hook () {
if (!collectionHookDeprecationMessageDisplayed) {
console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4')
collectionHookDeprecationMessageDisplayed = true
}
return HookCollection()
}
Hook.Singular = HookSingular.bind()
Hook.Collection = HookCollection.bind()
module.exports = Hook
// expose constructors as a named property for TypeScript
module.exports.Hook = Hook
module.exports.Singular = Hook.Singular
module.exports.Collection = Hook.Collection
/***/ }),
/***/ 5549:
/***/ ((module) => {
module.exports = addHook;
function addHook(state, kind, name, hook) {
var orig = hook;
if (!state.registry[name]) {
state.registry[name] = [];
}
if (kind === "before") {
hook = function (method, options) {
return Promise.resolve()
.then(orig.bind(null, options))
.then(method.bind(null, options));
};
}
if (kind === "after") {
hook = function (method, options) {
var result;
return Promise.resolve()
.then(method.bind(null, options))
.then(function (result_) {
result = result_;
return orig(result, options);
})
.then(function () {
return result;
});
};
}
if (kind === "error") {
hook = function (method, options) {
return Promise.resolve()
.then(method.bind(null, options))
.catch(function (error) {
return orig(error, options);
});
};
}
state.registry[name].push({
hook: hook,
orig: orig,
});
}
/***/ }),
/***/ 4670:
/***/ ((module) => {
module.exports = register;
function register(state, name, method, options) {
if (typeof method !== "function") {
throw new Error("method for before hook must be a function");
}
if (!options) {
options = {};
}
if (Array.isArray(name)) {
return name.reverse().reduce(function (callback, name) {
return register.bind(null, state, name, callback, options);
}, method)();
}
return Promise.resolve().then(function () {
if (!state.registry[name]) {
return method(options);
}
return state.registry[name].reduce(function (method, registered) {
return registered.hook.bind(null, method, options);
}, method)();
});
}
/***/ }),
/***/ 6819:
/***/ ((module) => {
module.exports = removeHook;
function removeHook(state, name, method) {
if (!state.registry[name]) {
return;
}
var index = state.registry[name]
.map(function (registered) {
return registered.orig;
})
.indexOf(method);
if (index === -1) {
return;
}
state.registry[name].splice(index, 1);
}
/***/ }),
/***/ 610:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const stringify = __nccwpck_require__(8750);
const compile = __nccwpck_require__(9434);
const expand = __nccwpck_require__(5873);
const parse = __nccwpck_require__(6477);
/**
* Expand the given pattern or create a regex-compatible string.
*
* ```js
* const braces = require('braces');
* console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
* console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {String}
* @api public
*/
const braces = (input, options = {}) => {
let output = [];
if (Array.isArray(input)) {
for (let pattern of input) {
let result = braces.create(pattern, options);
if (Array.isArray(result)) {
output.push(...result);
} else {
output.push(result);
}
}
} else {
output = [].concat(braces.create(input, options));
}
if (options && options.expand === true && options.nodupes === true) {
output = [...new Set(output)];
}
return output;
};
/**
* Parse the given `str` with the given `options`.
*
* ```js
* // braces.parse(pattern, [, options]);
* const ast = braces.parse('a/{b,c}/d');
* console.log(ast);
* ```
* @param {String} pattern Brace pattern to parse
* @param {Object} options
* @return {Object} Returns an AST
* @api public
*/
braces.parse = (input, options = {}) => parse(input, options);
/**
* Creates a braces string from an AST, or an AST node.
*
* ```js
* const braces = require('braces');
* let ast = braces.parse('foo/{a,b}/bar');
* console.log(stringify(ast.nodes[2])); //=> '{a,b}'
* ```
* @param {String} `input` Brace pattern or AST.
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.stringify = (input, options = {}) => {
if (typeof input === 'string') {
return stringify(braces.parse(input, options), options);
}
return stringify(input, options);
};
/**
* Compiles a brace pattern into a regex-compatible, optimized string.
* This method is called by the main [braces](#braces) function by default.
*
* ```js
* const braces = require('braces');
* console.log(braces.compile('a/{b,c}/d'));
* //=> ['a/(b|c)/d']
* ```
* @param {String} `input` Brace pattern or AST.
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.compile = (input, options = {}) => {
if (typeof input === 'string') {
input = braces.parse(input, options);
}
return compile(input, options);
};
/**
* Expands a brace pattern into an array. This method is called by the
* main [braces](#braces) function when `options.expand` is true. Before
* using this method it's recommended that you read the [performance notes](#performance))
* and advantages of using [.compile](#compile) instead.
*
* ```js
* const braces = require('braces');
* console.log(braces.expand('a/{b,c}/d'));
* //=> ['a/b/d', 'a/c/d'];
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.expand = (input, options = {}) => {
if (typeof input === 'string') {
input = braces.parse(input, options);
}
let result = expand(input, options);
// filter out empty strings if specified
if (options.noempty === true) {
result = result.filter(Boolean);
}
// filter out duplicates if specified
if (options.nodupes === true) {
result = [...new Set(result)];
}
return result;
};
/**
* Processes a brace pattern and returns either an expanded array
* (if `options.expand` is true), a highly optimized regex-compatible string.
* This method is called by the main [braces](#braces) function.
*
* ```js
* const braces = require('braces');
* console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
* //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.create = (input, options = {}) => {
if (input === '' || input.length < 3) {
return [input];
}
return options.expand !== true
? braces.compile(input, options)
: braces.expand(input, options);
};
/**
* Expose "braces"
*/
module.exports = braces;
/***/ }),
/***/ 9434:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fill = __nccwpck_require__(6330);
const utils = __nccwpck_require__(5207);
const compile = (ast, options = {}) => {
let walk = (node, parent = {}) => {
let invalidBlock = utils.isInvalidBrace(parent);
let invalidNode = node.invalid === true && options.escapeInvalid === true;
let invalid = invalidBlock === true || invalidNode === true;
let prefix = options.escapeInvalid === true ? '\\' : '';
let output = '';
if (node.isOpen === true) {
return prefix + node.value;
}
if (node.isClose === true) {
return prefix + node.value;
}
if (node.type === 'open') {
return invalid ? (prefix + node.value) : '(';
}
if (node.type === 'close') {
return invalid ? (prefix + node.value) : ')';
}
if (node.type === 'comma') {
return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
}
if (node.value) {
return node.value;
}
if (node.nodes && node.ranges > 0) {
let args = utils.reduce(node.nodes);
let range = fill(...args, { ...options, wrap: false, toRegex: true });
if (range.length !== 0) {
return args.length > 1 && range.length > 1 ? `(${range})` : range;
}
}
if (node.nodes) {
for (let child of node.nodes) {
output += walk(child, node);
}
}
return output;
};
return walk(ast);
};
module.exports = compile;
/***/ }),
/***/ 8774:
/***/ ((module) => {
"use strict";
module.exports = {
MAX_LENGTH: 1024 * 64,
// Digits
CHAR_0: '0', /* 0 */
CHAR_9: '9', /* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 'A', /* A */
CHAR_LOWERCASE_A: 'a', /* a */
CHAR_UPPERCASE_Z: 'Z', /* Z */
CHAR_LOWERCASE_Z: 'z', /* z */
CHAR_LEFT_PARENTHESES: '(', /* ( */
CHAR_RIGHT_PARENTHESES: ')', /* ) */
CHAR_ASTERISK: '*', /* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: '&', /* & */
CHAR_AT: '@', /* @ */
CHAR_BACKSLASH: '\\', /* \ */
CHAR_BACKTICK: '`', /* ` */
CHAR_CARRIAGE_RETURN: '\r', /* \r */
CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
CHAR_COLON: ':', /* : */
CHAR_COMMA: ',', /* , */
CHAR_DOLLAR: '$', /* . */
CHAR_DOT: '.', /* . */
CHAR_DOUBLE_QUOTE: '"', /* " */
CHAR_EQUAL: '=', /* = */
CHAR_EXCLAMATION_MARK: '!', /* ! */
CHAR_FORM_FEED: '\f', /* \f */
CHAR_FORWARD_SLASH: '/', /* / */
CHAR_HASH: '#', /* # */
CHAR_HYPHEN_MINUS: '-', /* - */
CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
CHAR_LEFT_CURLY_BRACE: '{', /* { */
CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
CHAR_LINE_FEED: '\n', /* \n */
CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
CHAR_PERCENT: '%', /* % */
CHAR_PLUS: '+', /* + */
CHAR_QUESTION_MARK: '?', /* ? */
CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
CHAR_RIGHT_CURLY_BRACE: '}', /* } */
CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
CHAR_SEMICOLON: ';', /* ; */
CHAR_SINGLE_QUOTE: '\'', /* ' */
CHAR_SPACE: ' ', /* */
CHAR_TAB: '\t', /* \t */
CHAR_UNDERSCORE: '_', /* _ */
CHAR_VERTICAL_LINE: '|', /* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
};
/***/ }),
/***/ 5873:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const fill = __nccwpck_require__(6330);
const stringify = __nccwpck_require__(8750);
const utils = __nccwpck_require__(5207);
const append = (queue = '', stash = '', enclose = false) => {
let result = [];
queue = [].concat(queue);
stash = [].concat(stash);
if (!stash.length) return queue;
if (!queue.length) {
return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
}
for (let item of queue) {
if (Array.isArray(item)) {
for (let value of item) {
result.push(append(value, stash, enclose));
}
} else {
for (let ele of stash) {
if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
}
}
}
return utils.flatten(result);
};
const expand = (ast, options = {}) => {
let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
let walk = (node, parent = {}) => {
node.queue = [];
let p = parent;
let q = parent.queue;
while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
p = p.parent;
q = p.queue;
}
if (node.invalid || node.dollar) {
q.push(append(q.pop(), stringify(node, options)));
return;
}
if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
q.push(append(q.pop(), ['{}']));
return;
}
if (node.nodes && node.ranges > 0) {
let args = utils.reduce(node.nodes);
if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
}
let range = fill(...args, options);
if (range.length === 0) {
range = stringify(node, options);
}
q.push(append(q.pop(), range));
node.nodes = [];
return;
}
let enclose = utils.encloseBrace(node);
let queue = node.queue;
let block = node;
while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
block = block.parent;
queue = block.queue;
}
for (let i = 0; i < node.nodes.length; i++) {
let child = node.nodes[i];
if (child.type === 'comma' && node.type === 'brace') {
if (i === 1) queue.push('');
queue.push('');
continue;
}
if (child.type === 'close') {
q.push(append(q.pop(), queue, enclose));
continue;
}
if (child.value && child.type !== 'open') {
queue.push(append(queue.pop(), child.value));
continue;
}
if (child.nodes) {
walk(child, node);
}
}
return queue;
};
return utils.flatten(walk(ast));
};
module.exports = expand;
/***/ }),
/***/ 6477:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const stringify = __nccwpck_require__(8750);
/**
* Constants
*/
const {
MAX_LENGTH,
CHAR_BACKSLASH, /* \ */
CHAR_BACKTICK, /* ` */
CHAR_COMMA, /* , */
CHAR_DOT, /* . */
CHAR_LEFT_PARENTHESES, /* ( */
CHAR_RIGHT_PARENTHESES, /* ) */
CHAR_LEFT_CURLY_BRACE, /* { */
CHAR_RIGHT_CURLY_BRACE, /* } */
CHAR_LEFT_SQUARE_BRACKET, /* [ */
CHAR_RIGHT_SQUARE_BRACKET, /* ] */
CHAR_DOUBLE_QUOTE, /* " */
CHAR_SINGLE_QUOTE, /* ' */
CHAR_NO_BREAK_SPACE,
CHAR_ZERO_WIDTH_NOBREAK_SPACE
} = __nccwpck_require__(8774);
/**
* parse
*/
const parse = (input, options = {}) => {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
let opts = options || {};
let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
if (input.length > max) {
throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
}
let ast = { type: 'root', input, nodes: [] };
let stack = [ast];
let block = ast;
let prev = ast;
let brackets = 0;
let length = input.length;
let index = 0;
let depth = 0;
let value;
let memo = {};
/**
* Helpers
*/
const advance = () => input[index++];
const push = node => {
if (node.type === 'text' && prev.type === 'dot') {
prev.type = 'text';
}
if (prev && prev.type === 'text' && node.type === 'text') {
prev.value += node.value;
return;
}
block.nodes.push(node);
node.parent = block;
node.prev = prev;
prev = node;
return node;
};
push({ type: 'bos' });
while (index < length) {
block = stack[stack.length - 1];
value = advance();
/**
* Invalid chars
*/
if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
continue;
}
/**
* Escaped chars
*/
if (value === CHAR_BACKSLASH) {
push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
continue;
}
/**
* Right square bracket (literal): ']'
*/
if (value === CHAR_RIGHT_SQUARE_BRACKET) {
push({ type: 'text', value: '\\' + value });
continue;
}
/**
* Left square bracket: '['
*/
if (value === CHAR_LEFT_SQUARE_BRACKET) {
brackets++;
let closed = true;
let next;
while (index < length && (next = advance())) {
value += next;
if (next === CHAR_LEFT_SQUARE_BRACKET) {
brackets++;
continue;
}
if (next === CHAR_BACKSLASH) {
value += advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
brackets--;
if (brackets === 0) {
break;
}
}
}
push({ type: 'text', value });
continue;
}
/**
* Parentheses
*/
if (value === CHAR_LEFT_PARENTHESES) {
block = push({ type: 'paren', nodes: [] });
stack.push(block);
push({ type: 'text', value });
continue;
}
if (value === CHAR_RIGHT_PARENTHESES) {
if (block.type !== 'paren') {
push({ type: 'text', value });
continue;
}
block = stack.pop();
push({ type: 'text', value });
block = stack[stack.length - 1];
continue;
}
/**
* Quotes: '|"|`
*/
if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
let open = value;
let next;
if (options.keepQuotes !== true) {
value = '';
}
while (index < length && (next = advance())) {
if (next === CHAR_BACKSLASH) {
value += next + advance();
continue;
}
if (next === open) {
if (options.keepQuotes === true) value += next;
break;
}
value += next;
}
push({ type: 'text', value });
continue;
}
/**
* Left curly brace: '{'
*/
if (value === CHAR_LEFT_CURLY_BRACE) {
depth++;
let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
let brace = {
type: 'brace',
open: true,
close: false,
dollar,
depth,
commas: 0,
ranges: 0,
nodes: []
};
block = push(brace);
stack.push(block);
push({ type: 'open', value });
continue;
}
/**
* Right curly brace: '}'
*/
if (value === CHAR_RIGHT_CURLY_BRACE) {
if (block.type !== 'brace') {
push({ type: 'text', value });
continue;
}
let type = 'close';
block = stack.pop();
block.close = true;
push({ type, value });
depth--;
block = stack[stack.length - 1];
continue;
}
/**
* Comma: ','
*/
if (value === CHAR_COMMA && depth > 0) {
if (block.ranges > 0) {
block.ranges = 0;
let open = block.nodes.shift();
block.nodes = [open, { type: 'text', value: stringify(block) }];
}
push({ type: 'comma', value });
block.commas++;
continue;
}
/**
* Dot: '.'
*/
if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
let siblings = block.nodes;
if (depth === 0 || siblings.length === 0) {
push({ type: 'text', value });
continue;
}
if (prev.type === 'dot') {
block.range = [];
prev.value += value;
prev.type = 'range';
if (block.nodes.length !== 3 && block.nodes.length !== 5) {
block.invalid = true;
block.ranges = 0;
prev.type = 'text';
continue;
}
block.ranges++;
block.args = [];
continue;
}
if (prev.type === 'range') {
siblings.pop();
let before = siblings[siblings.length - 1];
before.value += prev.value + value;
prev = before;
block.ranges--;
continue;
}
push({ type: 'dot', value });
continue;
}
/**
* Text
*/
push({ type: 'text', value });
}
// Mark imbalanced braces and brackets as invalid
do {
block = stack.pop();
if (block.type !== 'root') {
block.nodes.forEach(node => {
if (!node.nodes) {
if (node.type === 'open') node.isOpen = true;
if (node.type === 'close') node.isClose = true;
if (!node.nodes) node.type = 'text';
node.invalid = true;
}
});
// get the location of the block on parent.nodes (block's siblings)
let parent = stack[stack.length - 1];
let index = parent.nodes.indexOf(block);
// replace the (invalid) block with it's nodes
parent.nodes.splice(index, 1, ...block.nodes);
}
} while (stack.length > 0);
push({ type: 'eos' });
return ast;
};
module.exports = parse;
/***/ }),
/***/ 8750:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const utils = __nccwpck_require__(5207);
module.exports = (ast, options = {}) => {
let stringify = (node, parent = {}) => {
let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
let invalidNode = node.invalid === true && options.escapeInvalid === true;
let output = '';
if (node.value) {
if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
return '\\' + node.value;
}
return node.value;
}
if (node.value) {
return node.value;
}
if (node.nodes) {
for (let child of node.nodes) {
output += stringify(child);
}
}
return output;
};
return stringify(ast);
};
/***/ }),
/***/ 5207:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
exports.isInteger = num => {
if (typeof num === 'number') {
return Number.isInteger(num);
}
if (typeof num === 'string' && num.trim() !== '') {
return Number.isInteger(Number(num));
}
return false;
};
/**
* Find a node of the given type
*/
exports.find = (node, type) => node.nodes.find(node => node.type === type);
/**
* Find a node of the given type
*/
exports.exceedsLimit = (min, max, step = 1, limit) => {
if (limit === false) return false;
if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
return ((Number(max) - Number(min)) / Number(step)) >= limit;
};
/**
* Escape the given node with '\\' before node.value
*/
exports.escapeNode = (block, n = 0, type) => {
let node = block.nodes[n];
if (!node) return;
if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
if (node.escaped !== true) {
node.value = '\\' + node.value;
node.escaped = true;
}
}
};
/**
* Returns true if the given brace node should be enclosed in literal braces
*/
exports.encloseBrace = node => {
if (node.type !== 'brace') return false;
if ((node.commas >> 0 + node.ranges >> 0) === 0) {
node.invalid = true;
return true;
}
return false;
};
/**
* Returns true if a brace node is invalid.
*/
exports.isInvalidBrace = block => {
if (block.type !== 'brace') return false;
if (block.invalid === true || block.dollar) return true;
if ((block.commas >> 0 + block.ranges >> 0) === 0) {
block.invalid = true;
return true;
}
if (block.open !== true || block.close !== true) {
block.invalid = true;
return true;
}
return false;
};
/**
* Returns true if a node is an open or close node
*/
exports.isOpenOrClose = node => {
if (node.type === 'open' || node.type === 'close') {
return true;
}
return node.open === true || node.close === true;
};
/**
* Reduce an array of text nodes.
*/
exports.reduce = nodes => nodes.reduce((acc, node) => {
if (node.type === 'text') acc.push(node.value);
if (node.type === 'range') node.type = 'text';
return acc;
}, []);
/**
* Flatten an array
*/
exports.flatten = (...args) => {
const result = [];
const flat = arr => {
for (let i = 0; i < arr.length; i++) {
let ele = arr[i];
Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele);
}
return result;
};
flat(args);
return result;
};
/***/ }),
/***/ 2371:
/***/ ((module) => {
"use strict";
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @return {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 {
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;
}
module.exports = dataUriToBuffer;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 8932:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class Deprecation extends Error {
constructor(message) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = 'Deprecation';
}
}
exports.Deprecation = Deprecation;
/***/ }),
/***/ 3664:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const taskManager = __nccwpck_require__(2708);
const async_1 = __nccwpck_require__(5679);
const stream_1 = __nccwpck_require__(4630);
const sync_1 = __nccwpck_require__(2405);
const settings_1 = __nccwpck_require__(952);
const utils = __nccwpck_require__(5444);
async function FastGlob(source, options) {
assertPatternsInput(source);
const works = getWorks(source, async_1.default, options);
const result = await Promise.all(works);
return utils.array.flatten(result);
}
// https://github.com/typescript-eslint/typescript-eslint/issues/60
// eslint-disable-next-line no-redeclare
(function (FastGlob) {
function sync(source, options) {
assertPatternsInput(source);
const works = getWorks(source, sync_1.default, options);
return utils.array.flatten(works);
}
FastGlob.sync = sync;
function stream(source, options) {
assertPatternsInput(source);
const works = getWorks(source, stream_1.default, options);
/**
* The stream returned by the provider cannot work with an asynchronous iterator.
* To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
* This affects performance (+25%). I don't see best solution right now.
*/
return utils.stream.merge(works);
}
FastGlob.stream = stream;
function generateTasks(source, options) {
assertPatternsInput(source);
const patterns = [].concat(source);
const settings = new settings_1.default(options);
return taskManager.generate(patterns, settings);
}
FastGlob.generateTasks = generateTasks;
function isDynamicPattern(source, options) {
assertPatternsInput(source);
const settings = new settings_1.default(options);
return utils.pattern.isDynamicPattern(source, settings);
}
FastGlob.isDynamicPattern = isDynamicPattern;
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escape(source);
}
FastGlob.escapePath = escapePath;
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options) {
const patterns = [].concat(source);
const settings = new settings_1.default(options);
const tasks = taskManager.generate(patterns, settings);
const provider = new _Provider(settings);
return tasks.map(provider.read, provider);
}
function assertPatternsInput(input) {
const source = [].concat(input);
const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
if (!isValidSource) {
throw new TypeError('Patterns must be a string (non empty) or an array of strings');
}
}
module.exports = FastGlob;
/***/ }),
/***/ 2708:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
const utils = __nccwpck_require__(5444);
function generate(patterns, settings) {
const positivePatterns = getPositivePatterns(patterns);
const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings));
const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings));
const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
return staticTasks.concat(dynamicTasks);
}
exports.generate = generate;
/**
* Returns tasks grouped by basic pattern directories.
*
* Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
* This is necessary because directory traversal starts at the base directory and goes deeper.
*/
function convertPatternsToTasks(positive, negative, dynamic) {
const tasks = [];
const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive);
const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive);
const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
/*
* For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
* into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
*/
if ('.' in insideCurrentDirectoryGroup) {
tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
}
else {
tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
}
return tasks;
}
exports.convertPatternsToTasks = convertPatternsToTasks;
function getPositivePatterns(patterns) {
return utils.pattern.getPositivePatterns(patterns);
}
exports.getPositivePatterns = getPositivePatterns;
function getNegativePatternsAsPositive(patterns, ignore) {
const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore);
const positive = negative.map(utils.pattern.convertToPositivePattern);
return positive;
}
exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
function groupPatternsByBaseDirectory(patterns) {
const group = {};
return patterns.reduce((collection, pattern) => {
const base = utils.pattern.getBaseDirectory(pattern);
if (base in collection) {
collection[base].push(pattern);
}
else {
collection[base] = [pattern];
}
return collection;
}, group);
}
exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
function convertPatternGroupsToTasks(positive, negative, dynamic) {
return Object.keys(positive).map((base) => {
return convertPatternGroupToTask(base, positive[base], negative, dynamic);
});
}
exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
function convertPatternGroupToTask(base, positive, negative, dynamic) {
return {
dynamic,
positive,
negative,
base,
patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern))
};
}
exports.convertPatternGroupToTask = convertPatternGroupToTask;
/***/ }),
/***/ 5679:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const stream_1 = __nccwpck_require__(2083);
const provider_1 = __nccwpck_require__(257);
class ProviderAsync extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new stream_1.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = [];
return new Promise((resolve, reject) => {
const stream = this.api(root, task, options);
stream.once('error', reject);
stream.on('data', (entry) => entries.push(options.transform(entry)));
stream.once('end', () => resolve(entries));
});
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderAsync;
/***/ }),
/***/ 6983:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const utils = __nccwpck_require__(5444);
const partial_1 = __nccwpck_require__(5295);
class DeepFilter {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
}
getFilter(basePath, positive, negative) {
const matcher = this._getMatcher(positive);
const negativeRe = this._getNegativePatternsRe(negative);
return (entry) => this._filter(basePath, entry, matcher, negativeRe);
}
_getMatcher(patterns) {
return new partial_1.default(patterns, this._settings, this._micromatchOptions);
}
_getNegativePatternsRe(patterns) {
const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern);
return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
}
_filter(basePath, entry, matcher, negativeRe) {
if (this._isSkippedByDeep(basePath, entry.path)) {
return false;
}
if (this._isSkippedSymbolicLink(entry)) {
return false;
}
const filepath = utils.path.removeLeadingDotSegment(entry.path);
if (this._isSkippedByPositivePatterns(filepath, matcher)) {
return false;
}
return this._isSkippedByNegativePatterns(filepath, negativeRe);
}
_isSkippedByDeep(basePath, entryPath) {
/**
* Avoid unnecessary depth calculations when it doesn't matter.
*/
if (this._settings.deep === Infinity) {
return false;
}
return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
}
_getEntryLevel(basePath, entryPath) {
const entryPathDepth = entryPath.split('/').length;
if (basePath === '') {
return entryPathDepth;
}
const basePathDepth = basePath.split('/').length;
return entryPathDepth - basePathDepth;
}
_isSkippedSymbolicLink(entry) {
return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
}
_isSkippedByPositivePatterns(entryPath, matcher) {
return !this._settings.baseNameMatch && !matcher.match(entryPath);
}
_isSkippedByNegativePatterns(entryPath, patternsRe) {
return !utils.pattern.matchAny(entryPath, patternsRe);
}
}
exports.default = DeepFilter;
/***/ }),
/***/ 1343:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const utils = __nccwpck_require__(5444);
class EntryFilter {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this.index = new Map();
}
getFilter(positive, negative) {
const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions);
const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions);
return (entry) => this._filter(entry, positiveRe, negativeRe);
}
_filter(entry, positiveRe, negativeRe) {
if (this._settings.unique && this._isDuplicateEntry(entry)) {
return false;
}
if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
return false;
}
if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
return false;
}
const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
if (this._settings.unique && isMatched) {
this._createIndexRecord(entry);
}
return isMatched;
}
_isDuplicateEntry(entry) {
return this.index.has(entry.path);
}
_createIndexRecord(entry) {
this.index.set(entry.path, undefined);
}
_onlyFileFilter(entry) {
return this._settings.onlyFiles && !entry.dirent.isFile();
}
_onlyDirectoryFilter(entry) {
return this._settings.onlyDirectories && !entry.dirent.isDirectory();
}
_isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
if (!this._settings.absolute) {
return false;
}
const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath);
return utils.pattern.matchAny(fullpath, patternsRe);
}
_isMatchToPatterns(entryPath, patternsRe) {
const filepath = utils.path.removeLeadingDotSegment(entryPath);
return utils.pattern.matchAny(filepath, patternsRe);
}
}
exports.default = EntryFilter;
/***/ }),
/***/ 6654:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const utils = __nccwpck_require__(5444);
class ErrorFilter {
constructor(_settings) {
this._settings = _settings;
}
getFilter() {
return (error) => this._isNonFatalError(error);
}
_isNonFatalError(error) {
return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
}
}
exports.default = ErrorFilter;
/***/ }),
/***/ 2576:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const utils = __nccwpck_require__(5444);
class Matcher {
constructor(_patterns, _settings, _micromatchOptions) {
this._patterns = _patterns;
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this._storage = [];
this._fillStorage();
}
_fillStorage() {
/**
* The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
* So, before expand patterns with brace expansion into separated patterns.
*/
const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns);
for (const pattern of patterns) {
const segments = this._getPatternSegments(pattern);
const sections = this._splitSegmentsIntoSections(segments);
this._storage.push({
complete: sections.length <= 1,
pattern,
segments,
sections
});
}
}
_getPatternSegments(pattern) {
const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions);
return parts.map((part) => {
const dynamic = utils.pattern.isDynamicPattern(part, this._settings);
if (!dynamic) {
return {
dynamic: false,
pattern: part
};
}
return {
dynamic: true,
pattern: part,
patternRe: utils.pattern.makeRe(part, this._micromatchOptions)
};
});
}
_splitSegmentsIntoSections(segments) {
return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern));
}
}
exports.default = Matcher;
/***/ }),
/***/ 5295:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const matcher_1 = __nccwpck_require__(2576);
class PartialMatcher extends matcher_1.default {
match(filepath) {
const parts = filepath.split('/');
const levels = parts.length;
const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
for (const pattern of patterns) {
const section = pattern.sections[0];
/**
* In this case, the pattern has a globstar and we must read all directories unconditionally,
* but only if the level has reached the end of the first group.
*
* fixtures/{a,b}/**
* ^ true/false ^ always true
*/
if (!pattern.complete && levels > section.length) {
return true;
}
const match = parts.every((part, index) => {
const segment = pattern.segments[index];
if (segment.dynamic && segment.patternRe.test(part)) {
return true;
}
if (!segment.dynamic && segment.pattern === part) {
return true;
}
return false;
});
if (match) {
return true;
}
}
return false;
}
}
exports.default = PartialMatcher;
/***/ }),
/***/ 257:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const path = __nccwpck_require__(5622);
const deep_1 = __nccwpck_require__(6983);
const entry_1 = __nccwpck_require__(1343);
const error_1 = __nccwpck_require__(6654);
const entry_2 = __nccwpck_require__(4029);
class Provider {
constructor(_settings) {
this._settings = _settings;
this.errorFilter = new error_1.default(this._settings);
this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
this.entryTransformer = new entry_2.default(this._settings);
}
_getRootDirectory(task) {
return path.resolve(this._settings.cwd, task.base);
}
_getReaderOptions(task) {
const basePath = task.base === '.' ? '' : task.base;
return {
basePath,
pathSegmentSeparator: '/',
concurrency: this._settings.concurrency,
deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
errorFilter: this.errorFilter.getFilter(),
followSymbolicLinks: this._settings.followSymbolicLinks,
fs: this._settings.fs,
stats: this._settings.stats,
throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
transform: this.entryTransformer.getTransformer()
};
}
_getMicromatchOptions() {
return {
dot: this._settings.dot,
matchBase: this._settings.baseNameMatch,
nobrace: !this._settings.braceExpansion,
nocase: !this._settings.caseSensitiveMatch,
noext: !this._settings.extglob,
noglobstar: !this._settings.globstar,
posix: true,
strictSlashes: false
};
}
}
exports.default = Provider;
/***/ }),
/***/ 4630:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const stream_1 = __nccwpck_require__(2413);
const stream_2 = __nccwpck_require__(2083);
const provider_1 = __nccwpck_require__(257);
class ProviderStream extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new stream_2.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const source = this.api(root, task, options);
const destination = new stream_1.Readable({ objectMode: true, read: () => { } });
source
.once('error', (error) => destination.emit('error', error))
.on('data', (entry) => destination.emit('data', options.transform(entry)))
.once('end', () => destination.emit('end'));
destination
.once('close', () => source.destroy());
return destination;
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderStream;
/***/ }),
/***/ 2405:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
2021-10-01 09:38:36 -04:00
const sync_1 = __nccwpck_require__(6234);
2021-09-26 15:31:45 -04:00
const provider_1 = __nccwpck_require__(257);
class ProviderSync extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new sync_1.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = this.api(root, task, options);
return entries.map(options.transform);
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderSync;
/***/ }),
/***/ 4029:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const utils = __nccwpck_require__(5444);
class EntryTransformer {
constructor(_settings) {
this._settings = _settings;
}
getTransformer() {
return (entry) => this._transform(entry);
}
_transform(entry) {
let filepath = entry.path;
if (this._settings.absolute) {
filepath = utils.path.makeAbsolute(this._settings.cwd, filepath);
filepath = utils.path.unixify(filepath);
}
if (this._settings.markDirectories && entry.dirent.isDirectory()) {
filepath += '/';
}
if (!this._settings.objectMode) {
return filepath;
}
return Object.assign(Object.assign({}, entry), { path: filepath });
}
}
exports.default = EntryTransformer;
/***/ }),
/***/ 5582:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const path = __nccwpck_require__(5622);
const fsStat = __nccwpck_require__(109);
const utils = __nccwpck_require__(5444);
class Reader {
constructor(_settings) {
this._settings = _settings;
this._fsStatSettings = new fsStat.Settings({
followSymbolicLink: this._settings.followSymbolicLinks,
fs: this._settings.fs,
throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
});
}
_getFullEntryPath(filepath) {
return path.resolve(this._settings.cwd, filepath);
}
_makeEntry(stats, pattern) {
const entry = {
name: pattern,
path: pattern,
dirent: utils.fs.createDirentFromStats(pattern, stats)
};
if (this._settings.stats) {
entry.stats = stats;
}
return entry;
}
_isFatalError(error) {
return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
}
}
exports.default = Reader;
/***/ }),
/***/ 2083:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const stream_1 = __nccwpck_require__(2413);
const fsStat = __nccwpck_require__(109);
const fsWalk = __nccwpck_require__(6026);
const reader_1 = __nccwpck_require__(5582);
class ReaderStream extends reader_1.default {
constructor() {
super(...arguments);
this._walkStream = fsWalk.walkStream;
this._stat = fsStat.stat;
}
dynamic(root, options) {
return this._walkStream(root, options);
}
static(patterns, options) {
const filepaths = patterns.map(this._getFullEntryPath, this);
const stream = new stream_1.PassThrough({ objectMode: true });
stream._write = (index, _enc, done) => {
return this._getEntry(filepaths[index], patterns[index], options)
.then((entry) => {
if (entry !== null && options.entryFilter(entry)) {
stream.push(entry);
}
if (index === filepaths.length - 1) {
stream.end();
}
done();
})
.catch(done);
};
for (let i = 0; i < filepaths.length; i++) {
stream.write(i);
}
return stream;
}
_getEntry(filepath, pattern, options) {
return this._getStat(filepath)
.then((stats) => this._makeEntry(stats, pattern))
.catch((error) => {
if (options.errorFilter(error)) {
return null;
}
throw error;
});
}
_getStat(filepath) {
return new Promise((resolve, reject) => {
this._stat(filepath, this._fsStatSettings, (error, stats) => {
return error === null ? resolve(stats) : reject(error);
});
});
}
}
exports.default = ReaderStream;
/***/ }),
2021-10-01 09:38:36 -04:00
/***/ 6234:
2021-09-26 15:31:45 -04:00
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const fsStat = __nccwpck_require__(109);
const fsWalk = __nccwpck_require__(6026);
const reader_1 = __nccwpck_require__(5582);
class ReaderSync extends reader_1.default {
constructor() {
super(...arguments);
this._walkSync = fsWalk.walkSync;
this._statSync = fsStat.statSync;
}
dynamic(root, options) {
return this._walkSync(root, options);
}
static(patterns, options) {
const entries = [];
for (const pattern of patterns) {
const filepath = this._getFullEntryPath(pattern);
const entry = this._getEntry(filepath, pattern, options);
if (entry === null || !options.entryFilter(entry)) {
continue;
}
entries.push(entry);
}
return entries;
}
_getEntry(filepath, pattern, options) {
try {
const stats = this._getStat(filepath);
return this._makeEntry(stats, pattern);
}
catch (error) {
if (options.errorFilter(error)) {
return null;
}
throw error;
}
}
_getStat(filepath) {
return this._statSync(filepath, this._fsStatSettings);
}
}
exports.default = ReaderSync;
/***/ }),
/***/ 952:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
const fs = __nccwpck_require__(5747);
const os = __nccwpck_require__(2087);
/**
* The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
* https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
*/
const CPU_COUNT = Math.max(os.cpus().length, 1);
exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
lstatSync: fs.lstatSync,
stat: fs.stat,
statSync: fs.statSync,
readdir: fs.readdir,
readdirSync: fs.readdirSync
};
class Settings {
constructor(_options = {}) {
this._options = _options;
this.absolute = this._getValue(this._options.absolute, false);
this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
this.braceExpansion = this._getValue(this._options.braceExpansion, true);
this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
this.cwd = this._getValue(this._options.cwd, process.cwd());
this.deep = this._getValue(this._options.deep, Infinity);
this.dot = this._getValue(this._options.dot, false);
this.extglob = this._getValue(this._options.extglob, true);
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
this.fs = this._getFileSystemMethods(this._options.fs);
this.globstar = this._getValue(this._options.globstar, true);
this.ignore = this._getValue(this._options.ignore, []);
this.markDirectories = this._getValue(this._options.markDirectories, false);
this.objectMode = this._getValue(this._options.objectMode, false);
this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
this.onlyFiles = this._getValue(this._options.onlyFiles, true);
this.stats = this._getValue(this._options.stats, false);
this.suppressErrors = this._getValue(this._options.suppressErrors, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
this.unique = this._getValue(this._options.unique, true);
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
}
_getValue(option, value) {
return option === undefined ? value : option;
}
_getFileSystemMethods(methods = {}) {
return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
}
}
exports.default = Settings;
/***/ }),
/***/ 5325:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.splitWhen = exports.flatten = void 0;
function flatten(items) {
return items.reduce((collection, item) => [].concat(collection, item), []);
}
exports.flatten = flatten;
function splitWhen(items, predicate) {
const result = [[]];
let groupIndex = 0;
for (const item of items) {
if (predicate(item)) {
groupIndex++;
result[groupIndex] = [];
}
else {
result[groupIndex].push(item);
}
}
return result;
}
exports.splitWhen = splitWhen;
/***/ }),
/***/ 1230:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isEnoentCodeError = void 0;
function isEnoentCodeError(error) {
return error.code === 'ENOENT';
}
exports.isEnoentCodeError = isEnoentCodeError;
/***/ }),
/***/ 7543:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDirentFromStats = void 0;
class DirentFromStats {
constructor(name, stats) {
this.name = name;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
}
function createDirentFromStats(name, stats) {
return new DirentFromStats(name, stats);
}
exports.createDirentFromStats = createDirentFromStats;
/***/ }),
/***/ 5444:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
const array = __nccwpck_require__(5325);
exports.array = array;
const errno = __nccwpck_require__(1230);
exports.errno = errno;
const fs = __nccwpck_require__(7543);
exports.fs = fs;
const path = __nccwpck_require__(3873);
exports.path = path;
const pattern = __nccwpck_require__(1221);
exports.pattern = pattern;
const stream = __nccwpck_require__(8382);
exports.stream = stream;
const string = __nccwpck_require__(2203);
exports.string = string;
/***/ }),
/***/ 3873:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
const path = __nccwpck_require__(5622);
const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
/**
* Designed to work only with simple paths: `dir\\file`.
*/
function unixify(filepath) {
return filepath.replace(/\\/g, '/');
}
exports.unixify = unixify;
function makeAbsolute(cwd, filepath) {
return path.resolve(cwd, filepath);
}
exports.makeAbsolute = makeAbsolute;
function escape(pattern) {
return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
}
exports.escape = escape;
function removeLeadingDotSegment(entry) {
// We do not use `startsWith` because this is 10x slower than current implementation for some cases.
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (entry.charAt(0) === '.') {
const secondCharactery = entry.charAt(1);
if (secondCharactery === '/' || secondCharactery === '\\') {
return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
}
}
return entry;
}
exports.removeLeadingDotSegment = removeLeadingDotSegment;
/***/ }),
/***/ 1221:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
const path = __nccwpck_require__(5622);
const globParent = __nccwpck_require__(4655);
const micromatch = __nccwpck_require__(6228);
const GLOBSTAR = '**';
const ESCAPE_SYMBOL = '\\';
const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
function isStaticPattern(pattern, options = {}) {
return !isDynamicPattern(pattern, options);
}
exports.isStaticPattern = isStaticPattern;
function isDynamicPattern(pattern, options = {}) {
/**
* A special case with an empty string is necessary for matching patterns that start with a forward slash.
* An empty string cannot be a dynamic pattern.
* For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
*/
if (pattern === '') {
return false;
}
/**
* When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
* filepath directly (without read directory).
*/
if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
return true;
}
if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
return true;
}
return false;
}
exports.isDynamicPattern = isDynamicPattern;
function convertToPositivePattern(pattern) {
return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
}
exports.convertToPositivePattern = convertToPositivePattern;
function convertToNegativePattern(pattern) {
return '!' + pattern;
}
exports.convertToNegativePattern = convertToNegativePattern;
function isNegativePattern(pattern) {
return pattern.startsWith('!') && pattern[1] !== '(';
}
exports.isNegativePattern = isNegativePattern;
function isPositivePattern(pattern) {
return !isNegativePattern(pattern);
}
exports.isPositivePattern = isPositivePattern;
function getNegativePatterns(patterns) {
return patterns.filter(isNegativePattern);
}
exports.getNegativePatterns = getNegativePatterns;
function getPositivePatterns(patterns) {
return patterns.filter(isPositivePattern);
}
exports.getPositivePatterns = getPositivePatterns;
/**
* Returns patterns that can be applied inside the current directory.
*
* @example
* // ['./*', '*', 'a/*']
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
function getPatternsInsideCurrentDirectory(patterns) {
return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
}
exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
/**
* Returns patterns to be expanded relative to (outside) the current directory.
*
* @example
* // ['../*', './../*']
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
function getPatternsOutsideCurrentDirectory(patterns) {
return patterns.filter(isPatternRelatedToParentDirectory);
}
exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
function isPatternRelatedToParentDirectory(pattern) {
return pattern.startsWith('..') || pattern.startsWith('./..');
}
exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
function getBaseDirectory(pattern) {
return globParent(pattern, { flipBackslashes: false });
}
exports.getBaseDirectory = getBaseDirectory;
function hasGlobStar(pattern) {
return pattern.includes(GLOBSTAR);
}
exports.hasGlobStar = hasGlobStar;
function endsWithSlashGlobStar(pattern) {
return pattern.endsWith('/' + GLOBSTAR);
}
exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
function isAffectDepthOfReadingPattern(pattern) {
const basename = path.basename(pattern);
return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
}
exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
function expandPatternsWithBraceExpansion(patterns) {
return patterns.reduce((collection, pattern) => {
return collection.concat(expandBraceExpansion(pattern));
}, []);
}
exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
function expandBraceExpansion(pattern) {
return micromatch.braces(pattern, {
expand: true,
nodupes: true
});
}
exports.expandBraceExpansion = expandBraceExpansion;
function getPatternParts(pattern, options) {
let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
/**
* The scan method returns an empty array in some cases.
* See micromatch/picomatch#58 for more details.
*/
if (parts.length === 0) {
parts = [pattern];
}
/**
* The scan method does not return an empty part for the pattern with a forward slash.
* This is another part of micromatch/picomatch#58.
*/
if (parts[0].startsWith('/')) {
parts[0] = parts[0].slice(1);
parts.unshift('');
}
return parts;
}
exports.getPatternParts = getPatternParts;
function makeRe(pattern, options) {
return micromatch.makeRe(pattern, options);
}
exports.makeRe = makeRe;
function convertPatternsToRe(patterns, options) {
return patterns.map((pattern) => makeRe(pattern, options));
}
exports.convertPatternsToRe = convertPatternsToRe;
function matchAny(entry, patternsRe) {
return patternsRe.some((patternRe) => patternRe.test(entry));
}
exports.matchAny = matchAny;
/***/ }),
/***/ 8382:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.merge = void 0;
const merge2 = __nccwpck_require__(2578);
function merge(streams) {
const mergedStream = merge2(streams);
streams.forEach((stream) => {
stream.once('error', (error) => mergedStream.emit('error', error));
});
mergedStream.once('close', () => propagateCloseEventToSources(streams));
mergedStream.once('end', () => propagateCloseEventToSources(streams));
return mergedStream;
}
exports.merge = merge;
function propagateCloseEventToSources(streams) {
streams.forEach((stream) => stream.emit('close'));
}
/***/ }),
/***/ 2203:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isEmpty = exports.isString = void 0;
function isString(input) {
return typeof input === 'string';
}
exports.isString = isString;
function isEmpty(input) {
return input === '';
}
exports.isEmpty = isEmpty;
/***/ }),
/***/ 7340:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/* eslint-disable no-var */
var reusify = __nccwpck_require__(2113)
function fastqueue (context, worker, concurrency) {
if (typeof context === 'function') {
concurrency = worker
worker = context
context = null
}
if (concurrency < 1) {
throw new Error('fastqueue concurrency must be greater than 1')
}
var cache = reusify(Task)
var queueHead = null
var queueTail = null
var _running = 0
var errorHandler = null
var self = {
push: push,
drain: noop,
saturated: noop,
pause: pause,
paused: false,
concurrency: concurrency,
running: running,
resume: resume,
idle: idle,
length: length,
getQueue: getQueue,
unshift: unshift,
empty: noop,
kill: kill,
killAndDrain: killAndDrain,
error: error
}
return self
function running () {
return _running
}
function pause () {
self.paused = true
}
function length () {
var current = queueHead
var counter = 0
while (current) {
current = current.next
counter++
}
return counter
}
function getQueue () {
var current = queueHead
var tasks = []
while (current) {
tasks.push(current.value)
current = current.next
}
return tasks
}
function resume () {
if (!self.paused) return
self.paused = false
for (var i = 0; i < self.concurrency; i++) {
_running++
release()
}
}
function idle () {
return _running === 0 && self.length() === 0
}
function push (value, done) {
var current = cache.get()
current.context = context
current.release = release
current.value = value
current.callback = done || noop
current.errorHandler = errorHandler
if (_running === self.concurrency || self.paused) {
if (queueTail) {
queueTail.next = current
queueTail = current
} else {
queueHead = current
queueTail = current
self.saturated()
}
} else {
_running++
worker.call(context, current.value, current.worked)
}
}
function unshift (value, done) {
var current = cache.get()
current.context = context
current.release = release
current.value = value
current.callback = done || noop
if (_running === self.concurrency || self.paused) {
if (queueHead) {
current.next = queueHead
queueHead = current
} else {
queueHead = current
queueTail = current
self.saturated()
}
} else {
_running++
worker.call(context, current.value, current.worked)
}
}
function release (holder) {
if (holder) {
cache.release(holder)
}
var next = queueHead
if (next) {
if (!self.paused) {
if (queueTail === queueHead) {
queueTail = null
}
queueHead = next.next
next.next = null
worker.call(context, next.value, next.worked)
if (queueTail === null) {
self.empty()
}
} else {
_running--
}
} else if (--_running === 0) {
self.drain()
}
}
function kill () {
queueHead = null
queueTail = null
self.drain = noop
}
function killAndDrain () {
queueHead = null
queueTail = null
self.drain()
self.drain = noop
}
function error (handler) {
errorHandler = handler
}
}
function noop () {}
function Task () {
this.value = null
this.callback = noop
this.next = null
this.release = noop
this.context = null
this.errorHandler = null
var self = this
this.worked = function worked (err, result) {
var callback = self.callback
var errorHandler = self.errorHandler
var val = self.value
self.value = null
self.callback = noop
if (self.errorHandler) {
errorHandler(err, val)
}
callback.call(self.context, err, result)
self.release(self)
}
}
function queueAsPromised (context, worker, concurrency) {
if (typeof context === 'function') {
concurrency = worker
worker = context
context = null
}
function asyncWrapper (arg, cb) {
worker.call(this, arg)
.then(function (res) {
cb(null, res)
}, cb)
}
var queue = fastqueue(context, asyncWrapper, concurrency)
var pushCb = queue.push
var unshiftCb = queue.unshift
queue.push = push
queue.unshift = unshift
queue.drained = drained
return queue
function push (value) {
var p = new Promise(function (resolve, reject) {
pushCb(value, function (err, result) {
if (err) {
reject(err)
return
}
resolve(result)
})
})
// Let's fork the promise chain to
// make the error bubble up to the user but
// not lead to a unhandledRejection
p.catch(noop)
return p
}
function unshift (value) {
var p = new Promise(function (resolve, reject) {
unshiftCb(value, function (err, result) {
if (err) {
reject(err)
return
}
resolve(result)
})
})
// Let's fork the promise chain to
// make the error bubble up to the user but
// not lead to a unhandledRejection
p.catch(noop)
return p
}
function drained () {
var previousDrain = queue.drain
var p = new Promise(function (resolve) {
queue.drain = function () {
previousDrain()
resolve()
}
})
return p
}
}
module.exports = fastqueue
module.exports.promise = queueAsPromised
/***/ }),
/***/ 6330:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Licensed under the MIT License.
*/
const util = __nccwpck_require__(1669);
const toRegexRange = __nccwpck_require__(1861);
const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
const transform = toNumber => {
return value => toNumber === true ? Number(value) : String(value);
};
const isValidValue = value => {
return typeof value === 'number' || (typeof value === 'string' && value !== '');
};
const isNumber = num => Number.isInteger(+num);
const zeros = input => {
let value = `${input}`;
let index = -1;
if (value[0] === '-') value = value.slice(1);
if (value === '0') return false;
while (value[++index] === '0');
return index > 0;
};
const stringify = (start, end, options) => {
if (typeof start === 'string' || typeof end === 'string') {
return true;
}
return options.stringify === true;
};
const pad = (input, maxLength, toNumber) => {
if (maxLength > 0) {
let dash = input[0] === '-' ? '-' : '';
if (dash) input = input.slice(1);
input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
}
if (toNumber === false) {
return String(input);
}
return input;
};
const toMaxLen = (input, maxLength) => {
let negative = input[0] === '-' ? '-' : '';
if (negative) {
input = input.slice(1);
maxLength--;
}
while (input.length < maxLength) input = '0' + input;
return negative ? ('-' + input) : input;
};
const toSequence = (parts, options) => {
parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
let prefix = options.capture ? '' : '?:';
let positives = '';
let negatives = '';
let result;
if (parts.positives.length) {
positives = parts.positives.join('|');
}
if (parts.negatives.length) {
negatives = `-(${prefix}${parts.negatives.join('|')})`;
}
if (positives && negatives) {
result = `${positives}|${negatives}`;
} else {
result = positives || negatives;
}
if (options.wrap) {
return `(${prefix}${result})`;
}
return result;
};
const toRange = (a, b, isNumbers, options) => {
if (isNumbers) {
return toRegexRange(a, b, { wrap: false, ...options });
}
let start = String.fromCharCode(a);
if (a === b) return start;
let stop = String.fromCharCode(b);
return `[${start}-${stop}]`;
};
const toRegex = (start, end, options) => {
if (Array.isArray(start)) {
let wrap = options.wrap === true;
let prefix = options.capture ? '' : '?:';
return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
}
return toRegexRange(start, end, options);
};
const rangeError = (...args) => {
return new RangeError('Invalid range arguments: ' + util.inspect(...args));
};
const invalidRange = (start, end, options) => {
if (options.strictRanges === true) throw rangeError([start, end]);
return [];
};
const invalidStep = (step, options) => {
if (options.strictRanges === true) {
throw new TypeError(`Expected step "${step}" to be a number`);
}
return [];
};
const fillNumbers = (start, end, step = 1, options = {}) => {
let a = Number(start);
let b = Number(end);
if (!Number.isInteger(a) || !Number.isInteger(b)) {
if (options.strictRanges === true) throw rangeError([start, end]);
return [];
}
// fix negative zero
if (a === 0) a = 0;
if (b === 0) b = 0;
let descending = a > b;
let startString = String(start);
let endString = String(end);
let stepString = String(step);
step = Math.max(Math.abs(step), 1);
let padded = zeros(startString) || zeros(endString) || zeros(stepString);
let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
let toNumber = padded === false && stringify(start, end, options) === false;
let format = options.transform || transform(toNumber);
if (options.toRegex && step === 1) {
return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
}
let parts = { negatives: [], positives: [] };
let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
let range = [];
let index = 0;
while (descending ? a >= b : a <= b) {
if (options.toRegex === true && step > 1) {
push(a);
} else {
range.push(pad(format(a, index), maxLen, toNumber));
}
a = descending ? a - step : a + step;
index++;
}
if (options.toRegex === true) {
return step > 1
? toSequence(parts, options)
: toRegex(range, null, { wrap: false, ...options });
}
return range;
};
const fillLetters = (start, end, step = 1, options = {}) => {
if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
return invalidRange(start, end, options);
}
let format = options.transform || (val => String.fromCharCode(val));
let a = `${start}`.charCodeAt(0);
let b = `${end}`.charCodeAt(0);
let descending = a > b;
let min = Math.min(a, b);
let max = Math.max(a, b);
if (options.toRegex && step === 1) {
return toRange(min, max, false, options);
}
let range = [];
let index = 0;
while (descending ? a >= b : a <= b) {
range.push(format(a, index));
a = descending ? a - step : a + step;
index++;
}
if (options.toRegex === true) {
return toRegex(range, null, { wrap: false, options });
}
return range;
};
const fill = (start, end, step, options = {}) => {
if (end == null && isValidValue(start)) {
return [start];
}
if (!isValidValue(start) || !isValidValue(end)) {
return invalidRange(start, end, options);
}
if (typeof step === 'function') {
return fill(start, end, 1, { transform: step });
}
if (isObject(step)) {
return fill(start, end, 0, step);
}
let opts = { ...options };
if (opts.capture === true) opts.wrap = true;
step = step || opts.step || 1;
if (!isNumber(step)) {
if (step != null && !isObject(step)) return invalidStep(step, opts);
return fill(start, end, 1, step);
}
if (isNumber(start) && isNumber(end)) {
return fillNumbers(start, end, step, opts);
}
return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
};
module.exports = fill;
/***/ }),
/***/ 4655:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
var isGlob = __nccwpck_require__(4466);
var pathPosixDirname = __nccwpck_require__(5622).posix.dirname;
var isWin32 = __nccwpck_require__(2087).platform() === 'win32';
var slash = '/';
var backslash = /\\/g;
var enclosure = /[\{\[].*[\}\]]$/;
var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
/**
* @param {string} str
* @param {Object} opts
* @param {boolean} [opts.flipBackslashes=true]
* @returns {string}
*/
module.exports = function globParent(str, opts) {
var options = Object.assign({ flipBackslashes: true }, opts);
// flip windows path separators
if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
str = str.replace(backslash, slash);
}
// special case for strings ending in enclosure containing path separator
if (enclosure.test(str)) {
str += slash;
}
// preserves full path in case of trailing path separator
str += 'a';
// remove path parts that are globby
do {
str = pathPosixDirname(str);
} while (isGlob(str) || globby.test(str));
// remove escape chars and return result
return str.replace(escaped, '$1');
};
/***/ }),
/***/ 6435:
/***/ ((module) => {
/*!
* is-extglob <https://github.com/jonschlinkert/is-extglob>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
module.exports = function isExtglob(str) {
if (typeof str !== 'string' || str === '') {
return false;
}
var match;
while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
if (match[2]) return true;
str = str.slice(match.index + match[0].length);
}
return false;
};
/***/ }),
/***/ 4466:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/*!
* is-glob <https://github.com/jonschlinkert/is-glob>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
var isExtglob = __nccwpck_require__(6435);
var chars = { '{': '}', '(': ')', '[': ']'};
var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
module.exports = function isGlob(str, options) {
if (typeof str !== 'string' || str === '') {
return false;
}
if (isExtglob(str)) {
return true;
}
var regex = strictRegex;
var match;
// optionally relax regex
if (options && options.strict === false) {
regex = relaxedRegex;
}
while ((match = regex.exec(str))) {
if (match[2]) return true;
var idx = match.index + match[0].length;
// if an open bracket/brace/paren is escaped,
// set the index to the next closing character
var open = match[1];
var close = open ? chars[open] : null;
if (open && close) {
var n = str.indexOf(close, idx);
if (n !== -1) {
idx = n + 1;
}
}
str = str.slice(idx);
}
return false;
};
/***/ }),
/***/ 5680:
/***/ ((module) => {
"use strict";
/*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Released under the MIT License.
*/
module.exports = function(num) {
if (typeof num === 'number') {
return num - num === 0;
}
if (typeof num === 'string' && num.trim() !== '') {
return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
}
return false;
};
/***/ }),
/***/ 3287:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
exports.isPlainObject = isPlainObject;
/***/ }),
/***/ 2578:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/*
* merge2
* https://github.com/teambition/merge2
*
* Copyright (c) 2014-2020 Teambition
* Licensed under the MIT license.
*/
const Stream = __nccwpck_require__(2413)
const PassThrough = Stream.PassThrough
const slice = Array.prototype.slice
module.exports = merge2
function merge2 () {
const streamsQueue = []
const args = slice.call(arguments)
let merging = false
let options = args[args.length - 1]
if (options && !Array.isArray(options) && options.pipe == null) {
args.pop()
} else {
options = {}
}
const doEnd = options.end !== false
const doPipeError = options.pipeError === true
if (options.objectMode == null) {
options.objectMode = true
}
if (options.highWaterMark == null) {
options.highWaterMark = 64 * 1024
}
const mergedStream = PassThrough(options)
function addStream () {
for (let i = 0, len = arguments.length; i < len; i++) {
streamsQueue.push(pauseStreams(arguments[i], options))
}
mergeStream()
return this
}
function mergeStream () {
if (merging) {
return
}
merging = true
let streams = streamsQueue.shift()
if (!streams) {
process.nextTick(endStream)
return
}
if (!Array.isArray(streams)) {
streams = [streams]
}
let pipesCount = streams.length + 1
function next () {
if (--pipesCount > 0) {
return
}
merging = false
mergeStream()
}
function pipe (stream) {
function onend () {
stream.removeListener('merge2UnpipeEnd', onend)
stream.removeListener('end', onend)
if (doPipeError) {
stream.removeListener('error', onerror)
}
next()
}
function onerror (err) {
mergedStream.emit('error', err)
}
// skip ended stream
if (stream._readableState.endEmitted) {
return next()
}
stream.on('merge2UnpipeEnd', onend)
stream.on('end', onend)
if (doPipeError) {
stream.on('error', onerror)
}
stream.pipe(mergedStream, { end: false })
// compatible for old stream
stream.resume()
}
for (let i = 0; i < streams.length; i++) {
pipe(streams[i])
}
next()
}
function endStream () {
merging = false
// emit 'queueDrain' when all streams merged.
mergedStream.emit('queueDrain')
if (doEnd) {
mergedStream.end()
}
}
mergedStream.setMaxListeners(0)
mergedStream.add = addStream
mergedStream.on('unpipe', function (stream) {
stream.emit('merge2UnpipeEnd')
})
if (args.length) {
addStream.apply(null, args)
}
return mergedStream
}
// check and pause streams for pipe.
function pauseStreams (streams, options) {
if (!Array.isArray(streams)) {
// Backwards-compat with old-style streams
if (!streams._readableState && streams.pipe) {
streams = streams.pipe(PassThrough(options))
}
if (!streams._readableState || !streams.pause || !streams.pipe) {
throw new Error('Only readable stream can be merged.')
}
streams.pause()
} else {
for (let i = 0, len = streams.length; i < len; i++) {
streams[i] = pauseStreams(streams[i], options)
}
}
return streams
}
/***/ }),
/***/ 6228:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const util = __nccwpck_require__(1669);
const braces = __nccwpck_require__(610);
const picomatch = __nccwpck_require__(8569);
const utils = __nccwpck_require__(479);
const isEmptyString = val => val === '' || val === './';
/**
* Returns an array of strings that match one or more glob patterns.
*
* ```js
* const mm = require('micromatch');
* // mm(list, patterns[, options]);
*
* console.log(mm(['a.js', 'a.txt'], ['*.js']));
* //=> [ 'a.js' ]
* ```
* @param {String|Array<string>} `list` List of strings to match.
* @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options)
* @return {Array} Returns an array of matches
* @summary false
* @api public
*/
const micromatch = (list, patterns, options) => {
patterns = [].concat(patterns);
list = [].concat(list);
let omit = new Set();
let keep = new Set();
let items = new Set();
let negatives = 0;
let onResult = state => {
items.add(state.output);
if (options && options.onResult) {
options.onResult(state);
}
};
for (let i = 0; i < patterns.length; i++) {
let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
if (negated) negatives++;
for (let item of list) {
let matched = isMatch(item, true);
let match = negated ? !matched.isMatch : matched.isMatch;
if (!match) continue;
if (negated) {
omit.add(matched.output);
} else {
omit.delete(matched.output);
keep.add(matched.output);
}
}
}
let result = negatives === patterns.length ? [...items] : [...keep];
let matches = result.filter(item => !omit.has(item));
if (options && matches.length === 0) {
if (options.failglob === true) {
throw new Error(`No matches found for "${patterns.join(', ')}"`);
}
if (options.nonull === true || options.nullglob === true) {
return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
}
}
return matches;
};
/**
* Backwards compatibility
*/
micromatch.match = micromatch;
/**
* Returns a matcher function from the given glob `pattern` and `options`.
* The returned function takes a string to match as its only argument and returns
* true if the string is a match.
*
* ```js
* const mm = require('micromatch');
* // mm.matcher(pattern[, options]);
*
* const isMatch = mm.matcher('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @param {String} `pattern` Glob pattern
* @param {Object} `options`
* @return {Function} Returns a matcher function.
* @api public
*/
micromatch.matcher = (pattern, options) => picomatch(pattern, options);
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const mm = require('micromatch');
* // mm.isMatch(string, patterns[, options]);
*
* console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(mm.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String} `str` The string to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `[options]` See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
/**
* Backwards compatibility
*/
micromatch.any = micromatch.isMatch;
/**
* Returns a list of strings that _**do not match any**_ of the given `patterns`.
*
* ```js
* const mm = require('micromatch');
* // mm.not(list, patterns[, options]);
*
* console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
* //=> ['b.b', 'c.c']
* ```
* @param {Array} `list` Array of strings to match.
* @param {String|Array} `patterns` One or more glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Array} Returns an array of strings that **do not match** the given patterns.
* @api public
*/
micromatch.not = (list, patterns, options = {}) => {
patterns = [].concat(patterns).map(String);
let result = new Set();
let items = [];
let onResult = state => {
if (options.onResult) options.onResult(state);
items.push(state.output);
};
let matches = micromatch(list, patterns, { ...options, onResult });
for (let item of items) {
if (!matches.includes(item)) {
result.add(item);
}
}
return [...result];
};
/**
* Returns true if the given `string` contains the given pattern. Similar
* to [.isMatch](#isMatch) but the pattern can match any part of the string.
*
* ```js
* var mm = require('micromatch');
* // mm.contains(string, pattern[, options]);
*
* console.log(mm.contains('aa/bb/cc', '*b'));
* //=> true
* console.log(mm.contains('aa/bb/cc', '*d'));
* //=> false
* ```
* @param {String} `str` The string to match.
* @param {String|Array} `patterns` Glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any of the patterns matches any part of `str`.
* @api public
*/
micromatch.contains = (str, pattern, options) => {
if (typeof str !== 'string') {
throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
}
if (Array.isArray(pattern)) {
return pattern.some(p => micromatch.contains(str, p, options));
}
if (typeof pattern === 'string') {
if (isEmptyString(str) || isEmptyString(pattern)) {
return false;
}
if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
return true;
}
}
return micromatch.isMatch(str, pattern, { ...options, contains: true });
};
/**
* Filter the keys of the given object with the given `glob` pattern
* and `options`. Does not attempt to match nested keys. If you need this feature,
* use [glob-object][] instead.
*
* ```js
* const mm = require('micromatch');
* // mm.matchKeys(object, patterns[, options]);
*
* const obj = { aa: 'a', ab: 'b', ac: 'c' };
* console.log(mm.matchKeys(obj, '*b'));
* //=> { ab: 'b' }
* ```
* @param {Object} `object` The object with keys to filter.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Object} Returns an object with only keys that match the given patterns.
* @api public
*/
micromatch.matchKeys = (obj, patterns, options) => {
if (!utils.isObject(obj)) {
throw new TypeError('Expected the first argument to be an object');
}
let keys = micromatch(Object.keys(obj), patterns, options);
let res = {};
for (let key of keys) res[key] = obj[key];
return res;
};
/**
* Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
*
* ```js
* const mm = require('micromatch');
* // mm.some(list, patterns[, options]);
*
* console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
* // true
* console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
* // false
* ```
* @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
* @api public
*/
micromatch.some = (list, patterns, options) => {
let items = [].concat(list);
for (let pattern of [].concat(patterns)) {
let isMatch = picomatch(String(pattern), options);
if (items.some(item => isMatch(item))) {
return true;
}
}
return false;
};
/**
* Returns true if every string in the given `list` matches
* any of the given glob `patterns`.
*
* ```js
* const mm = require('micromatch');
* // mm.every(list, patterns[, options]);
*
* console.log(mm.every('foo.js', ['foo.js']));
* // true
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
* // true
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
* // false
* console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
* // false
* ```
* @param {String|Array} `list` The string or array of strings to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
* @api public
*/
micromatch.every = (list, patterns, options) => {
let items = [].concat(list);
for (let pattern of [].concat(patterns)) {
let isMatch = picomatch(String(pattern), options);
if (!items.every(item => isMatch(item))) {
return false;
}
}
return true;
};
/**
* Returns true if **all** of the given `patterns` match
* the specified string.
*
* ```js
* const mm = require('micromatch');
* // mm.all(string, patterns[, options]);
*
* console.log(mm.all('foo.js', ['foo.js']));
* // true
*
* console.log(mm.all('foo.js', ['*.js', '!foo.js']));
* // false
*
* console.log(mm.all('foo.js', ['*.js', 'foo.js']));
* // true
*
* console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
* // true
* ```
* @param {String|Array} `str` The string to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.all = (str, patterns, options) => {
if (typeof str !== 'string') {
throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
}
return [].concat(patterns).every(p => picomatch(p, options)(str));
};
/**
* Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
*
* ```js
* const mm = require('micromatch');
* // mm.capture(pattern, string[, options]);
*
* console.log(mm.capture('test/*.js', 'test/foo.js'));
* //=> ['foo']
* console.log(mm.capture('test/*.js', 'foo/bar.css'));
* //=> null
* ```
* @param {String} `glob` Glob pattern to use for matching.
* @param {String} `input` String to match
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
* @api public
*/
micromatch.capture = (glob, input, options) => {
let posix = utils.isWindows(options);
let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
if (match) {
return match.slice(1).map(v => v === void 0 ? '' : v);
}
};
/**
* Create a regular expression from the given glob `pattern`.
*
* ```js
* const mm = require('micromatch');
* // mm.makeRe(pattern[, options]);
*
* console.log(mm.makeRe('*.js'));
* //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
* ```
* @param {String} `pattern` A glob pattern to convert to regex.
* @param {Object} `options`
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
micromatch.makeRe = (...args) => picomatch.makeRe(...args);
/**
* Scan a glob pattern to separate the pattern into segments. Used
* by the [split](#split) method.
*
* ```js
* const mm = require('micromatch');
* const state = mm.scan(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
micromatch.scan = (...args) => picomatch.scan(...args);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const mm = require('micromatch');
* const state = mm(pattern[, options]);
* ```
* @param {String} `glob`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as regex source string.
* @api public
*/
micromatch.parse = (patterns, options) => {
let res = [];
for (let pattern of [].concat(patterns || [])) {
for (let str of braces(String(pattern), options)) {
res.push(picomatch.parse(str, options));
}
}
return res;
};
/**
* Process the given brace `pattern`.
*
* ```js
* const { braces } = require('micromatch');
* console.log(braces('foo/{a,b,c}/bar'));
* //=> [ 'foo/(a|b|c)/bar' ]
*
* console.log(braces('foo/{a,b,c}/bar', { expand: true }));
* //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
* ```
* @param {String} `pattern` String with brace pattern to process.
* @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
* @return {Array}
* @api public
*/
micromatch.braces = (pattern, options) => {
if (typeof pattern !== 'string') throw new TypeError('Expected a string');
if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
return [pattern];
}
return braces(pattern, options);
};
/**
* Expand braces
*/
micromatch.braceExpand = (pattern, options) => {
if (typeof pattern !== 'string') throw new TypeError('Expected a string');
return micromatch.braces(pattern, { ...options, expand: true });
};
/**
* Expose micromatch
*/
module.exports = micromatch;
/***/ }),
/***/ 7760:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
if (!globalThis.DOMException) {
try {
const { MessageChannel } = __nccwpck_require__(5013),
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
/***/ }),
2021-12-11 08:00:14 -05:00
/***/ 8119:
2021-09-26 15:31:45 -04:00
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-12-11 08:00:14 -05:00
/**
* @license node-stream-zip | (c) 2020 Antelle | https://github.com/antelle/node-stream-zip/blob/master/LICENSE
* Portions copyright https://github.com/cthackers/adm-zip | https://raw.githubusercontent.com/cthackers/adm-zip/master/LICENSE
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let fs = __nccwpck_require__(5747);
const util = __nccwpck_require__(1669);
const path = __nccwpck_require__(5622);
const events = __nccwpck_require__(8614);
const zlib = __nccwpck_require__(8761);
const stream = __nccwpck_require__(2413);
const consts = {
/* The local file header */
LOCHDR: 30, // LOC header size
LOCSIG: 0x04034b50, // "PK\003\004"
LOCVER: 4, // version needed to extract
LOCFLG: 6, // general purpose bit flag
LOCHOW: 8, // compression method
LOCTIM: 10, // modification time (2 bytes time, 2 bytes date)
LOCCRC: 14, // uncompressed file crc-32 value
LOCSIZ: 18, // compressed size
LOCLEN: 22, // uncompressed size
LOCNAM: 26, // filename length
LOCEXT: 28, // extra field length
/* The Data descriptor */
EXTSIG: 0x08074b50, // "PK\007\008"
EXTHDR: 16, // EXT header size
EXTCRC: 4, // uncompressed file crc-32 value
EXTSIZ: 8, // compressed size
EXTLEN: 12, // uncompressed size
/* The central directory file header */
CENHDR: 46, // CEN header size
CENSIG: 0x02014b50, // "PK\001\002"
CENVEM: 4, // version made by
CENVER: 6, // version needed to extract
CENFLG: 8, // encrypt, decrypt flags
CENHOW: 10, // compression method
CENTIM: 12, // modification time (2 bytes time, 2 bytes date)
CENCRC: 16, // uncompressed file crc-32 value
CENSIZ: 20, // compressed size
CENLEN: 24, // uncompressed size
CENNAM: 28, // filename length
CENEXT: 30, // extra field length
CENCOM: 32, // file comment length
CENDSK: 34, // volume number start
CENATT: 36, // internal file attributes
CENATX: 38, // external file attributes (host system dependent)
CENOFF: 42, // LOC header offset
/* The entries in the end of central directory */
ENDHDR: 22, // END header size
ENDSIG: 0x06054b50, // "PK\005\006"
ENDSIGFIRST: 0x50,
ENDSUB: 8, // number of entries on this disk
ENDTOT: 10, // total number of entries
ENDSIZ: 12, // central directory size in bytes
ENDOFF: 16, // offset of first CEN header
ENDCOM: 20, // zip file comment length
MAXFILECOMMENT: 0xffff,
/* The entries in the end of ZIP64 central directory locator */
ENDL64HDR: 20, // ZIP64 end of central directory locator header size
ENDL64SIG: 0x07064b50, // ZIP64 end of central directory locator signature
ENDL64SIGFIRST: 0x50,
ENDL64OFS: 8, // ZIP64 end of central directory offset
/* The entries in the end of ZIP64 central directory */
END64HDR: 56, // ZIP64 end of central directory header size
END64SIG: 0x06064b50, // ZIP64 end of central directory signature
END64SIGFIRST: 0x50,
END64SUB: 24, // number of entries on this disk
END64TOT: 32, // total number of entries
END64SIZ: 40,
END64OFF: 48,
/* Compression methods */
STORED: 0, // no compression
SHRUNK: 1, // shrunk
REDUCED1: 2, // reduced with compression factor 1
REDUCED2: 3, // reduced with compression factor 2
REDUCED3: 4, // reduced with compression factor 3
REDUCED4: 5, // reduced with compression factor 4
IMPLODED: 6, // imploded
// 7 reserved
DEFLATED: 8, // deflated
ENHANCED_DEFLATED: 9, // deflate64
PKWARE: 10, // PKWare DCL imploded
// 11 reserved
BZIP2: 12, // compressed using BZIP2
// 13 reserved
LZMA: 14, // LZMA
// 15-17 reserved
IBM_TERSE: 18, // compressed using IBM TERSE
IBM_LZ77: 19, //IBM LZ77 z
/* General purpose bit flag */
FLG_ENC: 0, // encrypted file
FLG_COMP1: 1, // compression option
FLG_COMP2: 2, // compression option
FLG_DESC: 4, // data descriptor
FLG_ENH: 8, // enhanced deflation
FLG_STR: 16, // strong encryption
FLG_LNG: 1024, // language encoding
FLG_MSK: 4096, // mask header values
FLG_ENTRY_ENC: 1,
/* 4.5 Extensible data fields */
EF_ID: 0,
EF_SIZE: 2,
/* Header IDs */
ID_ZIP64: 0x0001,
ID_AVINFO: 0x0007,
ID_PFS: 0x0008,
ID_OS2: 0x0009,
ID_NTFS: 0x000a,
ID_OPENVMS: 0x000c,
ID_UNIX: 0x000d,
ID_FORK: 0x000e,
ID_PATCH: 0x000f,
ID_X509_PKCS7: 0x0014,
ID_X509_CERTID_F: 0x0015,
ID_X509_CERTID_C: 0x0016,
ID_STRONGENC: 0x0017,
ID_RECORD_MGT: 0x0018,
ID_X509_PKCS7_RL: 0x0019,
ID_IBM1: 0x0065,
ID_IBM2: 0x0066,
ID_POSZIP: 0x4690,
EF_ZIP64_OR_32: 0xffffffff,
EF_ZIP64_OR_16: 0xffff,
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const StreamZip = function (config) {
let fd, fileSize, chunkSize, op, centralDirectory, closed;
const ready = false,
that = this,
entries = config.storeEntries !== false ? {} : null,
fileName = config.file,
textDecoder = config.nameEncoding ? new TextDecoder(config.nameEncoding) : null;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
open();
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function open() {
if (config.fd) {
fd = config.fd;
readFile();
} else {
fs.open(fileName, 'r', (err, f) => {
if (err) {
return that.emit('error', err);
}
fd = f;
readFile();
});
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readFile() {
fs.fstat(fd, (err, stat) => {
if (err) {
return that.emit('error', err);
}
fileSize = stat.size;
chunkSize = config.chunkSize || Math.round(fileSize / 1000);
chunkSize = Math.max(
Math.min(chunkSize, Math.min(128 * 1024, fileSize)),
Math.min(1024, fileSize)
);
readCentralDirectory();
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readUntilFoundCallback(err, bytesRead) {
if (err || !bytesRead) {
return that.emit('error', err || new Error('Archive read error'));
}
let pos = op.lastPos;
let bufferPosition = pos - op.win.position;
const buffer = op.win.buffer;
const minPos = op.minPos;
while (--pos >= minPos && --bufferPosition >= 0) {
if (buffer.length - bufferPosition >= 4 && buffer[bufferPosition] === op.firstByte) {
// quick check first signature byte
if (buffer.readUInt32LE(bufferPosition) === op.sig) {
op.lastBufferPosition = bufferPosition;
op.lastBytesRead = bytesRead;
op.complete();
return;
}
}
}
if (pos === minPos) {
return that.emit('error', new Error('Bad archive'));
}
op.lastPos = pos + 1;
op.chunkSize *= 2;
if (pos <= minPos) {
return that.emit('error', new Error('Bad archive'));
}
const expandLength = Math.min(op.chunkSize, pos - minPos);
op.win.expandLeft(expandLength, readUntilFoundCallback);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readCentralDirectory() {
const totalReadLength = Math.min(consts.ENDHDR + consts.MAXFILECOMMENT, fileSize);
op = {
win: new FileWindowBuffer(fd),
totalReadLength,
minPos: fileSize - totalReadLength,
lastPos: fileSize,
chunkSize: Math.min(1024, chunkSize),
firstByte: consts.ENDSIGFIRST,
sig: consts.ENDSIG,
complete: readCentralDirectoryComplete,
};
op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readCentralDirectoryComplete() {
const buffer = op.win.buffer;
const pos = op.lastBufferPosition;
try {
centralDirectory = new CentralDirectoryHeader();
centralDirectory.read(buffer.slice(pos, pos + consts.ENDHDR));
centralDirectory.headerOffset = op.win.position + pos;
if (centralDirectory.commentLength) {
that.comment = buffer
.slice(
pos + consts.ENDHDR,
pos + consts.ENDHDR + centralDirectory.commentLength
)
.toString();
} else {
that.comment = null;
}
that.entriesCount = centralDirectory.volumeEntries;
that.centralDirectory = centralDirectory;
if (
(centralDirectory.volumeEntries === consts.EF_ZIP64_OR_16 &&
centralDirectory.totalEntries === consts.EF_ZIP64_OR_16) ||
centralDirectory.size === consts.EF_ZIP64_OR_32 ||
centralDirectory.offset === consts.EF_ZIP64_OR_32
) {
readZip64CentralDirectoryLocator();
} else {
op = {};
readEntries();
}
} catch (err) {
that.emit('error', err);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readZip64CentralDirectoryLocator() {
const length = consts.ENDL64HDR;
if (op.lastBufferPosition > length) {
op.lastBufferPosition -= length;
readZip64CentralDirectoryLocatorComplete();
} else {
op = {
win: op.win,
totalReadLength: length,
minPos: op.win.position - length,
lastPos: op.win.position,
chunkSize: op.chunkSize,
firstByte: consts.ENDL64SIGFIRST,
sig: consts.ENDL64SIG,
complete: readZip64CentralDirectoryLocatorComplete,
};
op.win.read(op.lastPos - op.chunkSize, op.chunkSize, readUntilFoundCallback);
}
}
function readZip64CentralDirectoryLocatorComplete() {
const buffer = op.win.buffer;
const locHeader = new CentralDirectoryLoc64Header();
locHeader.read(
buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.ENDL64HDR)
);
const readLength = fileSize - locHeader.headerOffset;
op = {
win: op.win,
totalReadLength: readLength,
minPos: locHeader.headerOffset,
lastPos: op.lastPos,
chunkSize: op.chunkSize,
firstByte: consts.END64SIGFIRST,
sig: consts.END64SIG,
complete: readZip64CentralDirectoryComplete,
};
op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
}
function readZip64CentralDirectoryComplete() {
const buffer = op.win.buffer;
const zip64cd = new CentralDirectoryZip64Header();
zip64cd.read(buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.END64HDR));
that.centralDirectory.volumeEntries = zip64cd.volumeEntries;
that.centralDirectory.totalEntries = zip64cd.totalEntries;
that.centralDirectory.size = zip64cd.size;
that.centralDirectory.offset = zip64cd.offset;
that.entriesCount = zip64cd.volumeEntries;
op = {};
readEntries();
}
function readEntries() {
op = {
win: new FileWindowBuffer(fd),
pos: centralDirectory.offset,
chunkSize,
entriesLeft: centralDirectory.volumeEntries,
};
op.win.read(op.pos, Math.min(chunkSize, fileSize - op.pos), readEntriesCallback);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readEntriesCallback(err, bytesRead) {
if (err || !bytesRead) {
return that.emit('error', err || new Error('Entries read error'));
}
let bufferPos = op.pos - op.win.position;
let entry = op.entry;
const buffer = op.win.buffer;
const bufferLength = buffer.length;
try {
while (op.entriesLeft > 0) {
if (!entry) {
entry = new ZipEntry();
entry.readHeader(buffer, bufferPos);
entry.headerOffset = op.win.position + bufferPos;
op.entry = entry;
op.pos += consts.CENHDR;
bufferPos += consts.CENHDR;
}
const entryHeaderSize = entry.fnameLen + entry.extraLen + entry.comLen;
const advanceBytes = entryHeaderSize + (op.entriesLeft > 1 ? consts.CENHDR : 0);
if (bufferLength - bufferPos < advanceBytes) {
op.win.moveRight(chunkSize, readEntriesCallback, bufferPos);
op.move = true;
return;
}
entry.read(buffer, bufferPos, textDecoder);
if (!config.skipEntryNameValidation) {
entry.validateName();
}
if (entries) {
entries[entry.name] = entry;
}
that.emit('entry', entry);
op.entry = entry = null;
op.entriesLeft--;
op.pos += entryHeaderSize;
bufferPos += entryHeaderSize;
}
that.emit('ready');
} catch (err) {
that.emit('error', err);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function checkEntriesExist() {
if (!entries) {
throw new Error('storeEntries disabled');
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
Object.defineProperty(this, 'ready', {
get() {
return ready;
},
});
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.entry = function (name) {
checkEntriesExist();
return entries[name];
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.entries = function () {
checkEntriesExist();
return entries;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.stream = function (entry, callback) {
return this.openEntry(
entry,
(err, entry) => {
if (err) {
return callback(err);
}
const offset = dataOffset(entry);
let entryStream = new EntryDataReaderStream(fd, offset, entry.compressedSize);
if (entry.method === consts.STORED) {
// nothing to do
} else if (entry.method === consts.DEFLATED) {
entryStream = entryStream.pipe(zlib.createInflateRaw());
} else {
return callback(new Error('Unknown compression method: ' + entry.method));
}
if (canVerifyCrc(entry)) {
entryStream = entryStream.pipe(
new EntryVerifyStream(entryStream, entry.crc, entry.size)
);
}
callback(null, entryStream);
},
false
);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.entryDataSync = function (entry) {
let err = null;
this.openEntry(
entry,
(e, en) => {
err = e;
entry = en;
},
true
);
if (err) {
throw err;
}
let data = Buffer.alloc(entry.compressedSize);
new FsRead(fd, data, 0, entry.compressedSize, dataOffset(entry), (e) => {
err = e;
}).read(true);
if (err) {
throw err;
}
if (entry.method === consts.STORED) {
// nothing to do
} else if (entry.method === consts.DEFLATED || entry.method === consts.ENHANCED_DEFLATED) {
data = zlib.inflateRawSync(data);
} else {
throw new Error('Unknown compression method: ' + entry.method);
}
if (data.length !== entry.size) {
throw new Error('Invalid size');
}
if (canVerifyCrc(entry)) {
const verify = new CrcVerify(entry.crc, entry.size);
verify.data(data);
}
return data;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.openEntry = function (entry, callback, sync) {
if (typeof entry === 'string') {
checkEntriesExist();
entry = entries[entry];
if (!entry) {
return callback(new Error('Entry not found'));
}
}
if (!entry.isFile) {
return callback(new Error('Entry is not file'));
}
if (!fd) {
return callback(new Error('Archive closed'));
}
const buffer = Buffer.alloc(consts.LOCHDR);
new FsRead(fd, buffer, 0, buffer.length, entry.offset, (err) => {
if (err) {
return callback(err);
}
let readEx;
try {
entry.readDataHeader(buffer);
if (entry.encrypted) {
readEx = new Error('Entry encrypted');
}
} catch (ex) {
readEx = ex;
}
callback(readEx, entry);
}).read(sync);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function dataOffset(entry) {
return entry.offset + consts.LOCHDR + entry.fnameLen + entry.extraLen;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function canVerifyCrc(entry) {
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written
return (entry.flags & 0x8) !== 0x8;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function extract(entry, outPath, callback) {
that.stream(entry, (err, stm) => {
if (err) {
callback(err);
} else {
let fsStm, errThrown;
stm.on('error', (err) => {
errThrown = err;
if (fsStm) {
stm.unpipe(fsStm);
fsStm.close(() => {
callback(err);
});
}
});
fs.open(outPath, 'w', (err, fdFile) => {
if (err) {
return callback(err);
}
if (errThrown) {
fs.close(fd, () => {
callback(errThrown);
});
return;
}
fsStm = fs.createWriteStream(outPath, { fd: fdFile });
fsStm.on('finish', () => {
that.emit('extract', entry, outPath);
if (!errThrown) {
callback();
}
});
stm.pipe(fsStm);
});
}
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function createDirectories(baseDir, dirs, callback) {
if (!dirs.length) {
return callback();
}
let dir = dirs.shift();
dir = path.join(baseDir, path.join(...dir));
fs.mkdir(dir, { recursive: true }, (err) => {
if (err && err.code !== 'EEXIST') {
return callback(err);
}
createDirectories(baseDir, dirs, callback);
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function extractFiles(baseDir, baseRelPath, files, callback, extractedCount) {
if (!files.length) {
return callback(null, extractedCount);
}
const file = files.shift();
const targetPath = path.join(baseDir, file.name.replace(baseRelPath, ''));
extract(file, targetPath, (err) => {
if (err) {
return callback(err, extractedCount);
}
extractFiles(baseDir, baseRelPath, files, callback, extractedCount + 1);
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.extract = function (entry, outPath, callback) {
let entryName = entry || '';
if (typeof entry === 'string') {
entry = this.entry(entry);
if (entry) {
entryName = entry.name;
} else {
if (entryName.length && entryName[entryName.length - 1] !== '/') {
entryName += '/';
}
}
}
if (!entry || entry.isDirectory) {
const files = [],
dirs = [],
allDirs = {};
for (const e in entries) {
if (
Object.prototype.hasOwnProperty.call(entries, e) &&
e.lastIndexOf(entryName, 0) === 0
) {
let relPath = e.replace(entryName, '');
const childEntry = entries[e];
if (childEntry.isFile) {
files.push(childEntry);
relPath = path.dirname(relPath);
}
if (relPath && !allDirs[relPath] && relPath !== '.') {
allDirs[relPath] = true;
let parts = relPath.split('/').filter((f) => {
return f;
});
if (parts.length) {
dirs.push(parts);
}
while (parts.length > 1) {
parts = parts.slice(0, parts.length - 1);
const partsPath = parts.join('/');
if (allDirs[partsPath] || partsPath === '.') {
break;
}
allDirs[partsPath] = true;
dirs.push(parts);
}
}
}
}
dirs.sort((x, y) => {
return x.length - y.length;
});
if (dirs.length) {
createDirectories(outPath, dirs, (err) => {
if (err) {
callback(err);
} else {
extractFiles(outPath, entryName, files, callback, 0);
}
});
} else {
extractFiles(outPath, entryName, files, callback, 0);
}
} else {
fs.stat(outPath, (err, stat) => {
if (stat && stat.isDirectory()) {
extract(entry, path.join(outPath, path.basename(entry.name)), callback);
} else {
extract(entry, outPath, callback);
}
});
}
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this.close = function (callback) {
if (closed || !fd) {
closed = true;
if (callback) {
callback();
}
} else {
closed = true;
fs.close(fd, (err) => {
fd = null;
if (callback) {
callback(err);
}
});
}
};
const originalEmit = events.EventEmitter.prototype.emit;
this.emit = function (...args) {
if (!closed) {
return originalEmit.call(this, ...args);
}
};
2021-09-26 15:31:45 -04:00
};
2021-12-11 08:00:14 -05:00
StreamZip.setFs = function (customFs) {
fs = customFs;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
StreamZip.debugLog = (...args) => {
if (StreamZip.debug) {
// eslint-disable-next-line no-console
console.log(...args);
}
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
util.inherits(StreamZip, events.EventEmitter);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const propZip = Symbol('zip');
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
StreamZip.async = class StreamZipAsync extends events.EventEmitter {
constructor(config) {
super();
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const zip = new StreamZip(config);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
zip.on('entry', (entry) => this.emit('entry', entry));
zip.on('extract', (entry, outPath) => this.emit('extract', entry, outPath));
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
this[propZip] = new Promise((resolve, reject) => {
zip.on('ready', () => {
zip.removeListener('error', reject);
resolve(zip);
});
zip.on('error', reject);
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
get entriesCount() {
return this[propZip].then((zip) => zip.entriesCount);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
get comment() {
return this[propZip].then((zip) => zip.comment);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async entry(name) {
const zip = await this[propZip];
return zip.entry(name);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async entries() {
const zip = await this[propZip];
return zip.entries();
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async stream(entry) {
const zip = await this[propZip];
return new Promise((resolve, reject) => {
zip.stream(entry, (err, stm) => {
if (err) {
reject(err);
} else {
resolve(stm);
}
});
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async entryData(entry) {
const stm = await this.stream(entry);
return new Promise((resolve, reject) => {
const data = [];
stm.on('data', (chunk) => data.push(chunk));
stm.on('end', () => {
resolve(Buffer.concat(data));
});
stm.on('error', (err) => {
stm.removeAllListeners('end');
reject(err);
});
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async extract(entry, outPath) {
const zip = await this[propZip];
return new Promise((resolve, reject) => {
zip.extract(entry, outPath, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
async close() {
const zip = await this[propZip];
return new Promise((resolve, reject) => {
zip.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
class CentralDirectoryHeader {
read(data) {
if (data.length !== consts.ENDHDR || data.readUInt32LE(0) !== consts.ENDSIG) {
throw new Error('Invalid central directory');
}
// number of entries on this volume
this.volumeEntries = data.readUInt16LE(consts.ENDSUB);
// total number of entries
this.totalEntries = data.readUInt16LE(consts.ENDTOT);
// central directory size in bytes
this.size = data.readUInt32LE(consts.ENDSIZ);
// offset of first CEN header
this.offset = data.readUInt32LE(consts.ENDOFF);
// zip file comment length
this.commentLength = data.readUInt16LE(consts.ENDCOM);
}
}
class CentralDirectoryLoc64Header {
read(data) {
if (data.length !== consts.ENDL64HDR || data.readUInt32LE(0) !== consts.ENDL64SIG) {
throw new Error('Invalid zip64 central directory locator');
}
// ZIP64 EOCD header offset
this.headerOffset = readUInt64LE(data, consts.ENDSUB);
}
}
class CentralDirectoryZip64Header {
read(data) {
if (data.length !== consts.END64HDR || data.readUInt32LE(0) !== consts.END64SIG) {
throw new Error('Invalid central directory');
}
// number of entries on this volume
this.volumeEntries = readUInt64LE(data, consts.END64SUB);
// total number of entries
this.totalEntries = readUInt64LE(data, consts.END64TOT);
// central directory size in bytes
this.size = readUInt64LE(data, consts.END64SIZ);
// offset of first CEN header
this.offset = readUInt64LE(data, consts.END64OFF);
}
}
class ZipEntry {
readHeader(data, offset) {
// data should be 46 bytes and start with "PK 01 02"
if (data.length < offset + consts.CENHDR || data.readUInt32LE(offset) !== consts.CENSIG) {
throw new Error('Invalid entry header');
}
// version made by
this.verMade = data.readUInt16LE(offset + consts.CENVEM);
// version needed to extract
this.version = data.readUInt16LE(offset + consts.CENVER);
// encrypt, decrypt flags
this.flags = data.readUInt16LE(offset + consts.CENFLG);
// compression method
this.method = data.readUInt16LE(offset + consts.CENHOW);
// modification time (2 bytes time, 2 bytes date)
const timebytes = data.readUInt16LE(offset + consts.CENTIM);
const datebytes = data.readUInt16LE(offset + consts.CENTIM + 2);
this.time = parseZipTime(timebytes, datebytes);
// uncompressed file crc-32 value
this.crc = data.readUInt32LE(offset + consts.CENCRC);
// compressed size
this.compressedSize = data.readUInt32LE(offset + consts.CENSIZ);
// uncompressed size
this.size = data.readUInt32LE(offset + consts.CENLEN);
// filename length
this.fnameLen = data.readUInt16LE(offset + consts.CENNAM);
// extra field length
this.extraLen = data.readUInt16LE(offset + consts.CENEXT);
// file comment length
this.comLen = data.readUInt16LE(offset + consts.CENCOM);
// volume number start
this.diskStart = data.readUInt16LE(offset + consts.CENDSK);
// internal file attributes
this.inattr = data.readUInt16LE(offset + consts.CENATT);
// external file attributes
this.attr = data.readUInt32LE(offset + consts.CENATX);
// LOC header offset
this.offset = data.readUInt32LE(offset + consts.CENOFF);
}
readDataHeader(data) {
// 30 bytes and should start with "PK\003\004"
if (data.readUInt32LE(0) !== consts.LOCSIG) {
throw new Error('Invalid local header');
}
// version needed to extract
this.version = data.readUInt16LE(consts.LOCVER);
// general purpose bit flag
this.flags = data.readUInt16LE(consts.LOCFLG);
// compression method
this.method = data.readUInt16LE(consts.LOCHOW);
// modification time (2 bytes time ; 2 bytes date)
const timebytes = data.readUInt16LE(consts.LOCTIM);
const datebytes = data.readUInt16LE(consts.LOCTIM + 2);
this.time = parseZipTime(timebytes, datebytes);
// uncompressed file crc-32 value
this.crc = data.readUInt32LE(consts.LOCCRC) || this.crc;
// compressed size
const compressedSize = data.readUInt32LE(consts.LOCSIZ);
if (compressedSize && compressedSize !== consts.EF_ZIP64_OR_32) {
this.compressedSize = compressedSize;
}
// uncompressed size
const size = data.readUInt32LE(consts.LOCLEN);
if (size && size !== consts.EF_ZIP64_OR_32) {
this.size = size;
}
// filename length
this.fnameLen = data.readUInt16LE(consts.LOCNAM);
// extra field length
this.extraLen = data.readUInt16LE(consts.LOCEXT);
}
read(data, offset, textDecoder) {
const nameData = data.slice(offset, (offset += this.fnameLen));
this.name = textDecoder
? textDecoder.decode(new Uint8Array(nameData))
: nameData.toString('utf8');
const lastChar = data[offset - 1];
this.isDirectory = lastChar === 47 || lastChar === 92;
if (this.extraLen) {
this.readExtra(data, offset);
offset += this.extraLen;
}
this.comment = this.comLen ? data.slice(offset, offset + this.comLen).toString() : null;
}
validateName() {
if (/\\|^\w+:|^\/|(^|\/)\.\.(\/|$)/.test(this.name)) {
throw new Error('Malicious entry: ' + this.name);
}
}
readExtra(data, offset) {
let signature, size;
const maxPos = offset + this.extraLen;
while (offset < maxPos) {
signature = data.readUInt16LE(offset);
offset += 2;
size = data.readUInt16LE(offset);
offset += 2;
if (consts.ID_ZIP64 === signature) {
this.parseZip64Extra(data, offset, size);
}
offset += size;
}
}
parseZip64Extra(data, offset, length) {
if (length >= 8 && this.size === consts.EF_ZIP64_OR_32) {
this.size = readUInt64LE(data, offset);
offset += 8;
length -= 8;
}
if (length >= 8 && this.compressedSize === consts.EF_ZIP64_OR_32) {
this.compressedSize = readUInt64LE(data, offset);
offset += 8;
length -= 8;
}
if (length >= 8 && this.offset === consts.EF_ZIP64_OR_32) {
this.offset = readUInt64LE(data, offset);
offset += 8;
length -= 8;
}
if (length >= 4 && this.diskStart === consts.EF_ZIP64_OR_16) {
this.diskStart = data.readUInt32LE(offset);
// offset += 4; length -= 4;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
get encrypted() {
return (this.flags & consts.FLG_ENTRY_ENC) === consts.FLG_ENTRY_ENC;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
get isFile() {
return !this.isDirectory;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
class FsRead {
constructor(fd, buffer, offset, length, position, callback) {
this.fd = fd;
this.buffer = buffer;
this.offset = offset;
this.length = length;
this.position = position;
this.callback = callback;
this.bytesRead = 0;
this.waiting = false;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
read(sync) {
StreamZip.debugLog('read', this.position, this.bytesRead, this.length, this.offset);
this.waiting = true;
let err;
if (sync) {
let bytesRead = 0;
try {
bytesRead = fs.readSync(
this.fd,
this.buffer,
this.offset + this.bytesRead,
this.length - this.bytesRead,
this.position + this.bytesRead
);
} catch (e) {
err = e;
}
this.readCallback(sync, err, err ? bytesRead : null);
} else {
fs.read(
this.fd,
this.buffer,
this.offset + this.bytesRead,
this.length - this.bytesRead,
this.position + this.bytesRead,
this.readCallback.bind(this, sync)
);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
readCallback(sync, err, bytesRead) {
if (typeof bytesRead === 'number') {
this.bytesRead += bytesRead;
}
if (err || !bytesRead || this.bytesRead === this.length) {
this.waiting = false;
return this.callback(err, this.bytesRead);
} else {
this.read(sync);
}
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
class FileWindowBuffer {
constructor(fd) {
this.position = 0;
this.buffer = Buffer.alloc(0);
this.fd = fd;
this.fsOp = null;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
checkOp() {
if (this.fsOp && this.fsOp.waiting) {
throw new Error('Operation in progress');
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
read(pos, length, callback) {
this.checkOp();
if (this.buffer.length < length) {
this.buffer = Buffer.alloc(length);
}
this.position = pos;
this.fsOp = new FsRead(this.fd, this.buffer, 0, length, this.position, callback).read();
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
expandLeft(length, callback) {
this.checkOp();
this.buffer = Buffer.concat([Buffer.alloc(length), this.buffer]);
this.position -= length;
if (this.position < 0) {
this.position = 0;
}
this.fsOp = new FsRead(this.fd, this.buffer, 0, length, this.position, callback).read();
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
expandRight(length, callback) {
this.checkOp();
const offset = this.buffer.length;
this.buffer = Buffer.concat([this.buffer, Buffer.alloc(length)]);
this.fsOp = new FsRead(
this.fd,
this.buffer,
offset,
length,
this.position + offset,
callback
).read();
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
moveRight(length, callback, shift) {
this.checkOp();
if (shift) {
this.buffer.copy(this.buffer, 0, shift);
} else {
shift = 0;
}
this.position += shift;
this.fsOp = new FsRead(
this.fd,
this.buffer,
this.buffer.length - shift,
shift,
this.position + this.buffer.length - shift,
callback
).read();
}
}
class EntryDataReaderStream extends stream.Readable {
constructor(fd, offset, length) {
super();
this.fd = fd;
this.offset = offset;
this.length = length;
this.pos = 0;
this.readCallback = this.readCallback.bind(this);
}
_read(n) {
const buffer = Buffer.alloc(Math.min(n, this.length - this.pos));
if (buffer.length) {
fs.read(this.fd, buffer, 0, buffer.length, this.offset + this.pos, this.readCallback);
} else {
this.push(null);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
readCallback(err, bytesRead, buffer) {
this.pos += bytesRead;
if (err) {
this.emit('error', err);
this.push(null);
} else if (!bytesRead) {
this.push(null);
} else {
if (bytesRead !== buffer.length) {
buffer = buffer.slice(0, bytesRead);
}
this.push(buffer);
}
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
class EntryVerifyStream extends stream.Transform {
constructor(baseStm, crc, size) {
super();
this.verify = new CrcVerify(crc, size);
baseStm.on('error', (e) => {
this.emit('error', e);
});
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
_transform(data, encoding, callback) {
let err;
try {
this.verify.data(data);
} catch (e) {
err = e;
}
callback(err, data);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
class CrcVerify {
constructor(crc, size) {
this.crc = crc;
this.size = size;
this.state = {
crc: ~0,
size: 0,
};
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
data(data) {
const crcTable = CrcVerify.getCrcTable();
let crc = this.state.crc;
let off = 0;
let len = data.length;
while (--len >= 0) {
crc = crcTable[(crc ^ data[off++]) & 0xff] ^ (crc >>> 8);
}
this.state.crc = crc;
this.state.size += data.length;
if (this.state.size >= this.size) {
const buf = Buffer.alloc(4);
buf.writeInt32LE(~this.state.crc & 0xffffffff, 0);
crc = buf.readUInt32LE(0);
if (crc !== this.crc) {
throw new Error('Invalid CRC');
}
if (this.state.size !== this.size) {
throw new Error('Invalid size');
}
}
}
static getCrcTable() {
let crcTable = CrcVerify.crcTable;
if (!crcTable) {
CrcVerify.crcTable = crcTable = [];
const b = Buffer.alloc(4);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 8; --k >= 0; ) {
if ((c & 1) !== 0) {
c = 0xedb88320 ^ (c >>> 1);
} else {
c = c >>> 1;
}
}
if (c < 0) {
b.writeInt32LE(c, 0);
c = b.readUInt32LE(0);
}
crcTable[n] = c;
}
}
return crcTable;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function parseZipTime(timebytes, datebytes) {
const timebits = toBits(timebytes, 16);
const datebits = toBits(datebytes, 16);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const mt = {
h: parseInt(timebits.slice(0, 5).join(''), 2),
m: parseInt(timebits.slice(5, 11).join(''), 2),
s: parseInt(timebits.slice(11, 16).join(''), 2) * 2,
Y: parseInt(datebits.slice(0, 7).join(''), 2) + 1980,
M: parseInt(datebits.slice(7, 11).join(''), 2),
D: parseInt(datebits.slice(11, 16).join(''), 2),
};
const dt_str = [mt.Y, mt.M, mt.D].join('-') + ' ' + [mt.h, mt.m, mt.s].join(':') + ' GMT+0';
return new Date(dt_str).getTime();
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function toBits(dec, size) {
let b = (dec >>> 0).toString(2);
while (b.length < size) {
b = '0' + b;
}
return b.split('');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function readUInt64LE(buffer, offset) {
return buffer.readUInt32LE(offset + 4) * 0x0000000100000000 + buffer.readUInt32LE(offset);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = StreamZip;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 1223:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
var wrappy = __nccwpck_require__(2940)
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
Object.defineProperty(Function.prototype, 'onceStrict', {
value: function () {
return onceStrict(this)
},
configurable: true
})
})
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function onceStrict (fn) {
var f = function () {
if (f.called)
throw new Error(f.onceError)
f.called = true
return f.value = fn.apply(this, arguments)
}
var name = fn.name || 'Function wrapped with `once`'
f.onceError = name + " shouldn't be called more than once"
f.called = false
return f
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 8569:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = __nccwpck_require__(3322);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 6099:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const path = __nccwpck_require__(5622);
const WIN_SLASH = '\\\\/';
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Posix glob regex
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const DOT_LITERAL = '\\.';
const PLUS_LITERAL = '\\+';
const QMARK_LITERAL = '\\?';
const SLASH_LITERAL = '\\/';
const ONE_CHAR = '(?=.)';
const QMARK = '[^/]';
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const NO_DOT = `(?!${DOT_LITERAL})`;
const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
const STAR = `${QMARK}*?`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Windows glob regex
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const WINDOWS_CHARS = {
...POSIX_CHARS,
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* POSIX Bracket Regex
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const POSIX_REGEX_SOURCE = {
alnum: 'a-zA-Z0-9',
alpha: 'a-zA-Z',
ascii: '\\x00-\\x7F',
blank: ' \\t',
cntrl: '\\x00-\\x1F\\x7F',
digit: '0-9',
graph: '\\x21-\\x7E',
lower: 'a-z',
print: '\\x20-\\x7E ',
punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
space: ' \\t\\r\\n\\v\\f',
upper: 'A-Z',
word: 'A-Za-z0-9_',
xdigit: 'A-Fa-f0-9'
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
'***': '*',
'**/**': '**',
'**/**/**': '**'
},
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// Digits
CHAR_0: 48, /* 0 */
CHAR_9: 57, /* 9 */
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// Alphabet chars.
CHAR_UPPERCASE_A: 65, /* A */
CHAR_LOWERCASE_A: 97, /* a */
CHAR_UPPERCASE_Z: 90, /* Z */
CHAR_LOWERCASE_Z: 122, /* z */
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
CHAR_LEFT_PARENTHESES: 40, /* ( */
CHAR_RIGHT_PARENTHESES: 41, /* ) */
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
CHAR_ASTERISK: 42, /* * */
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// Non-alphabetic chars.
CHAR_AMPERSAND: 38, /* & */
CHAR_AT: 64, /* @ */
CHAR_BACKWARD_SLASH: 92, /* \ */
CHAR_CARRIAGE_RETURN: 13, /* \r */
CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
CHAR_COLON: 58, /* : */
CHAR_COMMA: 44, /* , */
CHAR_DOT: 46, /* . */
CHAR_DOUBLE_QUOTE: 34, /* " */
CHAR_EQUAL: 61, /* = */
CHAR_EXCLAMATION_MARK: 33, /* ! */
CHAR_FORM_FEED: 12, /* \f */
CHAR_FORWARD_SLASH: 47, /* / */
CHAR_GRAVE_ACCENT: 96, /* ` */
CHAR_HASH: 35, /* # */
CHAR_HYPHEN_MINUS: 45, /* - */
CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
CHAR_LEFT_CURLY_BRACE: 123, /* { */
CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
CHAR_LINE_FEED: 10, /* \n */
CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
CHAR_PERCENT: 37, /* % */
CHAR_PLUS: 43, /* + */
CHAR_QUESTION_MARK: 63, /* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
CHAR_RIGHT_CURLY_BRACE: 125, /* } */
CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
CHAR_SEMICOLON: 59, /* ; */
CHAR_SINGLE_QUOTE: 39, /* ' */
CHAR_SPACE: 32, /* */
CHAR_TAB: 9, /* \t */
CHAR_UNDERSCORE: 95, /* _ */
CHAR_VERTICAL_LINE: 124, /* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
SEP: path.sep,
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Create EXTGLOB_CHARS
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
extglobChars(chars) {
return {
'!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
'?': { type: 'qmark', open: '(?:', close: ')?' },
'+': { type: 'plus', open: '(?:', close: ')+' },
'*': { type: 'star', open: '(?:', close: ')*' },
'@': { type: 'at', open: '(?:', close: ')' }
};
},
2021-09-26 15:31:45 -04:00
/**
2021-12-11 08:00:14 -05:00
* Create GLOB_CHARS
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 2139:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const constants = __nccwpck_require__(6099);
const utils = __nccwpck_require__(479);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Constants
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Helpers
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const expandRange = (args, options) => {
if (typeof options.expandRange === 'function') {
return options.expandRange(...args, options);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
args.sort();
const value = `[${args.join('-')}]`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
try {
/* eslint-disable-next-line no-new */
new RegExp(value);
} catch (ex) {
return args.map(v => utils.escapeRegex(v)).join('..');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return value;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Create the message for a syntax error
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Parse the given input string.
* @param {String} input
* @param {Object} options
* @return {Object}
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const parse = (input, options) => {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
input = REPLACEMENTS[input] || input;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const opts = { ...options };
const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const bos = { type: 'bos', value: '', output: opts.prepend || '' };
const tokens = [bos];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const capture = opts.capture ? '' : '?:';
const win32 = utils.isWindows(options);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// create constants based on platform, for windows or posix
const PLATFORM_CHARS = constants.globChars(win32);
const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const {
DOT_LITERAL,
PLUS_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK,
QMARK_NO_DOT,
STAR,
START_ANCHOR
} = PLATFORM_CHARS;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const globstar = opts => {
return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const nodot = opts.dot ? '' : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.capture) {
star = `(${star})`;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// minimatch options support
if (typeof opts.noext === 'boolean') {
opts.noextglob = opts.noext;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const state = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: '',
output: '',
prefix: '',
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
input = utils.removePrefix(input, state);
len = input.length;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Tokenizing helpers
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const eos = () => state.index === len - 1;
const peek = state.peek = (n = 1) => input[state.index + n];
const advance = state.advance = () => input[++state.index] || '';
const remaining = () => input.slice(state.index + 1);
const consume = (value = '', num = 0) => {
state.consumed += value;
state.index += num;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const append = token => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const negate = () => {
let count = 1;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
advance();
state.start++;
count++;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (count % 2 === 0) {
return false;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
state.negated = true;
state.start++;
return true;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const increment = type => {
state[type]++;
stack.push(type);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const decrement = type => {
state[type]--;
stack.pop();
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Push tokens onto the tokens array. This helper speeds up
* tokenizing by 1) helping us avoid backtracking as much as possible,
* and 2) helping us avoid creating extra tokens when consecutive
* characters are plain text. This improves performance and simplifies
* lookbehinds.
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const push = tok => {
if (prev.type === 'globstar') {
const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = 'star';
prev.value = '*';
prev.output = star;
state.output += prev.output;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (extglobs.length && tok.type !== 'paren') {
extglobs[extglobs.length - 1].inner += tok.value;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (tok.value || tok.output) append(tok);
if (prev && prev.type === 'text' && tok.type === 'text') {
prev.value += tok.value;
prev.output = (prev.output || '') + tok.value;
return;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const extglobOpen = (type, value) => {
const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? '(' : '') + token.open;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
increment('parens');
push({ type, value, output: state.output ? '' : ONE_CHAR });
push({ type: 'paren', extglob: true, value: advance(), output });
extglobs.push(token);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const extglobClose = token => {
let output = token.close + (opts.capture ? ')' : '');
let rest;
if (token.type === 'negate') {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
extglobStar = globstar(opts);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
output = token.close = `)$))${extglobStar}`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
output = token.close = `)${rest})${extglobStar})`;
}
if (token.prev.type === 'bos') {
state.negatedExtglob = true;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'paren', extglob: true, value, output });
decrement('parens');
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Fast paths
*/
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
if (first === '\\') {
backslashes = true;
return m;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (first === '?') {
if (esc) {
return esc + first + (rest ? QMARK.repeat(rest.length) : '');
}
if (index === 0) {
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
}
return QMARK.repeat(chars.length);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (first === '.') {
return DOT_LITERAL.repeat(chars.length);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (first === '*') {
if (esc) {
return esc + first + (rest ? star : '');
}
return star;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return esc ? m : `\\${m}`;
});
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (backslashes === true) {
if (opts.unescape === true) {
output = output.replace(/\\/g, '');
} else {
output = output.replace(/\\+/g, m => {
return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
});
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
state.output = utils.wrapOutput(output, state, options);
return state;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Tokenize input until we reach end-of-string
*/
while (!eos()) {
value = advance();
if (value === '\u0000') {
2021-09-26 15:31:45 -04:00
continue;
}
/**
2021-12-11 08:00:14 -05:00
* Escaped characters
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
if (value === '\\') {
const next = peek();
if (next === '/' && opts.bash !== true) {
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
if (next === '.' || next === ';') {
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
if (!next) {
value += '\\';
push({ type: 'text', value });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
// collapse slashes to reduce potential for exploits
const match = /^\\+/.exec(remaining());
let slashes = 0;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (match && match[0].length > 2) {
slashes = match[0].length;
state.index += slashes;
if (slashes % 2 !== 0) {
value += '\\';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.unescape === true) {
value = advance();
} else {
value += advance();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (state.brackets === 0) {
push({ type: 'text', value });
2021-09-26 15:31:45 -04:00
continue;
}
}
/**
2021-12-11 08:00:14 -05:00
* If we're inside a regex character class, continue
* until we reach the closing bracket.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
if (opts.posix !== false && value === ':') {
const inner = prev.value.slice(1);
if (inner.includes('[')) {
prev.posix = true;
if (inner.includes(':')) {
const idx = prev.value.lastIndexOf('[');
const pre = prev.value.slice(0, idx);
const rest = prev.value.slice(idx + 2);
const posix = POSIX_REGEX_SOURCE[rest];
if (posix) {
prev.value = pre + posix;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR;
}
continue;
}
}
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
value = `\\${value}`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
value = `\\${value}`;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.posix === true && value === '!' && prev.value === '[') {
value = '^';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
prev.value += value;
append({ value });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* If we're inside a quoted string, continue
* until we reach the closing double quote.
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (state.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value);
prev.value += value;
append({ value });
2021-09-26 15:31:45 -04:00
continue;
}
/**
2021-12-11 08:00:14 -05:00
* Double quotes
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
if (value === '"') {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push({ type: 'text', value });
2021-09-26 15:31:45 -04:00
}
continue;
}
/**
2021-12-11 08:00:14 -05:00
* Parentheses
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
if (value === '(') {
increment('parens');
push({ type: 'paren', value });
continue;
}
if (value === ')') {
if (state.parens === 0 && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('opening', '('));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
decrement('parens');
2021-09-26 15:31:45 -04:00
continue;
}
/**
2021-12-11 08:00:14 -05:00
* Square brackets
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
if (value === '[') {
if (opts.nobracket === true || !remaining().includes(']')) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('closing', ']'));
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
value = `\\${value}`;
} else {
increment('brackets');
}
push({ type: 'bracket', value });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
if (value === ']') {
if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
push({ type: 'text', value, output: `\\${value}` });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
if (state.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('opening', '['));
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'text', value, output: `\\${value}` });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
decrement('brackets');
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
value = `/${value}`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
prev.value += value;
append({ value });
// when literal brackets are explicitly disabled
// assume we should match with a regex character class
if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
const escaped = utils.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// when literal brackets are explicitly enabled
// assume we should escape the brackets to match literal characters
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
// when the user specifies nothing, try to match both
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Braces
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '{' && opts.nobrace !== true) {
increment('braces');
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const open = {
type: 'brace',
value,
output: '(',
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
braces.push(open);
push(open);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '}') {
const brace = braces[braces.length - 1];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.nobrace === true || !brace) {
push({ type: 'text', value, output: value });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
let output = ')';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === 'brace') {
break;
}
if (arr[i].type !== 'dots') {
range.unshift(arr[i].value);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
output = expandRange(range, opts);
state.backtrack = true;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = '\\{';
value = output = '\\}';
state.output = out;
for (const t of toks) {
state.output += (t.output || t.value);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'brace', value, output });
decrement('braces');
braces.pop();
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
/**
* Pipes
*/
if (value === '|') {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push({ type: 'text', value });
2021-09-26 15:31:45 -04:00
continue;
}
2021-12-11 08:00:14 -05:00
/**
* Commas
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === ',') {
let output = value;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === 'braces') {
brace.comma = true;
output = '|';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'comma', value, output });
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* Slashes
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '/') {
// if the beginning of the glob is "./", advance the start
// to the current index, and don't add the "./" characters
// to the state. This greatly simplifies lookbehinds when
// checking for BOS characters like "!" and "." (not "./")
if (prev.type === 'dot' && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = '';
state.output = '';
tokens.pop();
prev = bos; // reset "prev" to the first token
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'slash', value, output: SLASH_LITERAL });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Dots
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '.') {
if (state.braces > 0 && prev.type === 'dot') {
if (prev.value === '.') prev.output = DOT_LITERAL;
const brace = braces[braces.length - 1];
prev.type = 'dots';
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
push({ type: 'text', value, output: DOT_LITERAL });
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'dot', value, output: DOT_LITERAL });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Question marks
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '?') {
const isGroup = prev && prev.value === '(';
if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
extglobOpen('qmark', value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prev && prev.type === 'paren') {
const next = peek();
let output = value;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (next === '<' && !utils.supportsLookbehinds()) {
throw new Error('Node.js v10 or higher is required for regex lookbehinds');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
output = `\\${value}`;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'text', value, output });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
push({ type: 'qmark', value, output: QMARK_NO_DOT });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'qmark', value, output: QMARK });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Exclamation
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '!') {
if (opts.noextglob !== true && peek() === '(') {
if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
extglobOpen('negate', value);
continue;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Plus
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '+') {
if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
extglobOpen('plus', value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if ((prev && prev.value === '(') || opts.regex === false) {
push({ type: 'plus', value, output: PLUS_LITERAL });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
push({ type: 'plus', value });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'plus', value: PLUS_LITERAL });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Plain text
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value === '@') {
if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
push({ type: 'at', extglob: true, value, output: '' });
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push({ type: 'text', value });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Plain text
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (value !== '*') {
if (value === '$' || value === '^') {
value = `\\${value}`;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state.index += match[0].length;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push({ type: 'text', value });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Stars
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prev && (prev.type === 'globstar' || prev.star === true)) {
prev.type = 'star';
prev.star = true;
prev.value += value;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume(value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen('star', value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prev.type === 'star') {
if (opts.noglobstar === true) {
consume(value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === 'slash' || prior.type === 'bos';
const afterStar = before && (before.type === 'star' || before.type === 'globstar');
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
push({ type: 'star', value, output: '' });
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
push({ type: 'star', value, output: '' });
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// strip consecutive `/**/`
while (rest.slice(0, 3) === '/**') {
const after = input[state.index + 4];
if (after && after !== '/') {
break;
}
rest = rest.slice(3);
consume('/**', 3);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prior.type === 'bos' && eos()) {
prev.type = 'globstar';
prev.value += value;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
prev.type = 'globstar';
prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value);
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
const end = rest[1] !== void 0 ? '|$' : '';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
prev.type = 'globstar';
prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
prev.value += value;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
state.output += prior.output + prev.output;
state.globstar = true;
consume(value + advance());
push({ type: 'slash', value: '/', output: '' });
continue;
}
if (prior.type === 'bos' && rest[0] === '/') {
prev.type = 'globstar';
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
state.output = prev.output;
state.globstar = true;
consume(value + advance());
push({ type: 'slash', value: '/', output: '' });
continue;
}
// remove single star from output
state.output = state.output.slice(0, -prev.output.length);
// reset previous token to globstar
prev.type = 'globstar';
prev.output = globstar(opts);
prev.value += value;
// reset output with globstar
state.output += prev.output;
state.globstar = true;
consume(value);
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const token = { type: 'star', value, output: star };
if (opts.bash === true) {
token.output = '.*?';
if (prev.type === 'bos' || prev.type === 'slash') {
token.output = nodot + token.output;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
push(token);
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
token.output = value;
push(token);
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
if (prev.type === 'dot') {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
} else {
state.output += nodot;
prev.output += nodot;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (peek() !== '*') {
state.output += ONE_CHAR;
prev.output += ONE_CHAR;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
push(token);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
while (state.brackets > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
state.output = utils.escapeLast(state.output, '[');
decrement('brackets');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
while (state.parens > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
state.output = utils.escapeLast(state.output, '(');
decrement('parens');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
while (state.braces > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
state.output = utils.escapeLast(state.output, '{');
decrement('braces');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// rebuild the output if we had to backtrack at any point
if (state.backtrack === true) {
state.output = '';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (token.suffix) {
state.output += token.suffix;
}
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return state;
2021-09-26 15:31:45 -04:00
};
/**
2021-12-11 08:00:14 -05:00
* Fast paths for creating regular expressions for common glob patterns.
* This can significantly speed up processing and has very little downside
* impact when none of the fast paths match.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
parse.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
input = REPLACEMENTS[input] || input;
const win32 = utils.isWindows(options);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// create constants based on platform, for windows or posix
const {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants.globChars(win32);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? '' : '?:';
const state = { negated: false, prefix: '' };
let star = opts.bash === true ? '.*?' : STAR;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.capture) {
star = `(${star})`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const globstar = opts => {
if (opts.noglobstar === true) return star;
return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const create = str => {
switch (str) {
case '*':
return `${nodot}${ONE_CHAR}${star}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
case '.*':
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
case '*.*':
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
case '*/*':
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
case '**':
return nodot + globstar(opts);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
case '**/*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
case '**/*.*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case '**/.*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match) return;
const source = create(match[1]);
if (!source) return;
return source + DOT_LITERAL + match[2];
}
}
};
const output = utils.removePrefix(input, state);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL}?`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return source;
2021-09-26 15:31:45 -04:00
};
2021-12-11 08:00:14 -05:00
module.exports = parse;
/***/ }),
/***/ 3322:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
const path = __nccwpck_require__(5622);
const scan = __nccwpck_require__(2429);
const parse = __nccwpck_require__(2139);
const utils = __nccwpck_require__(479);
const constants = __nccwpck_require__(6099);
const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
2021-09-26 15:31:45 -04:00
/**
2021-12-11 08:00:14 -05:00
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
2021-09-26 15:31:45 -04:00
*
* ```js
* const picomatch = require('picomatch');
2021-12-11 08:00:14 -05:00
* // picomatch(glob[, options]);
2021-09-26 15:31:45 -04:00
*
2021-12-11 08:00:14 -05:00
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
2021-09-26 15:31:45 -04:00
* @api public
*/
2021-12-11 08:00:14 -05:00
const picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map(input => picomatch(input, options, returnState));
const arrayMatcher = str => {
for (const isMatch of fns) {
const state = isMatch(str);
if (state) return state;
}
return false;
};
return arrayMatcher;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const isState = isObject(glob) && glob.tokens && glob.input;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (glob === '' || (typeof glob !== 'string' && !isState)) {
throw new TypeError('Expected pattern to be a non-empty string');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const opts = options || {};
const posix = utils.isWindows(options);
const regex = isState
? picomatch.compileRe(glob, options)
: picomatch.makeRe(glob, options, false, true);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const state = regex.state;
delete regex.state;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
const result = { glob, state, regex, posix, input, output, match, isMatch };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (typeof opts.onResult === 'function') {
opts.onResult(result);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (isIgnored(input)) {
if (typeof opts.onIgnore === 'function') {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (typeof opts.onMatch === 'function') {
opts.onMatch(result);
}
return returnObject ? result : true;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (returnState) {
matcher.state = state;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return matcher;
2021-09-26 15:31:45 -04:00
};
/**
2021-12-11 08:00:14 -05:00
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
2021-09-26 15:31:45 -04:00
*
* ```js
2021-12-11 08:00:14 -05:00
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
2021-09-26 15:31:45 -04:00
* ```
2021-12-11 08:00:14 -05:00
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
2021-09-26 15:31:45 -04:00
* @api public
*/
2021-12-11 08:00:14 -05:00
picomatch.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (input === '') {
return { isMatch: false, output: '' };
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const opts = options || {};
const format = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = (match && format) ? format(input) : input;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix);
} else {
match = regex.exec(output);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return { isMatch: Boolean(match), match, output };
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(path.basename(input));
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.scan = (input, options) => scan(input, options);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Compile a regular expression from the `state` object returned by the
* [parse()](#parse) method.
*
* @param {Object} `state`
* @param {Object} `options`
* @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
* @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* @return {RegExp}
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const opts = options || {};
const prepend = opts.contains ? '' : '^';
const append = opts.contains ? '' : '$';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = state;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return regex;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== 'string') {
throw new TypeError('Expected a non-empty string');
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let parsed = { negated: false, fastpaths: true };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
parsed.output = parse.fastpaths(input, options);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (!parsed.output) {
parsed = parse(input, options);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Picomatch constants.
* @return {Object}
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
picomatch.constants = constants;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Expose "picomatch"
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = picomatch;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 2429:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const utils = __nccwpck_require__(479);
const {
CHAR_ASTERISK, /* * */
CHAR_AT, /* @ */
CHAR_BACKWARD_SLASH, /* \ */
CHAR_COMMA, /* , */
CHAR_DOT, /* . */
CHAR_EXCLAMATION_MARK, /* ! */
CHAR_FORWARD_SLASH, /* / */
CHAR_LEFT_CURLY_BRACE, /* { */
CHAR_LEFT_PARENTHESES, /* ( */
CHAR_LEFT_SQUARE_BRACKET, /* [ */
CHAR_PLUS, /* + */
CHAR_QUESTION_MARK, /* ? */
CHAR_RIGHT_CURLY_BRACE, /* } */
CHAR_RIGHT_PARENTHESES, /* ) */
CHAR_RIGHT_SQUARE_BRACKET /* ] */
} = __nccwpck_require__(6099);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const isPathSeparator = code => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const depth = token => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const scan = (input, options) => {
const opts = options || {};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = { value: '', depth: 0, isGlob: false };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
2021-09-26 15:31:45 -04:00
};
2021-12-11 08:00:14 -05:00
while (index < length) {
code = advance();
let next;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
continue;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: '', depth: 0, isGlob: false };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (finished === true) continue;
if (prev === CHAR_DOT && index === (start + 1)) {
start += 2;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
lastIndex = index + 1;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS
|| code === CHAR_AT
|| code === CHAR_ASTERISK
|| code === CHAR_QUESTION_MARK
|| code === CHAR_EXCLAMATION_MARK;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
break;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (isGlob === true) {
finished = true;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (scanToEnd === true) {
continue;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
break;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
let base = str;
let prefix = '';
let glob = '';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = '';
glob = str;
2021-09-26 15:31:45 -04:00
} else {
2021-12-11 08:00:14 -05:00
base = str;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (base && base !== '' && base !== '/' && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
if (opts.unescape === true) {
if (glob) glob = utils.removeBackslashes(glob);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.tokens = tokens;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== '') {
parts.push(value);
}
prevIndex = i;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
state.slashes = slashes;
state.parts = parts;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return state;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = scan;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 479:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
const path = __nccwpck_require__(5622);
const win32 = process.platform === 'win32';
const {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = __nccwpck_require__(6099);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.removeBackslashes = str => {
return str.replace(REGEX_REMOVE_BACKSLASH, match => {
return match === '\\' ? '' : match;
});
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.supportsLookbehinds = () => {
const segs = process.version.slice(1).split('.').map(Number);
if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
return true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return false;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.isWindows = options => {
if (options && typeof options.windows === 'boolean') {
return options.windows;
}
return win32 === true || path.sep === '\\';
2021-09-26 15:31:45 -04:00
};
2021-12-11 08:00:14 -05:00
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith('./')) {
output = output.slice(2);
state.prefix = './';
}
return output;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
exports.wrapOutput = (input, state = {}, options = {}) => {
const prepend = options.contains ? '' : '^';
const append = options.contains ? '' : '$';
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return output;
};
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 9795:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
let promise
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
// reuse resolved promise, and allocate it lazily
: cb => (promise || (promise = Promise.resolve()))
.then(cb)
.catch(err => setTimeout(() => { throw err }, 0))
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 2113:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
function reusify (Constructor) {
var head = new Constructor()
var tail = head
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function get () {
var current = head
if (current.next) {
head = current.next
2021-09-26 15:31:45 -04:00
} else {
2021-12-11 08:00:14 -05:00
head = new Constructor()
tail = head
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
current.next = null
return current
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function release (obj) {
tail.next = obj
tail = obj
}
return {
get: get,
release: release
}
}
module.exports = reusify
/***/ }),
/***/ 5288:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
module.exports = runParallel
const queueMicrotask = __nccwpck_require__(9795)
function runParallel (tasks, cb) {
let results, pending, keys
let isSync = true
if (Array.isArray(tasks)) {
results = []
pending = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) queueMicrotask(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (--pending === 0 || err) {
done(err)
}
}
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.forEach(function (key) {
tasks[key](function (err, result) { each(key, err, result) })
})
} else {
// array
tasks.forEach(function (task, i) {
task(function (err, result) { each(i, err, result) })
})
}
isSync = false
}
/***/ }),
/***/ 1861:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
/*!
* to-regex-range <https://github.com/micromatch/to-regex-range>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*/
const isNumber = __nccwpck_require__(5680);
const toRegexRange = (min, max, options) => {
if (isNumber(min) === false) {
throw new TypeError('toRegexRange: expected the first argument to be a number');
}
if (max === void 0 || min === max) {
return String(min);
}
if (isNumber(max) === false) {
throw new TypeError('toRegexRange: expected the second argument to be a number.');
}
let opts = { relaxZeros: true, ...options };
if (typeof opts.strictZeros === 'boolean') {
opts.relaxZeros = opts.strictZeros === false;
}
let relax = String(opts.relaxZeros);
let shorthand = String(opts.shorthand);
let capture = String(opts.capture);
let wrap = String(opts.wrap);
let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
return toRegexRange.cache[cacheKey].result;
}
let a = Math.min(min, max);
let b = Math.max(min, max);
if (Math.abs(a - b) === 1) {
let result = min + '|' + max;
if (opts.capture) {
return `(${result})`;
}
if (opts.wrap === false) {
return result;
}
return `(?:${result})`;
}
let isPadded = hasPadding(min) || hasPadding(max);
let state = { min, max, a, b };
let positives = [];
let negatives = [];
if (isPadded) {
state.isPadded = isPadded;
state.maxLen = String(state.max).length;
}
if (a < 0) {
let newMin = b < 0 ? Math.abs(b) : 1;
negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
a = state.a = 0;
}
if (b >= 0) {
positives = splitToPatterns(a, b, state, opts);
}
state.negatives = negatives;
state.positives = positives;
state.result = collatePatterns(negatives, positives, opts);
if (opts.capture === true) {
state.result = `(${state.result})`;
} else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
state.result = `(?:${state.result})`;
}
toRegexRange.cache[cacheKey] = state;
return state.result;
};
function collatePatterns(neg, pos, options) {
let onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
let onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
let intersected = filterPatterns(neg, pos, '-?', true, options) || [];
let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
return subpatterns.join('|');
}
function splitToRanges(min, max) {
let nines = 1;
let zeros = 1;
let stop = countNines(min, nines);
let stops = new Set([max]);
while (min <= stop && stop <= max) {
stops.add(stop);
nines += 1;
stop = countNines(min, nines);
}
stop = countZeros(max + 1, zeros) - 1;
while (min < stop && stop <= max) {
stops.add(stop);
zeros += 1;
stop = countZeros(max + 1, zeros) - 1;
}
stops = [...stops];
stops.sort(compare);
return stops;
}
/**
* Convert a range to a regex pattern
* @param {Number} `start`
* @param {Number} `stop`
* @return {String}
*/
function rangeToPattern(start, stop, options) {
if (start === stop) {
return { pattern: start, count: [], digits: 0 };
}
let zipped = zip(start, stop);
let digits = zipped.length;
let pattern = '';
let count = 0;
for (let i = 0; i < digits; i++) {
let [startDigit, stopDigit] = zipped[i];
if (startDigit === stopDigit) {
pattern += startDigit;
} else if (startDigit !== '0' || stopDigit !== '9') {
pattern += toCharacterClass(startDigit, stopDigit, options);
} else {
count++;
}
}
if (count) {
pattern += options.shorthand === true ? '\\d' : '[0-9]';
}
return { pattern, count: [count], digits };
}
2021-09-26 15:31:45 -04:00
function splitToPatterns(min, max, tok, options) {
let ranges = splitToRanges(min, max);
let tokens = [];
let start = min;
let prev;
for (let i = 0; i < ranges.length; i++) {
let max = ranges[i];
let obj = rangeToPattern(String(start), String(max), options);
let zeros = '';
if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
if (prev.count.length > 1) {
prev.count.pop();
}
prev.count.push(obj.count[0]);
prev.string = prev.pattern + toQuantifier(prev.count);
start = max + 1;
continue;
}
if (tok.isPadded) {
zeros = padZeros(max, tok, options);
}
obj.string = zeros + obj.pattern + toQuantifier(obj.count);
tokens.push(obj);
start = max + 1;
prev = obj;
}
return tokens;
}
function filterPatterns(arr, comparison, prefix, intersection, options) {
let result = [];
for (let ele of arr) {
let { string } = ele;
// only push if _both_ are negative...
if (!intersection && !contains(comparison, 'string', string)) {
result.push(prefix + string);
}
// or _both_ are positive
if (intersection && contains(comparison, 'string', string)) {
result.push(prefix + string);
}
}
return result;
}
/**
* Zip strings
*/
function zip(a, b) {
let arr = [];
for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
return arr;
}
function compare(a, b) {
return a > b ? 1 : b > a ? -1 : 0;
}
function contains(arr, key, val) {
return arr.some(ele => ele[key] === val);
}
function countNines(min, len) {
return Number(String(min).slice(0, -len) + '9'.repeat(len));
}
function countZeros(integer, zeros) {
return integer - (integer % Math.pow(10, zeros));
}
function toQuantifier(digits) {
let [start = 0, stop = ''] = digits;
if (stop || start > 1) {
return `{${start + (stop ? ',' + stop : '')}}`;
}
return '';
}
function toCharacterClass(a, b, options) {
return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
}
function hasPadding(str) {
return /^-?(0+)\d/.test(str);
}
function padZeros(value, tok, options) {
if (!tok.isPadded) {
return value;
}
let diff = Math.abs(tok.maxLen - String(value).length);
let relax = options.relaxZeros !== false;
switch (diff) {
case 0:
return '';
case 1:
return relax ? '0?' : '0';
case 2:
return relax ? '0{0,2}' : '00';
default: {
return relax ? `0{0,${diff}}` : `0{${diff}}`;
}
}
}
/**
* Cache
*/
toRegexRange.cache = {};
toRegexRange.clearCache = () => (toRegexRange.cache = {});
/**
* Expose `toRegexRange`
*/
module.exports = toRegexRange;
/***/ }),
2021-12-11 08:00:14 -05:00
/***/ 4920:
2021-09-26 15:31:45 -04:00
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2021-12-11 08:00:14 -05:00
var parser = __nccwpck_require__(5642);
var compiler = __nccwpck_require__(8215);
module.exports = {
parse: function(input) {
var nodes = parser.parse(input.toString());
return compiler.compile(nodes);
}
};
2021-09-26 15:31:45 -04:00
/***/ }),
2021-12-11 08:00:14 -05:00
/***/ 8215:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
"use strict";
2021-12-11 08:00:14 -05:00
function compile(nodes) {
var assignedPaths = [];
var valueAssignments = [];
var currentPath = "";
var data = Object.create(null);
var context = data;
var arrayMode = false;
return reduce(nodes);
function reduce(nodes) {
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
switch (node.type) {
case "Assign":
assign(node);
break;
case "ObjectPath":
setPath(node);
break;
case "ArrayPath":
addTableArray(node);
break;
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return data;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function assign(node) {
var key = node.key;
var value = node.value;
var line = node.line;
var column = node.column;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
var fullPath;
if (currentPath) {
fullPath = currentPath + "." + key;
} else {
fullPath = key;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (typeof context[key] !== "undefined") {
genError("Cannot redefine existing key '" + fullPath + "'.", line, column);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
context[key] = reduceValueNode(value);
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (!pathAssigned(fullPath)) {
assignedPaths.push(fullPath);
valueAssignments.push(fullPath);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function pathAssigned(path) {
return assignedPaths.indexOf(path) !== -1;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function reduceValueNode(node) {
if (node.type === "Array") {
return reduceArrayWithTypeChecking(node.value);
} else if (node.type === "InlineTable") {
return reduceInlineTableNode(node.value);
} else {
return node.value;
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function reduceInlineTableNode(values) {
var obj = Object.create(null);
for (var i = 0; i < values.length; i++) {
var val = values[i];
if (val.value.type === "InlineTable") {
obj[val.key] = reduceInlineTableNode(val.value.value);
} else if (val.type === "InlineTableValue") {
obj[val.key] = reduceValueNode(val.value);
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return obj;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function setPath(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (pathAssigned(quotedPath)) {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
assignedPaths.push(quotedPath);
context = deepRef(data, path, Object.create(null), line, column);
currentPath = path;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function addTableArray(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (!pathAssigned(quotedPath)) {
assignedPaths.push(quotedPath);
}
assignedPaths = assignedPaths.filter(function(p) {
return p.indexOf(quotedPath) !== 0;
});
assignedPaths.push(quotedPath);
context = deepRef(data, path, [], line, column);
currentPath = quotedPath;
if (context instanceof Array) {
var newObj = Object.create(null);
context.push(newObj);
context = newObj;
} else {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
}
// Given a path 'a.b.c', create (as necessary) `start.a`,
// `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`.
// If `a` or `b` are arrays and have items in them, the last item in the
// array is used as the context for the next sub-path.
function deepRef(start, keys, value, line, column) {
var traversed = [];
var traversedPath = "";
var path = keys.join(".");
var ctx = start;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
traversed.push(key);
traversedPath = traversed.join(".");
if (typeof ctx[key] === "undefined") {
if (i === keys.length - 1) {
ctx[key] = value;
} else {
ctx[key] = Object.create(null);
}
} else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) {
// already a non-object value at key, can't be used as part of a new path
genError("Cannot redefine existing key '" + traversedPath + "'.", line, column);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
ctx = ctx[key];
if (ctx instanceof Array && ctx.length && i < keys.length - 1) {
ctx = ctx[ctx.length - 1];
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return ctx;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function reduceArrayWithTypeChecking(array) {
// Ensure that all items in the array are of the same type
var firstType = null;
for (var i = 0; i < array.length; i++) {
var node = array[i];
if (firstType === null) {
firstType = node.type;
} else {
if (node.type !== firstType) {
genError("Cannot add value of type " + node.type + " to array of type " +
firstType + ".", node.line, node.column);
2021-09-26 15:31:45 -04:00
}
}
}
2021-12-11 08:00:14 -05:00
// Recursively reduce array of nodes into array of the nodes' values
return array.map(reduceValueNode);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function quoteDottedString(str) {
if (str.indexOf(".") > -1) {
return "\"" + str + "\"";
2021-09-26 15:31:45 -04:00
} else {
2021-12-11 08:00:14 -05:00
return str;
2021-09-26 15:31:45 -04:00
}
}
}
2021-12-11 08:00:14 -05:00
module.exports = {
compile: compile
};
2021-09-26 15:31:45 -04:00
/***/ }),
2021-12-11 08:00:14 -05:00
/***/ 5642:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = [],
peg$c1 = function() { return nodes },
peg$c2 = peg$FAILED,
peg$c3 = "#",
peg$c4 = { type: "literal", value: "#", description: "\"#\"" },
peg$c5 = void 0,
peg$c6 = { type: "any", description: "any character" },
peg$c7 = "[",
peg$c8 = { type: "literal", value: "[", description: "\"[\"" },
peg$c9 = "]",
peg$c10 = { type: "literal", value: "]", description: "\"]\"" },
peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) },
peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) },
peg$c13 = function(parts, name) { return parts.concat(name) },
peg$c14 = function(name) { return [name] },
peg$c15 = function(name) { return name },
peg$c16 = ".",
peg$c17 = { type: "literal", value: ".", description: "\".\"" },
peg$c18 = "=",
peg$c19 = { type: "literal", value: "=", description: "\"=\"" },
peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) },
peg$c21 = function(chars) { return chars.join('') },
peg$c22 = function(node) { return node.value },
peg$c23 = "\"\"\"",
peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" },
peg$c25 = null,
peg$c26 = function(chars) { return node('String', chars.join(''), line, column) },
peg$c27 = "\"",
peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" },
peg$c29 = "'''",
peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" },
peg$c31 = "'",
peg$c32 = { type: "literal", value: "'", description: "\"'\"" },
peg$c33 = function(char) { return char },
peg$c34 = function(char) { return char},
peg$c35 = "\\",
peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" },
peg$c37 = function() { return '' },
peg$c38 = "e",
peg$c39 = { type: "literal", value: "e", description: "\"e\"" },
peg$c40 = "E",
peg$c41 = { type: "literal", value: "E", description: "\"E\"" },
peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) },
peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) },
peg$c44 = "+",
peg$c45 = { type: "literal", value: "+", description: "\"+\"" },
peg$c46 = function(digits) { return digits.join('') },
peg$c47 = "-",
peg$c48 = { type: "literal", value: "-", description: "\"-\"" },
peg$c49 = function(digits) { return '-' + digits.join('') },
peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) },
peg$c51 = "true",
peg$c52 = { type: "literal", value: "true", description: "\"true\"" },
peg$c53 = function() { return node('Boolean', true, line, column) },
peg$c54 = "false",
peg$c55 = { type: "literal", value: "false", description: "\"false\"" },
peg$c56 = function() { return node('Boolean', false, line, column) },
peg$c57 = function() { return node('Array', [], line, column) },
peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) },
peg$c59 = function(values) { return node('Array', values, line, column) },
peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) },
peg$c61 = function(value) { return value },
peg$c62 = ",",
peg$c63 = { type: "literal", value: ",", description: "\",\"" },
peg$c64 = "{",
peg$c65 = { type: "literal", value: "{", description: "\"{\"" },
peg$c66 = "}",
peg$c67 = { type: "literal", value: "}", description: "\"}\"" },
peg$c68 = function(values) { return node('InlineTable', values, line, column) },
peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) },
peg$c70 = function(digits) { return "." + digits },
peg$c71 = function(date) { return date.join('') },
peg$c72 = ":",
peg$c73 = { type: "literal", value: ":", description: "\":\"" },
peg$c74 = function(time) { return time.join('') },
peg$c75 = "T",
peg$c76 = { type: "literal", value: "T", description: "\"T\"" },
peg$c77 = "Z",
peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" },
peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) },
peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) },
peg$c81 = /^[ \t]/,
peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" },
peg$c83 = "\n",
peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" },
peg$c85 = "\r",
peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" },
peg$c87 = /^[0-9a-f]/i,
peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" },
peg$c89 = /^[0-9]/,
peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" },
peg$c91 = "_",
peg$c92 = { type: "literal", value: "_", description: "\"_\"" },
peg$c93 = function() { return "" },
peg$c94 = /^[A-Za-z0-9_\-]/,
peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" },
peg$c96 = function(d) { return d.join('') },
peg$c97 = "\\\"",
peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" },
peg$c99 = function() { return '"' },
peg$c100 = "\\\\",
peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" },
peg$c102 = function() { return '\\' },
peg$c103 = "\\b",
peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" },
peg$c105 = function() { return '\b' },
peg$c106 = "\\t",
peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" },
peg$c108 = function() { return '\t' },
peg$c109 = "\\n",
peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" },
peg$c111 = function() { return '\n' },
peg$c112 = "\\f",
peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" },
peg$c114 = function() { return '\f' },
peg$c115 = "\\r",
peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" },
peg$c117 = function() { return '\r' },
peg$c118 = "\\U",
peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" },
peg$c120 = function(digits) { return convertCodePoint(digits.join('')) },
peg$c121 = "\\u",
peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$cache = {},
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function offset() {
return peg$reportedPos;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return peg$cachedPosDetails;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsestart() {
var s0, s1, s2;
var key = peg$currPos * 49 + 0,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseline();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseline();
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c1();
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseline() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 1,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parseexpression();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parsecomment();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parsecomment();
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseNL();
if (s6 !== peg$FAILED) {
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseNL();
}
} else {
s5 = peg$c2;
}
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
if (s5 !== peg$FAILED) {
s1 = [s1, s2, s3, s4, s5];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
} else {
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseNL();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseNL();
}
} else {
s2 = peg$c2;
}
if (s2 === peg$FAILED) {
s2 = peg$parseEOF();
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s0 === peg$FAILED) {
s0 = peg$parseNL();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseexpression() {
var s0;
var key = peg$currPos * 49 + 2,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsecomment();
if (s0 === peg$FAILED) {
s0 = peg$parsepath();
if (s0 === peg$FAILED) {
s0 = peg$parsetablearray();
if (s0 === peg$FAILED) {
s0 = peg$parseassignment();
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsecomment() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 3,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 35) {
s1 = peg$c3;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c4); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseNL();
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c5;
} else {
peg$currPos = s4;
s4 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
} else {
peg$currPos = s3;
s3 = peg$c2;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseNL();
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c5;
} else {
peg$currPos = s4;
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s3;
s3 = peg$c2;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsepath() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 4,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetable_key();
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s5 = peg$c9;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c11(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsetablearray() {
var s0, s1, s2, s3, s4, s5, s6, s7;
var key = peg$currPos * 49 + 5,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 91) {
s2 = peg$c7;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
s4 = peg$parsetable_key();
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s6 = peg$c9;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s7 = peg$c9;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c12(s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetable_key() {
var s0, s1, s2;
var key = peg$currPos * 49 + 6,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsedot_ended_table_key_part();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsedot_ended_table_key_part();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsetable_key_part();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c13(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsetable_key_part();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c14(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsetable_key_part() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 7,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsequoted_key();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsedot_ended_table_key_part() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 8,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsequoted_key();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseassignment() {
var s0, s1, s2, s3, s4, s5;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
var key = peg$currPos * 49 + 9,
cached = peg$cache[key];
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
s0 = peg$currPos;
s1 = peg$parsekey();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c18;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsevalue();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c20(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsequoted_key();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c18;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsevalue();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c20(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsekey() {
var s0, s1, s2;
var key = peg$currPos * 49 + 10,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseASCII_BASIC();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseASCII_BASIC();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c21(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsequoted_key() {
var s0, s1;
var key = peg$currPos * 49 + 11,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsedouble_quoted_single_line_string();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsesingle_quoted_single_line_string();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsevalue() {
var s0;
var key = peg$currPos * 49 + 12,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsestring();
if (s0 === peg$FAILED) {
s0 = peg$parsedatetime();
if (s0 === peg$FAILED) {
s0 = peg$parsefloat();
if (s0 === peg$FAILED) {
s0 = peg$parseinteger();
if (s0 === peg$FAILED) {
s0 = peg$parseboolean();
if (s0 === peg$FAILED) {
s0 = peg$parsearray();
if (s0 === peg$FAILED) {
s0 = peg$parseinline_table();
}
}
}
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsestring() {
var s0;
var key = peg$currPos * 49 + 13,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsedouble_quoted_multiline_string();
if (s0 === peg$FAILED) {
s0 = peg$parsedouble_quoted_single_line_string();
if (s0 === peg$FAILED) {
s0 = peg$parsesingle_quoted_multiline_string();
if (s0 === peg$FAILED) {
s0 = peg$parsesingle_quoted_single_line_string();
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsedouble_quoted_multiline_string() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 14,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c23) {
s1 = peg$c23;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsemultiline_string_char();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsemultiline_string_char();
}
if (s3 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c23) {
s4 = peg$c23;
peg$currPos += 3;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsedouble_quoted_single_line_string() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 15,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c27;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsestring_char();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsestring_char();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c27;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsesingle_quoted_multiline_string() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 16,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c29) {
s1 = peg$c29;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsemultiline_literal_char();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsemultiline_literal_char();
}
if (s3 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c29) {
s4 = peg$c29;
peg$currPos += 3;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsesingle_quoted_single_line_string() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 17,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 39) {
s1 = peg$c31;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseliteral_char();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseliteral_char();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 39) {
s3 = peg$c31;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsestring_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 18,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseESCAPED();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 34) {
s2 = peg$c27;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseliteral_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 19,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 39) {
s2 = peg$c31;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsemultiline_string_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 20,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseESCAPED();
if (s0 === peg$FAILED) {
s0 = peg$parsemultiline_string_delim();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 3) === peg$c23) {
s2 = peg$c23;
peg$currPos += 3;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c34(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsemultiline_string_delim() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 21,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s1 = peg$c35;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseNLS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseNLS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c37();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsemultiline_literal_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 22,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 3) === peg$c29) {
s2 = peg$c29;
peg$currPos += 3;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsefloat() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 23,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsefloat_text();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger_text();
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 101) {
s2 = peg$c38;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c39); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 69) {
s2 = peg$c40;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c41); }
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
s3 = peg$parseinteger_text();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c42(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsefloat_text();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c43(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsefloat_text() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 24,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 43) {
s1 = peg$c44;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
if (s1 === peg$FAILED) {
s1 = peg$c25;
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseDIGITS();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGITS();
if (s5 !== peg$FAILED) {
s3 = [s3, s4, s5];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c46(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseDIGITS();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGITS();
if (s5 !== peg$FAILED) {
s3 = [s3, s4, s5];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c49(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseinteger() {
var s0, s1;
var key = peg$currPos * 49 + 25,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseinteger_text();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c50(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseinteger_text() {
var s0, s1, s2, s3, s4;
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
var key = peg$currPos * 49 + 26,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 43) {
s1 = peg$c44;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
if (s1 === peg$FAILED) {
s1 = peg$c25;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseDIGIT_OR_UNDER();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c5;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c46(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseDIGIT_OR_UNDER();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c5;
} else {
peg$currPos = s3;
s3 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c49(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseboolean() {
var s0, s1;
var key = peg$currPos * 49 + 27,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 4) === peg$c51) {
s1 = peg$c51;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c52); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c53();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c54) {
s1 = peg$c54;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c56();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsearray() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 28,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_sep();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_sep();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c57();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
s2 = peg$parsearray_value();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c58(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_value_list();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_value_list();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c59(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_value_list();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_value_list();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsearray_value();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s4 = peg$c9;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c60(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsearray_value() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 29,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsearray_sep();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsearray_sep();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsevalue();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsearray_sep();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsearray_sep();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsearray_value_list() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 30,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsearray_sep();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsearray_sep();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsevalue();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsearray_sep();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsearray_sep();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s4 = peg$c62;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c63); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parsearray_sep();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parsearray_sep();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsearray_sep() {
var s0;
var key = peg$currPos * 49 + 31,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseS();
if (s0 === peg$FAILED) {
s0 = peg$parseNL();
if (s0 === peg$FAILED) {
s0 = peg$parsecomment();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseinline_table() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 32,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c64;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c65); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseinline_table_assignment();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseinline_table_assignment();
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s5 = peg$c66;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c67); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c68(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseinline_table_assignment() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 33,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s4 = peg$c18;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
s6 = peg$parsevalue();
if (s6 !== peg$FAILED) {
s7 = [];
s8 = peg$parseS();
while (s8 !== peg$FAILED) {
s7.push(s8);
s8 = peg$parseS();
}
if (s7 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s8 = peg$c62;
peg$currPos++;
} else {
s8 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c63); }
}
if (s8 !== peg$FAILED) {
s9 = [];
s10 = peg$parseS();
while (s10 !== peg$FAILED) {
s9.push(s10);
s10 = peg$parseS();
}
if (s9 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c69(s2, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s4 = peg$c18;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
s6 = peg$parsevalue();
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c69(s2, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parsesecfragment() {
var s0, s1, s2;
var key = peg$currPos * 49 + 34,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c16;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseDIGITS();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c70(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedate() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;
var key = peg$currPos * 49 + 35,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
s4 = peg$parseDIGIT_OR_UNDER();
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s6 = peg$c47;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s6 !== peg$FAILED) {
s7 = peg$parseDIGIT_OR_UNDER();
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s9 = peg$c47;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s9 !== peg$FAILED) {
s10 = peg$parseDIGIT_OR_UNDER();
if (s10 !== peg$FAILED) {
s11 = peg$parseDIGIT_OR_UNDER();
if (s11 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c71(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetime() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 36,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c72;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
s6 = peg$parseDIGIT_OR_UNDER();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s7 = peg$c72;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
s9 = peg$parseDIGIT_OR_UNDER();
if (s9 !== peg$FAILED) {
s10 = peg$parsesecfragment();
if (s10 === peg$FAILED) {
s10 = peg$c25;
}
if (s10 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c74(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetime_with_offset() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16;
var key = peg$currPos * 49 + 37,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c72;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
s6 = peg$parseDIGIT_OR_UNDER();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s7 = peg$c72;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
s9 = peg$parseDIGIT_OR_UNDER();
if (s9 !== peg$FAILED) {
s10 = peg$parsesecfragment();
if (s10 === peg$FAILED) {
s10 = peg$c25;
}
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s11 = peg$c47;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s11 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s11 = peg$c44;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
}
if (s11 !== peg$FAILED) {
s12 = peg$parseDIGIT_OR_UNDER();
if (s12 !== peg$FAILED) {
s13 = peg$parseDIGIT_OR_UNDER();
if (s13 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s14 = peg$c72;
peg$currPos++;
} else {
s14 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s14 !== peg$FAILED) {
s15 = peg$parseDIGIT_OR_UNDER();
if (s15 !== peg$FAILED) {
s16 = peg$parseDIGIT_OR_UNDER();
if (s16 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c74(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedatetime() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 38,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsedate();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 84) {
s2 = peg$c75;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c76); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetime();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 90) {
s4 = peg$c77;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c78); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c79(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsedate();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 84) {
s2 = peg$c75;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c76); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetime_with_offset();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c80(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseS() {
var s0;
var key = peg$currPos * 49 + 39,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c81.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseNL() {
var s0, s1, s2;
var key = peg$currPos * 49 + 40,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (input.charCodeAt(peg$currPos) === 10) {
s0 = peg$c83;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c84); }
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 13) {
s1 = peg$c85;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c86); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 10) {
s2 = peg$c83;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c84); }
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseNLS() {
var s0;
var key = peg$currPos * 49 + 41,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseNL();
if (s0 === peg$FAILED) {
s0 = peg$parseS();
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseEOF() {
var s0, s1;
var key = peg$currPos * 49 + 42,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
peg$silentFails++;
if (input.length > peg$currPos) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
peg$silentFails--;
if (s1 === peg$FAILED) {
s0 = peg$c5;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseHEX() {
var s0;
var key = peg$currPos * 49 + 43,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c87.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c88); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseDIGIT_OR_UNDER() {
var s0, s1;
var key = peg$currPos * 49 + 44,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c89.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c90); }
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 95) {
s1 = peg$c91;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c93();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseASCII_BASIC() {
var s0;
var key = peg$currPos * 49 + 45,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c94.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseDIGITS() {
var s0, s1, s2;
var key = peg$currPos * 49 + 46,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseDIGIT_OR_UNDER();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c96(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseESCAPED() {
var s0, s1;
var key = peg$currPos * 49 + 47,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c97) {
s1 = peg$c97;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c98); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c99();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c100) {
s1 = peg$c100;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c102();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c103) {
s1 = peg$c103;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c104); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c105();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c106) {
s1 = peg$c106;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c107); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c108();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c109) {
s1 = peg$c109;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c110); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c111();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c112) {
s1 = peg$c112;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c113); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c114();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c115) {
s1 = peg$c115;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c116); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c117();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$parseESCAPED_UNICODE();
}
}
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function peg$parseESCAPED_UNICODE() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 48,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c118) {
s1 = peg$c118;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c119); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseHEX();
if (s3 !== peg$FAILED) {
s4 = peg$parseHEX();
if (s4 !== peg$FAILED) {
s5 = peg$parseHEX();
if (s5 !== peg$FAILED) {
s6 = peg$parseHEX();
if (s6 !== peg$FAILED) {
s7 = peg$parseHEX();
if (s7 !== peg$FAILED) {
s8 = peg$parseHEX();
if (s8 !== peg$FAILED) {
s9 = peg$parseHEX();
if (s9 !== peg$FAILED) {
s10 = peg$parseHEX();
if (s10 !== peg$FAILED) {
s3 = [s3, s4, s5, s6, s7, s8, s9, s10];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c120(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c121) {
s1 = peg$c121;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c122); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseHEX();
if (s3 !== peg$FAILED) {
s4 = peg$parseHEX();
if (s4 !== peg$FAILED) {
s5 = peg$parseHEX();
if (s5 !== peg$FAILED) {
s6 = peg$parseHEX();
if (s6 !== peg$FAILED) {
s3 = [s3, s4, s5, s6];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c120(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
var nodes = [];
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
}
function addNode(node) {
nodes.push(node);
}
function node(type, value, line, column, key) {
var obj = { type: type, value: value, line: line(), column: column() };
if (key) obj.key = key;
return obj;
}
function convertCodePoint(str, line, col) {
var num = parseInt("0x" + str);
if (
!isFinite(num) ||
Math.floor(num) != num ||
num < 0 ||
num > 0x10FFFF ||
(num > 0xD7FF && num < 0xE000)
) {
genError("Invalid Unicode escape code: " + str, line, col);
} else {
return fromCodePoint(num);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
function fromCodePoint() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return result;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
/***/ }),
/***/ 4294:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
module.exports = __nccwpck_require__(4219);
/***/ }),
/***/ 4219:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var net = __nccwpck_require__(1631);
var tls = __nccwpck_require__(4016);
var http = __nccwpck_require__(8605);
var https = __nccwpck_require__(7211);
var events = __nccwpck_require__(8614);
var assert = __nccwpck_require__(2357);
var util = __nccwpck_require__(1669);
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;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function onCloseOrRemove(err) {
self.removeSocket(socket);
socket.removeListener('free', onFree);
socket.removeListener('close', onCloseOrRemove);
socket.removeListener('agentRemove', onCloseOrRemove);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
});
};
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 ' +
Buffer.from(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];
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
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:');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
console.error.apply(console, args);
}
} else {
debug = function() {};
}
exports.debug = debug; // for test
/***/ }),
/***/ 5030:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
function getUserAgent() {
if (typeof navigator === "object" && "userAgent" in navigator) {
return navigator.userAgent;
}
if (typeof process === "object" && "version" in process) {
return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
}
return "<environment undetectable>";
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 1452:
/***/ (function(__unused_webpack_module, exports) {
/**
* web-streams-polyfill v3.1.1
*/
(function (global, factory) {
true ? factory(exports) :
0;
}(this, (function (exports) { 'use strict';
/// <reference lib="es2015.symbol" />
const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
Symbol :
description => `Symbol(${description})`;
/// <reference lib="dom" />
function noop() {
return undefined;
}
function getGlobals() {
if (typeof self !== 'undefined') {
return self;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else if (typeof window !== 'undefined') {
return window;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else if (typeof global !== 'undefined') {
return global;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return undefined;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return Function.prototype.apply.call(F, V, args);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function promiseCall(F, V, args) {
try {
return promiseResolvedWith(reflectCall(F, V, args));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
catch (value) {
return promiseRejectedWith(value);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
get length() {
return this._size;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
++this._size;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// No mutations before this point.
--this._size;
this._cursor = newCursor;
if (oldFront !== newFront) {
this._front = newFront;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Permit shifted element to be garbage collected.
elements[oldCursor] = undefined;
return element;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// 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];
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
function ReadableStreamReaderGenericInitialize(reader, stream) {
reader._ownerReadableStream = stream;
stream._reader = reader;
if (stream._state === 'readable') {
defaultReaderClosedPromiseInitialize(reader);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else if (stream._state === 'closed') {
defaultReaderClosedPromiseInitializeAsResolved(reader);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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]]');
/// <reference lib="es2015.core" />
// 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);
};
/// <reference lib="es2015.core" />
// 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.`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
// https://heycam.github.io/webidl/#idl-callback-functions
function assertFunction(x, context) {
if (typeof x !== 'function') {
throw new TypeError(`${context} is not a function.`);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// https://heycam.github.io/webidl/#idl-object
function isObject(x) {
return (typeof x === 'object' && x !== null) || typeof x === 'function';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function assertObject(x, context) {
if (!isObject(x)) {
throw new TypeError(`${context} is not an object.`);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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.`);
}
2021-09-26 15:31:45 -04:00
}
// Abstract operations for the ReadableStream.
2021-12-11 08:00:14 -05:00
function AcquireReadableStreamDefaultReader(stream) {
return new ReadableStreamDefaultReader(stream);
2021-09-26 15:31:45 -04:00
}
// ReadableStream API exposed for controllers.
2021-12-11 08:00:14 -05:00
function ReadableStreamAddReadRequest(stream, readRequest) {
stream._reader._readRequests.push(readRequest);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableStreamFulfillReadRequest(stream, chunk, done) {
2021-09-26 15:31:45 -04:00
const reader = stream._reader;
2021-12-11 08:00:14 -05:00
const readRequest = reader._readRequests.shift();
2021-09-26 15:31:45 -04:00
if (done) {
2021-12-11 08:00:14 -05:00
readRequest._closeSteps();
2021-09-26 15:31:45 -04:00
}
else {
2021-12-11 08:00:14 -05:00
readRequest._chunkSteps(chunk);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function ReadableStreamGetNumReadRequests(stream) {
return stream._reader._readRequests.length;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableStreamHasDefaultReader(stream) {
2021-09-26 15:31:45 -04:00
const reader = stream._reader;
if (reader === undefined) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!IsReadableStreamDefaultReader(reader)) {
2021-09-26 15:31:45 -04:00
return false;
}
return true;
}
/**
2021-12-11 08:00:14 -05:00
* A default reader vended by a {@link ReadableStream}.
2021-09-26 15:31:45 -04:00
*
* @public
*/
2021-12-11 08:00:14 -05:00
class ReadableStreamDefaultReader {
2021-09-26 15:31:45 -04:00
constructor(stream) {
2021-12-11 08:00:14 -05:00
assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
2021-09-26 15:31:45 -04:00
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);
2021-12-11 08:00:14 -05:00
this._readRequests = new SimpleQueue();
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
get closed() {
2021-12-11 08:00:14 -05:00
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
2021-09-26 15:31:45 -04:00
}
return this._closedPromise;
}
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason = undefined) {
2021-12-11 08:00:14 -05:00
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
2021-09-26 15:31:45 -04:00
}
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('cancel'));
}
return ReadableStreamReaderGenericCancel(this, reason);
}
/**
2021-12-11 08:00:14 -05:00
* Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
2021-09-26 15:31:45 -04:00
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
2021-12-11 08:00:14 -05:00
read() {
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('read'));
2021-09-26 15:31:45 -04:00
}
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('read from'));
}
let resolvePromise;
let rejectPromise;
const promise = newPromise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
2021-12-11 08:00:14 -05:00
const readRequest = {
2021-09-26 15:31:45 -04:00
_chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
2021-12-11 08:00:14 -05:00
_closeSteps: () => resolvePromise({ value: undefined, done: true }),
2021-09-26 15:31:45 -04:00
_errorSteps: e => rejectPromise(e)
};
2021-12-11 08:00:14 -05:00
ReadableStreamDefaultReaderRead(this, readRequest);
2021-09-26 15:31:45 -04:00
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
2021-12-11 08:00:14 -05:00
* the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
2021-09-26 15:31:45 -04:00
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock() {
2021-12-11 08:00:14 -05:00
if (!IsReadableStreamDefaultReader(this)) {
throw defaultReaderBrandCheckException('releaseLock');
2021-09-26 15:31:45 -04:00
}
if (this._ownerReadableStream === undefined) {
return;
}
2021-12-11 08:00:14 -05:00
if (this._readRequests.length > 0) {
2021-09-26 15:31:45 -04:00
throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
}
ReadableStreamReaderGenericRelease(this);
}
}
2021-12-11 08:00:14 -05:00
Object.defineProperties(ReadableStreamDefaultReader.prototype, {
2021-09-26 15:31:45 -04:00
cancel: { enumerable: true },
read: { enumerable: true },
releaseLock: { enumerable: true },
closed: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2021-12-11 08:00:14 -05:00
Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamDefaultReader',
2021-09-26 15:31:45 -04:00
configurable: true
});
}
// Abstract operations for the readers.
2021-12-11 08:00:14 -05:00
function IsReadableStreamDefaultReader(x) {
2021-09-26 15:31:45 -04:00
if (!typeIsObject(x)) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return x instanceof ReadableStreamDefaultReader;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableStreamDefaultReaderRead(reader, readRequest) {
2021-09-26 15:31:45 -04:00
const stream = reader._ownerReadableStream;
stream._disturbed = true;
2021-12-11 08:00:14 -05:00
if (stream._state === 'closed') {
readRequest._closeSteps();
}
else if (stream._state === 'errored') {
readRequest._errorSteps(stream._storedError);
2021-09-26 15:31:45 -04:00
}
else {
2021-12-11 08:00:14 -05:00
stream._readableStreamController[PullSteps](readRequest);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// Helper functions for the ReadableStreamDefaultReader.
function defaultReaderBrandCheckException(name) {
return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/// <reference lib="es2018.asynciterable" />
/* eslint-disable @typescript-eslint/no-empty-function */
const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype);
/// <reference lib="es2018.asynciterable" />
class ReadableStreamAsyncIteratorImpl {
constructor(reader, preventCancel) {
this._ongoingPromise = undefined;
this._isFinished = false;
this._reader = reader;
this._preventCancel = preventCancel;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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 });
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
};
if (AsyncIteratorPrototype !== undefined) {
Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the ReadableStream.
function streamAsyncIteratorBrandCheckException(name) {
return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/// <reference lib="es2015.core" />
// 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();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Not implemented correctly
function TransferArrayBuffer(O) {
return O;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Not implemented correctly
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function IsDetachedBuffer(O) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const length = end - begin;
const slice = new ArrayBuffer(length);
CopyDataBlockBytes(slice, 0, buffer, begin, length);
return slice;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function IsNonNegativeNumber(v) {
if (typeof v !== 'number') {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
if (NumberIsNaN(v)) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (v < 0) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* A pull-into request in a {@link ReadableByteStreamController}.
2021-09-26 15:31:45 -04:00
*
* @public
*/
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return this._view;
}
respond(bytesWritten) {
if (!IsReadableStreamBYOBRequest(this)) {
throw byobRequestBrandCheckException('respond');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
assertRequiredArgument(bytesWritten, 1, 'respond');
bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
if (this._associatedReadableByteStreamController === undefined) {
throw new TypeError('This BYOB request has been invalidated');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* Returns the current BYOB pull request, or `null` if there isn't one.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get byobRequest() {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('byobRequest');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return ReadableByteStreamControllerGetBYOBRequest(this);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get desiredSize() {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('desiredSize');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return ReadableByteStreamControllerGetDesiredSize(this);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
close() {
2021-12-11 08:00:14 -05:00
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('close');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (this._closeRequested) {
throw new TypeError('The stream has already been closed; do not close it again!');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
error(e = undefined) {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('error');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
Object.defineProperties(ReadableByteStreamController.prototype, {
2021-09-26 15:31:45 -04:00
close: { enumerable: true },
2021-12-11 08:00:14 -05:00
enqueue: { enumerable: true },
error: { enumerable: true },
byobRequest: { enumerable: true },
desiredSize: { enumerable: true }
2021-09-26 15:31:45 -04:00
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2021-12-11 08:00:14 -05:00
Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableByteStreamController',
2021-09-26 15:31:45 -04:00
configurable: true
});
}
2021-12-11 08:00:14 -05:00
// Abstract operations for the ReadableByteStreamController.
function IsReadableByteStreamController(x) {
2021-09-26 15:31:45 -04:00
if (!typeIsObject(x)) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return x instanceof ReadableByteStreamController;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function IsReadableStreamBYOBRequest(x) {
if (!typeIsObject(x)) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return x instanceof ReadableStreamBYOBRequest;
}
function ReadableByteStreamControllerCallPullIfNeeded(controller) {
const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
if (!shouldPull) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (controller._pulling) {
controller._pullAgain = true;
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerClearPendingPullIntos(controller) {
ReadableByteStreamControllerInvalidateBYOBRequest(controller);
controller._pendingPullIntos = new SimpleQueue();
}
function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
let done = false;
if (stream._state === 'closed') {
done = true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
if (pullIntoDescriptor.readerType === 'default') {
ReadableStreamFulfillReadRequest(stream, filledView, done);
}
else {
ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
const bytesFilled = pullIntoDescriptor.bytesFilled;
const elementSize = pullIntoDescriptor.elementSize;
return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
controller._queue.push({ buffer, byteOffset, byteLength });
controller._queueTotalSize += byteLength;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return ready;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
pullIntoDescriptor.bytesFilled += size;
}
function ReadableByteStreamControllerHandleQueueDrain(controller) {
if (controller._queueTotalSize === 0 && controller._closeRequested) {
ReadableByteStreamControllerClearAlgorithms(controller);
ReadableStreamClose(controller._controlledReadableByteStream);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
ReadableByteStreamControllerCallPullIfNeeded(controller);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
if (controller._byobRequest === null) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
controller._byobRequest._associatedReadableByteStreamController = undefined;
controller._byobRequest._view = null;
controller._byobRequest = null;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
}
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
const stream = controller._controlledReadableByteStream;
let elementSize = 1;
if (view.constructor !== DataView) {
elementSize = view.constructor.BYTES_PER_ELEMENT;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
const stream = controller._controlledReadableByteStream;
if (ReadableStreamHasBYOBReader(stream)) {
while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
}
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableByteStreamControllerShiftPendingPullInto(controller) {
const descriptor = controller._pendingPullIntos.shift();
return descriptor;
}
function ReadableByteStreamControllerShouldCallPull(controller) {
const stream = controller._controlledReadableByteStream;
if (stream._state !== 'readable') {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
ReadableByteStreamControllerClearAlgorithms(controller);
ReadableStreamClose(stream);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
else {
2021-12-11 08:00:14 -05:00
const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
ReadableStreamFulfillReadRequest(stream, transferredView, false);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
function ReadableByteStreamControllerError(controller, e) {
const stream = controller._controlledReadableByteStream;
if (stream._state !== 'readable') {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
else {
if (bytesWritten === 0) {
throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
throw new RangeError('bytesWritten out of range');
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
else {
if (view.byteLength === 0) {
throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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');
}
firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (underlyingByteSource.pull !== undefined) {
pullAlgorithm = () => underlyingByteSource.pull(controller);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function SetUpReadableStreamBYOBRequest(request, controller, view) {
request._associatedReadableByteStreamController = controller;
request._view = view;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the ReadableStreamBYOBRequest.
function byobRequestBrandCheckException(name) {
return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the ReadableByteStreamController.
function byteStreamControllerBrandCheckException(name) {
return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
2021-09-26 15:31:45 -04:00
}
else {
2021-12-11 08:00:14 -05:00
readIntoRequest._chunkSteps(chunk);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function ReadableStreamGetNumReadIntoRequests(stream) {
return stream._reader._readIntoRequests.length;
}
function ReadableStreamHasBYOBReader(stream) {
const reader = stream._reader;
if (reader === undefined) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (!IsReadableStreamBYOBReader(reader)) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return true;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* A BYOB reader vended by a {@link ReadableStream}.
2021-09-26 15:31:45 -04:00
*
* @public
*/
2021-12-11 08:00:14 -05:00
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();
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get closed() {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('closed'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return this._closedPromise;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
cancel(reason = undefined) {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('cancel'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return ReadableStreamReaderGenericCancel(this, reason);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* Attempts to reads bytes into view, and returns a promise resolved with the result.
2021-09-26 15:31:45 -04:00
*
2021-12-11 08:00:14 -05:00
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
read(view) {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('read'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (!ArrayBuffer.isView(view)) {
return promiseRejectedWith(new TypeError('view must be an array buffer view'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* 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);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
Object.defineProperties(ReadableStreamBYOBReader.prototype, {
cancel: { enumerable: true },
read: { enumerable: true },
releaseLock: { enumerable: true },
closed: { enumerable: true }
2021-09-26 15:31:45 -04:00
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2021-12-11 08:00:14 -05:00
Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamBYOBReader',
2021-09-26 15:31:45 -04:00
configurable: true
});
}
2021-12-11 08:00:14 -05:00
// Abstract operations for the readers.
function IsReadableStreamBYOBReader(x) {
2021-09-26 15:31:45 -04:00
if (!typeIsObject(x)) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return x instanceof ReadableStreamBYOBReader;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
const stream = reader._ownerReadableStream;
stream._disturbed = true;
if (stream._state === 'errored') {
readIntoRequest._errorSteps(stream._storedError);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
// Helper functions for the ReadableStreamBYOBReader.
function byobReaderBrandCheckException(name) {
return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ExtractHighWaterMark(strategy, defaultHWM) {
const { highWaterMark } = strategy;
if (highWaterMark === undefined) {
return defaultHWM;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
throw new RangeError('Invalid highWaterMark');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return highWaterMark;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ExtractSizeAlgorithm(strategy) {
const { size } = strategy;
if (!size) {
return () => 1;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return size;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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`)
};
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function convertQueuingStrategySize(fn, context) {
assertFunction(fn, context);
return chunk => convertUnrestrictedDouble(fn(chunk));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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
};
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function convertUnderlyingSinkAbortCallback(fn, original, context) {
assertFunction(fn, context);
return (reason) => promiseCall(fn, original, [reason]);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function convertUnderlyingSinkCloseCallback(fn, original, context) {
assertFunction(fn, context);
return () => promiseCall(fn, original, []);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function convertUnderlyingSinkStartCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => reflectCall(fn, original, [controller]);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function convertUnderlyingSinkWriteCallback(fn, original, context) {
assertFunction(fn, context);
return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function assertWritableStream(x, context) {
if (!IsWritableStream(x)) {
throw new TypeError(`${context} is not a WritableStream.`);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function isAbortSignal(value) {
if (typeof value !== 'object' || value === null) {
2021-09-26 15:31:45 -04:00
return false;
}
try {
2021-12-11 08:00:14 -05:00
return typeof value.aborted === 'boolean';
2021-09-26 15:31:45 -04:00
}
catch (_a) {
2021-12-11 08:00:14 -05:00
// AbortSignal.prototype.aborted throws if its brand check fails
2021-09-26 15:31:45 -04:00
return false;
}
}
2021-12-11 08:00:14 -05:00
const supportsAbortController = typeof AbortController === 'function';
/**
* Construct a new AbortController, if supported by the platform.
*
* @internal
*/
function createAbortController() {
if (supportsAbortController) {
return new AbortController();
}
return undefined;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* A writable stream represents a destination for data, into which you can write.
2021-09-26 15:31:45 -04:00
*
* @public
*/
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* Returns whether or not the writable stream is locked to a writer.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get locked() {
if (!IsWritableStream(this)) {
throw streamBrandCheckException$2('locked');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return IsWritableStreamLocked(this);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
abort(reason = undefined) {
if (!IsWritableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$2('abort'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (IsWritableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return WritableStreamAbort(this, reason);
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
close() {
if (!IsWritableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$2('close'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (IsWritableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (WritableStreamCloseQueuedOrInFlight(this)) {
return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
Object.defineProperties(WritableStream.prototype, {
abort: { enumerable: true },
2021-09-26 15:31:45 -04:00
close: { enumerable: true },
2021-12-11 08:00:14 -05:00
getWriter: { enumerable: true },
locked: { enumerable: true }
2021-09-26 15:31:45 -04:00
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2021-12-11 08:00:14 -05:00
Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
value: 'WritableStream',
2021-09-26 15:31:45 -04:00
configurable: true
});
}
2021-12-11 08:00:14 -05:00
// 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) {
2021-09-26 15:31:45 -04:00
if (!typeIsObject(x)) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return x instanceof WritableStream;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function IsWritableStreamLocked(stream) {
if (stream._writer === undefined) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamAbort(stream, reason) {
var _a;
if (stream._state === 'closed' || stream._state === 'errored') {
return promiseResolvedWith(undefined);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (stream._pendingAbortRequest !== undefined) {
return stream._pendingAbortRequest._promise;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
let wasAlreadyErroring = false;
if (state === 'erroring') {
wasAlreadyErroring = true;
// reason will not be used, so don't keep a reference to it.
reason = undefined;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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`));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
WritableStreamDefaultControllerClose(stream._writableStreamController);
return promise;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
2021-09-26 15:31:45 -04:00
return;
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
WritableStreamFinishErroring(stream);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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);
});
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
stream._state = 'closed';
const writer = stream._writer;
if (writer !== undefined) {
defaultWriterClosedPromiseResolve(writer);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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) {
2021-09-26 15:31:45 -04:00
return false;
}
return true;
}
2021-12-11 08:00:14 -05:00
function WritableStreamHasOperationMarkedInFlight(stream) {
if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return true;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamMarkCloseRequestInFlight(stream) {
stream._inFlightCloseRequest = stream._closeRequest;
stream._closeRequest = undefined;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamMarkFirstWriteRequestInFlight(stream) {
stream._inFlightWriteRequest = stream._writeRequests.shift();
}
function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
if (stream._closeRequest !== undefined) {
stream._closeRequest._reject(stream._storedError);
stream._closeRequest = undefined;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const writer = stream._writer;
if (writer !== undefined) {
defaultWriterClosedPromiseReject(writer, stream._storedError);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function WritableStreamUpdateBackpressure(stream, backpressure) {
const writer = stream._writer;
if (writer !== undefined && backpressure !== stream._backpressure) {
if (backpressure) {
defaultWriterReadyPromiseReset(writer);
}
else {
defaultWriterReadyPromiseResolve(writer);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
stream._backpressure = backpressure;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* 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');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
this._ownerWritableStream = stream;
stream._writer = this;
const state = stream._state;
if (state === 'writable') {
if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
defaultWriterReadyPromiseInitialize(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
defaultWriterReadyPromiseInitializeAsResolved(this);
}
defaultWriterClosedPromiseInitialize(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else if (state === 'erroring') {
defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
defaultWriterClosedPromiseInitialize(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else if (state === 'closed') {
defaultWriterReadyPromiseInitializeAsResolved(this);
defaultWriterClosedPromiseInitializeAsResolved(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
else {
const storedError = stream._storedError;
defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the writers lock is released before the stream finishes closing.
*/
get closed() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return this._closedPromise;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* Returns the desired size to fill the streams 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 writers lock is released.
*/
get desiredSize() {
if (!IsWritableStreamDefaultWriter(this)) {
throw defaultWriterBrandCheckException('desiredSize');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (this._ownerWritableStream === undefined) {
throw defaultWriterLockException('desiredSize');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return WritableStreamDefaultWriterGetDesiredSize(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* Returns a promise that will be fulfilled when the desired size to fill the streams 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 writers lock is released, the returned promise will become
* rejected.
*/
get ready() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (this._ownerWritableStream === undefined) {
return promiseRejectedWith(defaultWriterLockException('abort'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return WritableStreamDefaultWriterAbort(this, reason);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
*/
close() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('close'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const stream = this._ownerWritableStream;
if (stream === undefined) {
return promiseRejectedWith(defaultWriterLockException('close'));
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (WritableStreamCloseQueuedOrInFlight(stream)) {
return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
}
return WritableStreamDefaultWriterClose(this);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* Releases the writers 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).
* Its 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);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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
});
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultWriterClose(writer) {
const stream = writer._ownerWritableStream;
return WritableStreamClose(stream);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
const stream = writer._ownerWritableStream;
const state = stream._state;
if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
return promiseResolvedWith(undefined);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (state === 'errored') {
return promiseRejectedWith(stream._storedError);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return WritableStreamDefaultWriterClose(writer);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
if (writer._closedPromiseState === 'pending') {
defaultWriterClosedPromiseReject(writer, error);
}
else {
defaultWriterClosedPromiseResetToRejected(writer, error);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
if (writer._readyPromiseState === 'pending') {
defaultWriterReadyPromiseReject(writer, error);
}
else {
defaultWriterReadyPromiseResetToRejected(writer, error);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultWriterGetDesiredSize(writer) {
const stream = writer._ownerWritableStream;
const state = stream._state;
if (state === 'errored' || state === 'erroring') {
return null;
}
if (state === 'closed') {
return 0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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 = {};
2021-09-26 15:31:45 -04:00
/**
2021-12-11 08:00:14 -05:00
* Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
2021-09-26 15:31:45 -04:00
*
* @public
*/
2021-12-11 08:00:14 -05:00
class WritableStreamDefaultController {
constructor() {
throw new TypeError('Illegal constructor');
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get abortReason() {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('abortReason');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return this._abortReason;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
get signal() {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('signal');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
return this._abortController.signal;
2021-09-26 15:31:45 -04:00
}
/**
2021-12-11 08:00:14 -05:00
* Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
2021-09-26 15:31:45 -04:00
*
2021-12-11 08:00:14 -05:00
* 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.
2021-09-26 15:31:45 -04:00
*/
2021-12-11 08:00:14 -05:00
error(e = undefined) {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('error');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
WritableStreamDefaultControllerError(this, e);
}
/** @internal */
[AbortSteps](reason) {
const result = this._abortAlgorithm(reason);
WritableStreamDefaultControllerClearAlgorithms(this);
return result;
}
/** @internal */
[ErrorSteps]() {
ResetQueue(this);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
Object.defineProperties(WritableStreamDefaultController.prototype, {
error: { enumerable: true }
2021-09-26 15:31:45 -04:00
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2021-12-11 08:00:14 -05:00
Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
value: 'WritableStreamDefaultController',
2021-09-26 15:31:45 -04:00
configurable: true
});
}
2021-12-11 08:00:14 -05:00
// Abstract operations implementing interface required by the WritableStream.
function IsWritableStreamDefaultController(x) {
2021-09-26 15:31:45 -04:00
if (!typeIsObject(x)) {
return false;
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
return x instanceof WritableStreamDefaultController;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
});
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (underlyingSink.write !== undefined) {
writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (underlyingSink.close !== undefined) {
closeAlgorithm = () => underlyingSink.close();
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (underlyingSink.abort !== undefined) {
abortAlgorithm = reason => underlyingSink.abort(reason);
}
SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
catch (chunkSizeE) {
WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
return 1;
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultControllerGetDesiredSize(controller) {
return controller._strategyHWM - controller._queueTotalSize;
}
function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
try {
EnqueueValueWithSize(controller, chunk, chunkSize);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
catch (enqueueE) {
WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const stream = controller._controlledWritableStream;
if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
WritableStreamUpdateBackpressure(stream, backpressure);
}
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Abstract operations for the WritableStreamDefaultController.
function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
const stream = controller._controlledWritableStream;
if (!controller._started) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (stream._inFlightWriteRequest !== undefined) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const state = stream._state;
if (state === 'erroring') {
WritableStreamFinishErroring(stream);
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (controller._queue.length === 0) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
const value = PeekQueueValue(controller);
if (value === closeSentinel) {
WritableStreamDefaultControllerProcessClose(controller);
}
else {
WritableStreamDefaultControllerProcessWrite(controller, value);
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
if (controller._controlledWritableStream._state === 'writable') {
WritableStreamDefaultControllerError(controller, error);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}, reason => {
if (stream._state === 'writable') {
WritableStreamDefaultControllerClearAlgorithms(controller);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
WritableStreamFinishInFlightWriteWithError(stream, reason);
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
function WritableStreamDefaultControllerGetBackpressure(controller) {
const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
return desiredSize <= 0;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the WritableStream.
function streamBrandCheckException$2(name) {
return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the WritableStreamDefaultController.
function defaultControllerBrandCheckException$2(name) {
return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// Helper functions for the WritableStreamDefaultWriter.
function defaultWriterBrandCheckException(name) {
return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterLockException(name) {
return new TypeError('Cannot ' + name + ' a stream using a released writer');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterClosedPromiseInitialize(writer) {
writer._closedPromise = newPromise((resolve, reject) => {
writer._closedPromise_resolve = resolve;
writer._closedPromise_reject = reject;
writer._closedPromiseState = 'pending';
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
defaultWriterClosedPromiseInitialize(writer);
defaultWriterClosedPromiseReject(writer, reason);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterClosedPromiseInitializeAsResolved(writer) {
defaultWriterClosedPromiseInitialize(writer);
defaultWriterClosedPromiseResolve(writer);
}
function defaultWriterClosedPromiseReject(writer, reason) {
if (writer._closedPromise_reject === undefined) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
setPromiseIsHandledToTrue(writer._closedPromise);
writer._closedPromise_reject(reason);
writer._closedPromise_resolve = undefined;
writer._closedPromise_reject = undefined;
writer._closedPromiseState = 'rejected';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterClosedPromiseResetToRejected(writer, reason) {
defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterClosedPromiseResolve(writer) {
if (writer._closedPromise_resolve === undefined) {
return;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
writer._closedPromise_resolve(undefined);
writer._closedPromise_resolve = undefined;
writer._closedPromise_reject = undefined;
writer._closedPromiseState = 'resolved';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterReadyPromiseInitialize(writer) {
writer._readyPromise = newPromise((resolve, reject) => {
writer._readyPromise_resolve = resolve;
writer._readyPromise_reject = reject;
2021-09-26 15:31:45 -04:00
});
2021-12-11 08:00:14 -05:00
writer._readyPromiseState = 'pending';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
setPromiseIsHandledToTrue(writer._readyPromise);
writer._readyPromise_reject(reason);
writer._readyPromise_resolve = undefined;
writer._readyPromise_reject = undefined;
writer._readyPromiseState = 'rejected';
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function defaultWriterReadyPromiseReset(writer) {
defaultWriterReadyPromiseInitialize(writer);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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';
}
/// <reference lib="dom" />
const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
/// <reference types="node" />
function isDOMExceptionConstructor(ctor) {
if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2021-09-26 15:31:45 -04:00
return false;
}
2021-12-11 08:00:14 -05:00
try {
new ctor();
return true;
}
catch (_a) {
2021-09-26 15:31:45 -04:00
return false;
}
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
};
2021-12-11 08:00:14 -05:00
ctor.prototype = Object.create(Error.prototype);
Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
return ctor;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
}
}
});
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
*
* @public
*/
class ReadableStreamDefaultController {
constructor() {
throw new TypeError('Illegal constructor');
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* 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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
/**
* 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);
}
2021-09-26 15:31:45 -04:00
}
}
2021-12-11 08:00:14 -05:00
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
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
// Abstract operations for the ReadableStreamDefaultController.
function IsReadableStreamDefaultController(x) {
if (!typeIsObject(x)) {
return false;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
return false;
}
return x instanceof ReadableStreamDefaultController;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
}, e => {
ReadableStreamDefaultControllerError(controller, e);
2021-09-26 15:31:45 -04:00
});
}
2021-12-11 08:00:14 -05:00
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;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
function ReadableStreamDefaultControllerClearAlgorithms(controller) {
controller._pullAlgorithm = undefined;
controller._cancelAlgorithm = undefined;
controller._strategySizeAlgorithm = undefined;
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
// 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);
}
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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`);
2021-09-26 15:31:45 -04:00
}
2021-12-11 08:00:14 -05:00
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 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) {
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(() => {
reading = 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);
}
});
},
_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 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(() => {
reading = 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);
}
});
},
_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(() => {
reading = 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);
}
});
},
_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) {
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) {
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`);
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
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;
};
Object.defineProperty(byteLengthSizeFunction, 'name', {
value: 'size',
configurable: true
});
/**
* 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;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
// The size function must not have a prototype property nor be a constructor
const countSizeFunction = () => {
return 1;
};
Object.defineProperty(countSizeFunction, 'name', {
value: 'size',
configurable: true
});
/**
* 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;
}
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
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 sides 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
/***/ }),
/***/ 2940:
/***/ ((module) => {
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
/***/ }),
2022-01-12 10:27:38 -05:00
/***/ 9500:
2021-12-11 08:00:14 -05:00
/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
2021-09-26 15:31:45 -04:00
"use strict";
// ESM COMPAT FLAG
__nccwpck_require__.r(__webpack_exports__);
2021-12-11 08:00:14 -05:00
// EXTERNAL MODULE: ./node_modules/fast-glob/out/index.js
var out = __nccwpck_require__(3664);
var out_default = /*#__PURE__*/__nccwpck_require__.n(out);
2021-09-26 15:31:45 -04:00
// EXTERNAL MODULE: external "fs"
var external_fs_ = __nccwpck_require__(5747);
var external_fs_default = /*#__PURE__*/__nccwpck_require__.n(external_fs_);
// EXTERNAL MODULE: external "path"
var external_path_ = __nccwpck_require__(5622);
var external_path_default = /*#__PURE__*/__nccwpck_require__.n(external_path_);
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/utils/file.ts
2021-09-26 15:31:45 -04:00
var __awaiter = (undefined && undefined.__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());
});
};
class File {
constructor(filePath) {
this.name = external_path_default().basename(filePath);
this.path = filePath;
Object.freeze(this);
}
getBuffer() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
external_fs_default().readFile(this.path, (error, data) => {
if (error) {
reject(error);
}
else {
resolve(data);
}
});
});
});
}
equals(file) {
return file instanceof File && file.path === this.path;
}
}
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/utils/file-utils.ts
var file_utils_awaiter = (undefined && undefined.__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());
});
};
2021-10-01 09:38:36 -04:00
const gradleOutputSelector = {
primary: "build/libs/!(*-@(dev|sources)).jar",
secondary: "build/libs/*-@(dev|sources).jar"
};
function getRequiredFiles(files) {
2021-12-11 08:00:14 -05:00
return file_utils_awaiter(this, void 0, void 0, function* () {
2021-10-01 09:38:36 -04:00
const foundFiles = yield getFiles(files);
if (foundFiles && foundFiles.length) {
return foundFiles;
}
throw new Error(`Specified files ('${typeof files === "string" ? files : [files.primary, files.secondary].filter(x => x).join(", ")}') were not found`);
});
}
2021-09-26 15:31:45 -04:00
function getFiles(files) {
2021-12-11 08:00:14 -05:00
return file_utils_awaiter(this, void 0, void 0, function* () {
2021-09-26 15:31:45 -04:00
if (!files || typeof files !== "string" && !files.primary && !files.secondary) {
return [];
}
if (typeof files === "string") {
return (yield out_default()(files)).map(x => new File(x));
}
let results = [];
if (files.primary) {
results = (yield out_default()(files.primary)).map(x => new File(x));
}
if (files.secondary) {
results = results.concat((yield out_default()(files.secondary)).map(x => new File(x)));
}
return results.filter((x, i, self) => self.findIndex(y => x.equals(y)) === i);
});
}
2021-10-01 09:38:36 -04:00
;// CONCATENATED MODULE: ./src/publishing/publisher-target.ts
var PublisherTarget;
(function (PublisherTarget) {
PublisherTarget[PublisherTarget["GitHub"] = 0] = "GitHub";
PublisherTarget[PublisherTarget["Modrinth"] = 1] = "Modrinth";
PublisherTarget[PublisherTarget["CurseForge"] = 2] = "CurseForge";
})(PublisherTarget || (PublisherTarget = {}));
(function (PublisherTarget) {
function getValues() {
return Object.values(PublisherTarget).filter(x => !isNaN(+x));
}
PublisherTarget.getValues = getValues;
function toString(target) {
return PublisherTarget[target] || target.toString();
}
PublisherTarget.toString = toString;
})(PublisherTarget || (PublisherTarget = {}));
/* harmony default export */ const publisher_target = (PublisherTarget);
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
var core = __nccwpck_require__(2186);
;// CONCATENATED MODULE: external "console"
const external_console_namespaceObject = require("console");
;// CONCATENATED MODULE: ./src/utils/logger-utils.ts
function getDefaultLogger() {
return {
fatal: core.setFailed,
error: core.warning,
warn: core.warning,
info: core.info,
debug: core.debug
};
}
function getConsoleLogger() {
return {
fatal: console.error,
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug
};
}
function getEmptyLogger() {
return {
fatal: () => { },
error: () => { },
warn: () => { },
info: () => { },
debug: () => { }
};
}
;// CONCATENATED MODULE: ./src/publishing/publisher.ts
class Publisher {
constructor(logger) {
this.logger = logger || getEmptyLogger();
}
validateOptions(options) {
if (!options || typeof options !== "object") {
throw new Error(`Expected options to be an object, got ${options ? typeof options : options}`);
}
}
}
// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js
var github = __nccwpck_require__(5438);
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/publishing/github/github-publisher.ts
2021-09-26 15:31:45 -04:00
var github_publisher_awaiter = (undefined && undefined.__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());
});
};
class GitHubPublisher extends Publisher {
get target() {
return publisher_target.GitHub;
}
2021-10-01 09:38:36 -04:00
publish(files, options) {
2021-09-26 15:31:45 -04:00
var _a;
return github_publisher_awaiter(this, void 0, void 0, function* () {
2021-10-01 09:38:36 -04:00
this.validateOptions(options);
2021-09-26 15:31:45 -04:00
let releaseId = 0;
const repo = github.context.repo;
2021-10-01 09:38:36 -04:00
const octokit = github.getOctokit(options.token);
if (options.tag) {
const response = yield octokit.rest.repos.getReleaseByTag(Object.assign(Object.assign({}, repo), { tag: options.tag }));
2021-09-26 15:31:45 -04:00
if (response.status >= 200 && response.status < 300) {
releaseId = response.data.id;
}
}
else {
releaseId = (_a = github.context.payload.release) === null || _a === void 0 ? void 0 : _a.id;
}
if (!releaseId) {
2021-10-01 09:38:36 -04:00
throw new Error(`Couldn't find release #${options.tag || releaseId}`);
2021-09-26 15:31:45 -04:00
}
const existingAssets = (yield octokit.rest.repos.listReleaseAssets(Object.assign(Object.assign({}, repo), { release_id: releaseId }))).data;
for (const file of files) {
const existingAsset = existingAssets.find(x => x.name === file.name || x.name === file.path);
if (existingAsset) {
yield octokit.rest.repos.deleteReleaseAsset(Object.assign(Object.assign({}, repo), { asset_id: existingAsset.id }));
}
yield octokit.rest.repos.uploadReleaseAsset({
owner: repo.owner,
repo: repo.repo,
release_id: releaseId,
name: file.name,
data: yield file.getBuffer()
});
}
});
}
}
// EXTERNAL MODULE: external "util"
var external_util_ = __nccwpck_require__(1669);
;// CONCATENATED MODULE: ./node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs
/**
* @license
* web-streams-polyfill v4.0.0-beta.1
* Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors.
* This code is released under the MIT license.
* SPDX-License-Identifier: MIT
*/
const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t,n=Promise,a=Promise.prototype.then,i=Promise.resolve.bind(n),l=Promise.reject.bind(n);function s(e){return new n(e)}function u(e){return i(e)}function c(e){return l(e)}function d(e,t,r){return a.call(e,t,r)}function f(e,t,r){d(d(e,t,r),void 0,o)}function b(e,t){f(e,t)}function _(e,t){f(e,void 0,t)}function h(e,t,r){return d(e,t,r)}function m(e){d(e,void 0,o)}let p=e=>{if("function"==typeof queueMicrotask)p=queueMicrotask;else{const e=u(void 0);p=t=>d(e,t)}return p(e)};function y(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function g(e,t,r){try{return u(y(e,t,r))}catch(e){return c(e)}}class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function v(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?C(e):"closed"===t._state?function(e){C(e),E(e)}(e):q(e,t._storedError)}function w(e,t){return cr(e._ownerReadableStream,t)}function R(e){"readable"===e._ownerReadableStream._state?P(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){q(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function T(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function C(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function q(e,t){C(e),P(e,t)}function P(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function E(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const W=e("[[AbortSteps]]"),O=e("[[ErrorSteps]]"),k=e("[[CancelSteps]]"),B=e("[[PullSteps]]"),j=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},A=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function z(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function F(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function I(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function L(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function D(e){return Number(e)}function M(e){return 0===e?0:e}function Q(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=M(o),!j(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return M(A(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return j(o)&&0!==o?o:0}function Y(e,t){if(!sr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function x(e){return new ReadableStreamDefaultReader(e)}function N(e,t){e._reader._readRequests.push(t)}function H(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function V(e){return e._reader
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js
const isFunction = (value) => (typeof value === "function");
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/blobHelpers.js
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
const CHUNK_SIZE = 65536;
async function* clonePart(part) {
const end = part.byteOffset + part.byteLength;
let position = part.byteOffset;
while (position !== end) {
const size = Math.min(end - position, CHUNK_SIZE);
const chunk = part.buffer.slice(position, position + size);
position += chunk.byteLength;
yield new Uint8Array(chunk);
}
}
async function* consumeNodeBlob(blob) {
let position = 0;
while (position !== blob.size) {
const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
yield new Uint8Array(buffer);
}
}
async function* consumeBlobParts(parts, clone = false) {
for (const part of parts) {
if (ArrayBuffer.isView(part)) {
if (clone) {
yield* clonePart(part);
}
else {
yield part;
}
}
else if (isFunction(part.stream)) {
yield* part.stream();
}
else {
yield* consumeNodeBlob(part);
}
}
}
function* sliceBlob(blobParts, blobSize, start = 0, end) {
end !== null && end !== void 0 ? end : (end = blobSize);
let relativeStart = start < 0
? Math.max(blobSize + start, 0)
: Math.min(start, blobSize);
let relativeEnd = end < 0
? Math.max(blobSize + end, 0)
: Math.min(end, blobSize);
const span = Math.max(relativeEnd - relativeStart, 0);
let added = 0;
for (const part of blobParts) {
if (added >= span) {
break;
}
const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
if (relativeStart && partSize <= relativeStart) {
relativeStart -= partSize;
relativeEnd -= partSize;
}
else {
let chunk;
if (ArrayBuffer.isView(part)) {
chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.byteLength;
}
else {
chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.size;
}
relativeEnd -= partSize;
relativeStart = 0;
yield chunk;
}
}
}
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/Blob.js
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _Blob_parts, _Blob_type, _Blob_size;
class Blob {
constructor(blobParts = [], options = {}) {
_Blob_parts.set(this, []);
_Blob_type.set(this, "");
_Blob_size.set(this, 0);
options !== null && options !== void 0 ? options : (options = {});
if (typeof blobParts !== "object" || blobParts === null) {
throw new TypeError("Failed to construct 'Blob': "
+ "The provided value cannot be converted to a sequence.");
}
if (!isFunction(blobParts[Symbol.iterator])) {
throw new TypeError("Failed to construct 'Blob': "
+ "The object must have a callable @@iterator property.");
}
if (typeof options !== "object" && !isFunction(options)) {
throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
}
const encoder = new TextEncoder();
for (const raw of blobParts) {
let part;
if (ArrayBuffer.isView(raw)) {
part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));
}
else if (raw instanceof ArrayBuffer) {
part = new Uint8Array(raw.slice(0));
}
else if (raw instanceof Blob) {
part = raw;
}
else {
part = encoder.encode(String(raw));
}
__classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f");
__classPrivateFieldGet(this, _Blob_parts, "f").push(part);
}
const type = options.type === undefined ? "" : String(options.type);
__classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f");
}
static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) {
return Boolean(value
&& typeof value === "object"
&& isFunction(value.constructor)
&& (isFunction(value.stream)
|| isFunction(value.arrayBuffer))
&& /^(Blob|File)$/.test(value[Symbol.toStringTag]));
}
get type() {
return __classPrivateFieldGet(this, _Blob_type, "f");
}
get size() {
return __classPrivateFieldGet(this, _Blob_size, "f");
}
slice(start, end, contentType) {
return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), {
type: contentType
});
}
async text() {
const decoder = new TextDecoder();
let result = "";
for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
result += decoder.decode(chunk, { stream: true });
}
result += decoder.decode();
return result;
}
async arrayBuffer() {
const view = new Uint8Array(this.size);
let offset = 0;
for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
view.set(chunk, offset);
offset += chunk.length;
}
return view.buffer;
}
stream() {
const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true);
return new ponyfill_ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
2021-10-01 09:38:36 -04:00
return queueMicrotask(() => controller.close());
2021-09-26 15:31:45 -04:00
}
controller.enqueue(value);
2021-10-01 09:38:36 -04:00
},
async cancel() {
await iterator.return();
2021-09-26 15:31:45 -04:00
}
});
}
get [Symbol.toStringTag]() {
return "Blob";
}
}
Object.defineProperties(Blob.prototype, {
type: { enumerable: true },
size: { enumerable: true },
slice: { enumerable: true },
stream: { enumerable: true },
text: { enumerable: true },
arrayBuffer: { enumerable: true }
});
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/File.js
var File_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var File_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _File_name, _File_lastModified;
class File_File extends Blob {
2021-10-01 09:38:36 -04:00
constructor(fileBits, name, options = {}) {
2021-09-26 15:31:45 -04:00
super(fileBits, options);
_File_name.set(this, void 0);
_File_lastModified.set(this, 0);
if (arguments.length < 2) {
throw new TypeError("Failed to construct 'File': 2 arguments required, "
+ `but only ${arguments.length} present.`);
}
File_classPrivateFieldSet(this, _File_name, String(name), "f");
2021-10-01 09:38:36 -04:00
const lastModified = options.lastModified === undefined
? Date.now()
: Number(options.lastModified);
2021-09-26 15:31:45 -04:00
if (!Number.isNaN(lastModified)) {
File_classPrivateFieldSet(this, _File_lastModified, lastModified, "f");
}
}
get name() {
return File_classPrivateFieldGet(this, _File_name, "f");
}
get lastModified() {
return File_classPrivateFieldGet(this, _File_lastModified, "f");
}
get [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.toStringTag)]() {
return "File";
}
}
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFile.js
const isFile = (value) => value instanceof File_File;
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/normalizeFilename.js
const normalizeFilename = (name = "blob") => String(name);
/* harmony default export */ const esm_normalizeFilename = (normalizeFilename);
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/FormData.js
var FormData_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _FormData_instances, _FormData_entries, _FormData_setEntry;
class FormData {
constructor(entries) {
_FormData_instances.add(this);
_FormData_entries.set(this, new Map());
if (entries) {
entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName));
}
}
append(name, value, fileName) {
return FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
fileName,
append: true,
argsLength: arguments.length
});
}
set(name, value, fileName) {
return FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
fileName,
append: false,
argsLength: arguments.length
});
}
get(name) {
const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return null;
}
return field[0];
}
getAll(name) {
const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return [];
}
return field.slice();
}
has(name) {
return FormData_classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
}
delete(name) {
return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
}
*keys() {
for (const key of FormData_classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
yield key;
}
}
*entries() {
for (const name of this.keys()) {
const values = this.getAll(name);
for (const value of values) {
yield [name, value];
}
}
}
*values() {
for (const [, value] of this) {
yield value;
}
}
[(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), _FormData_setEntry = function _FormData_setEntry({ name, value, append, fileName, argsLength }) {
const methodName = append ? "append" : "set";
name = String(name);
if (argsLength < 2) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ `2 arguments required, but only ${argsLength} present.`);
}
let normalizedValue;
if (isFile(value)) {
fileName = esm_normalizeFilename(fileName === undefined ? value.name : fileName);
normalizedValue = new File_File([value], fileName, {
type: value.type,
lastModified: value.lastModified
});
}
else if (fileName) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ "parameter 2 is not of type 'Blob'.");
}
else {
normalizedValue = String(value);
}
const values = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(name);
if (!values) {
return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [normalizedValue]);
}
if (!append) {
return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [normalizedValue]);
}
values.push(normalizedValue);
}, Symbol.iterator)]() {
return this.entries();
}
2021-10-01 09:38:36 -04:00
forEach(callback, thisArg) {
2021-09-26 15:31:45 -04:00
for (const [name, value] of this) {
2021-10-01 09:38:36 -04:00
callback.call(thisArg, value, name, this);
2021-09-26 15:31:45 -04:00
}
}
get [Symbol.toStringTag]() {
return "FormData";
}
[external_util_.inspect.custom]() {
return this[Symbol.toStringTag];
}
}
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/index.js
// EXTERNAL MODULE: ./node_modules/node-domexception/index.js
var node_domexception = __nccwpck_require__(7760);
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isPlainObject.js
const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase());
function isPlainObject(value) {
if (getType(value) !== "object") {
return false;
}
const pp = Object.getPrototypeOf(value);
if (pp === null || pp === undefined) {
return true;
}
const Ctor = pp.constructor && pp.constructor.toString();
return Ctor === Object.toString();
}
/* harmony default export */ const esm_isPlainObject = (isPlainObject);
;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/fileFromPath.js
var fileFromPath_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var fileFromPath_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _FileFromPath_path, _FileFromPath_start;
const MESSAGE = "The requested file could not be read, "
+ "typically due to permission problems that have occurred after a reference "
+ "to a file was acquired.";
class FileFromPath {
constructor(input) {
_FileFromPath_path.set(this, void 0);
_FileFromPath_start.set(this, void 0);
fileFromPath_classPrivateFieldSet(this, _FileFromPath_path, input.path, "f");
fileFromPath_classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f");
this.name = (0,external_path_.basename)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"));
this.size = input.size;
this.lastModified = input.lastModified;
}
slice(start, end) {
return new FileFromPath({
path: fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"),
lastModified: this.lastModified,
size: end - start,
start
});
}
async *stream() {
const { mtimeMs } = await external_fs_.promises.stat(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"));
if (mtimeMs > this.lastModified) {
throw new node_domexception(MESSAGE, "NotReadableError");
}
if (this.size) {
yield* (0,external_fs_.createReadStream)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"), {
start: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f"),
end: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1
});
}
}
get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() {
return "File";
}
}
function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) {
let filename;
if (esm_isPlainObject(filenameOrOptions)) {
[options, filename] = [filenameOrOptions, undefined];
}
else {
filename = filenameOrOptions;
}
const file = new FileFromPath({ path, size, lastModified: mtimeMs });
if (!filename) {
filename = file.name;
}
return new File_File([file], filename, {
...options, lastModified: file.lastModified
});
}
function fileFromPathSync(path, filenameOrOptions, options = {}) {
return createFileFromPath(path, statSync(path), filenameOrOptions, options);
}
async function fileFromPath(path, filenameOrOptions, options) {
const stats = await external_fs_.promises.stat(path);
return createFileFromPath(path, stats, filenameOrOptions, options);
}
// EXTERNAL MODULE: external "http"
var external_http_ = __nccwpck_require__(8605);
// EXTERNAL MODULE: external "https"
var external_https_ = __nccwpck_require__(7211);
// EXTERNAL MODULE: external "zlib"
var external_zlib_ = __nccwpck_require__(8761);
// EXTERNAL MODULE: external "stream"
var external_stream_ = __nccwpck_require__(2413);
// EXTERNAL MODULE: ./node_modules/data-uri-to-buffer/dist/src/index.js
var src = __nccwpck_require__(2371);
// EXTERNAL MODULE: ./node_modules/fetch-blob/streams.cjs
var streams = __nccwpck_require__(8010);
;// CONCATENATED MODULE: ./node_modules/fetch-blob/index.js
// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)
// Node has recently added whatwg stream into core
/** @typedef {import('buffer').Blob} NodeBlob} */
// 64 KiB (same size chrome slice theirs blob into Uint8array's)
const POOL_SIZE = 65536;
/** @param {(Blob | NodeBlob | Uint8Array)[]} parts */
async function * toIterator (parts, clone = true) {
for (let part of parts) {
if ('stream' in part) {
yield * part.stream();
} else if (ArrayBuffer.isView(part)) {
if (clone) {
let position = part.byteOffset;
let 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;
}
} else {
/* c8 ignore start */
// For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)
let position = 0;
while (position !== part.size) {
const chunk = part.slice(position, Math.min(part.size, position + POOL_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
yield new Uint8Array(buffer);
}
/* c8 ignore end */
}
}
}
const _Blob = class Blob {
/** @type {Array.<(Blob|Uint8Array)>} */
#parts = [];
#type = '';
#size = 0;
/**
* 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 }} [options]
*/
constructor(blobParts = [], options = {}) {
let size = 0;
const parts = blobParts.map(element => {
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 = new TextEncoder().encode(element);
}
size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
return part;
});
const type = options.type === undefined ? '' : String(options.type);
this.#type = /[^\u0020-\u007E]/.test(type) ? '' : type;
this.#size = size;
this.#parts = parts;
}
/**
* 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<string>}
*/
async text() {
// More optimized than using this.arrayBuffer()
// that requires twice as much ram
const decoder = new TextDecoder();
let str = '';
for await (let 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<ArrayBuffer>}
*/
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 ReadableStream({
type: 'bytes',
async pull(ctrl) {
const chunk = await it.next();
chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
}
})
}
/**
* 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
}
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 fetch_blob_Blob = _Blob;
/* harmony default export */ const fetch_blob = (fetch_blob_Blob);
;// 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: external "crypto"
const external_crypto_namespaceObject = require("crypto");
2022-01-12 10:27:38 -05:00
var external_crypto_default = /*#__PURE__*/__nccwpck_require__.n(external_crypto_namespaceObject);
2021-09-26 15:31:45 -04:00
;// 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 {*} obj
* @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 {*} obj
* @return {boolean}
*/
const isBlob = object => {
return (
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 a spec-compliant `FormData` object
*
* @param {*} object
* @return {boolean}
*/
function isFormData(object) {
return (
typeof object === 'object' &&
typeof object.append === 'function' &&
typeof object.set === 'function' &&
typeof object.get === 'function' &&
typeof object.getAll === 'function' &&
typeof object.delete === 'function' &&
typeof object.keys === 'function' &&
typeof object.values === 'function' &&
typeof object.entries === 'function' &&
typeof object.constructor === 'function' &&
object[NAME] === 'FormData'
);
}
/**
* Check if `obj` is an instance of AbortSignal.
*
* @param {*} obj
* @return {boolean}
*/
const isAbortSignal = object => {
return (
typeof object === 'object' && (
object[NAME] === 'AbortSignal' ||
object[NAME] === 'EventTarget'
)
);
};
;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/form-data.js
const carriage = '\r\n';
const dashes = '-'.repeat(2);
const carriageLength = Buffer.byteLength(carriage);
/**
* @param {string} boundary
*/
const getFooter = boundary => `${dashes}${boundary}${dashes}${carriage.repeat(2)}`;
/**
* @param {string} boundary
* @param {string} name
* @param {*} field
*
* @return {string}
*/
function getHeader(boundary, name, field) {
let header = '';
header += `${dashes}${boundary}${carriage}`;
header += `Content-Disposition: form-data; name="${name}"`;
if (isBlob(field)) {
header += `; filename="${field.name}"${carriage}`;
header += `Content-Type: ${field.type || 'application/octet-stream'}`;
}
return `${header}${carriage.repeat(2)}`;
}
/**
* @return {string}
*/
const getBoundary = () => (0,external_crypto_namespaceObject.randomBytes)(8).toString('hex');
/**
* @param {FormData} form
* @param {string} boundary
*/
async function * formDataIterator(form, boundary) {
for (const [name, value] of form) {
yield getHeader(boundary, name, value);
if (isBlob(value)) {
yield * value.stream();
} else {
yield value;
}
yield carriage;
}
yield getFooter(boundary);
}
/**
* @param {FormData} form
* @param {string} boundary
*/
function getFormDataLength(form, boundary) {
let length = 0;
for (const [name, value] of form) {
length += Buffer.byteLength(getHeader(boundary, name, value));
length += isBlob(value) ? value.size : Buffer.byteLength(String(value));
length += carriageLength;
}
length += Buffer.byteLength(getFooter(boundary));
return length;
}
;// CONCATENATED MODULE: ./node_modules/node-fetch/src/body.js
/**
* Body.js
*
* Body interface provides common methods for Request and Response
*/
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 = Buffer.from(body.toString());
} else if (isBlob(body)) {
// Body is blob
} else if (Buffer.isBuffer(body)) {
// Body is Buffer
} else if (external_util_.types.isAnyArrayBuffer(body)) {
// Body is ArrayBuffer
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
// Body is ArrayBufferView
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof external_stream_) {
// Body is stream
} else if (isFormData(body)) {
// Body is an instance of formdata-node
boundary = `NodeFetchFormDataBoundary${getBoundary()}`;
body = external_stream_.Readable.from(formDataIterator(body, boundary));
} else {
// None of the above
// coerce to string then buffer
body = Buffer.from(String(body));
}
this[INTERNALS] = {
body,
boundary,
disturbed: false,
error: null
};
this.size = size;
if (body instanceof external_stream_) {
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].body;
}
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);
}
/**
* 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.buffer();
return new fetch_blob([buf], {
type: ct
});
}
/**
* Decode response as json
*
* @return Promise
*/
async json() {
const buffer = await consumeBody(this);
return JSON.parse(buffer.toString());
}
/**
* Decode response as text
*
* @return Promise
*/
async text() {
const buffer = await consumeBody(this);
return buffer.toString();
}
/**
* Decode response as buffer (non-spec api)
*
* @return Promise
*/
buffer() {
return consumeBody(this);
}
}
// 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}
});
/**
* 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;
}
let {body} = data;
// Body is null
if (body === null) {
return Buffer.alloc(0);
}
// Body is blob
if (isBlob(body)) {
body = external_stream_.Readable.from(body.stream());
}
// Body is buffer
if (Buffer.isBuffer(body)) {
return body;
}
/* c8 ignore next 3 */
if (!(body instanceof external_stream_)) {
return 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 Buffer.from(accum.join(''));
}
return 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;
// 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_stream_) && (typeof body.getBoundary !== 'function')) {
// Tee instance body
p1 = new external_stream_.PassThrough({highWaterMark});
p2 = new external_stream_.PassThrough({highWaterMark});
body.pipe(p1);
body.pipe(p2);
// Set instance body to teed body and return the other teed body
instance[INTERNALS].body = p1;
body = p2;
}
return body;
};
/**
* 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 (Buffer.isBuffer(body) || external_util_.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
return null;
}
// Detect form data input from form-data module
if (body && typeof body.getBoundary === 'function') {
return `multipart/form-data;boundary=${body.getBoundary()}`;
}
if (isFormData(body)) {
return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
}
// Body is stream - can't really do much about this
if (body instanceof external_stream_) {
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;
// Body is null or undefined
if (body === null) {
return 0;
}
// Body is Blob
if (isBlob(body)) {
return body.size;
}
// Body is Buffer
if (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 a spec-compliant form-data
if (isFormData(body)) {
return getFormDataLength(request[INTERNALS].boundary);
}
// 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 {void}
*/
const writeToStream = (dest, {body}) => {
if (body === null) {
// Body is null
dest.end();
} else if (isBlob(body)) {
// Body is Blob
external_stream_.Readable.from(body.stream()).pipe(dest);
} else if (Buffer.isBuffer(body)) {
// Body is buffer
dest.write(body);
dest.end();
} else {
// Body is stream
body.pipe(dest);
}
};
;// CONCATENATED MODULE: ./node_modules/node-fetch/src/headers.js
/**
* Headers.js
*
* Headers class offers convenient helpers
*/
const validateHeaderName = typeof external_http_.validateHeaderName === 'function' ?
external_http_.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;
}
};
const validateHeaderValue = typeof external_http_.validateHeaderValue === 'function' ?
external_http_.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<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>} 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_util_.types.isBoxedPrimitive(init)) {
const method = init[Symbol.iterator];
// eslint-disable-next-line no-eq-null, eqeqeq
if (method == null) {
// Record<ByteString, ByteString>
result.push(...Object.entries(init));
} else {
if (typeof method !== 'function') {
throw new TypeError('Header pairs must be iterable');
}
// Sequence<sequence<ByteString>>
// Note: per spec we have to first exhaust the lists then process them
result = [...init]
.map(pair => {
if (
typeof pair !== 'object' || external_util_.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<sequence<ByteString>> or record<ByteString, ByteString>)');
}
// 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<string, string[]>}
*/
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);
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
});
}
/**
* @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;
}
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}
});
// EXTERNAL MODULE: external "url"
var external_url_ = __nccwpck_require__(8835);
;// 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: ./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 {*} obj
* @return {boolean}
*/
const isRequest = object => {
return (
typeof object === 'object' &&
typeof object[request_INTERNALS] === 'object'
);
};
/**
* 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 = {};
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
// 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.append('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');
}
this[request_INTERNALS] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// 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;
}
get method() {
return this[request_INTERNALS].method;
}
get url() {
return (0,external_url_.format)(this[request_INTERNALS].parsedURL);
}
get headers() {
return this[request_INTERNALS].headers;
}
get redirect() {
return this[request_INTERNALS].redirect;
}
get signal() {
return this[request_INTERNALS].signal;
}
/**
* 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}
});
/**
* Convert a Request to Node.js http request options.
*
* @param Request A Request instance
* @return Object 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);
}
// 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);
}
if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}
// HTTP-network fetch step 4.2
// chunked encoding is handled by Node.js
const search = getSearch(parsedURL);
// Manually spread the URL object instead of spread syntax
const requestOptions = {
path: parsedURL.pathname + search,
pathname: parsedURL.pathname,
hostname: parsedURL.hostname,
protocol: parsedURL.protocol,
port: parsedURL.port,
hash: parsedURL.hash,
search: parsedURL.search,
query: parsedURL.query,
href: parsedURL.href,
method: request.method,
headers: headers[Symbol.for('nodejs.util.inspect.custom')](),
insecureHTTPParser: request.insecureHTTPParser,
agent
};
return requestOptions;
};
;// 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);
}
}
;// 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<import('./response').default>}
*/
async function fetch(url, options_) {
return new Promise((resolve, reject) => {
// Build request object
const request = new Request(url, options_);
const options = getNodeRequestOptions(request);
if (!supportedSchemas.has(options.protocol)) {
throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${options.protocol.replace(/:$/, '')}" is not supported.`);
}
if (options.protocol === 'data:') {
const data = src(request.url);
const response = new Response(data, {headers: {'Content-Type': data.typeFull}});
resolve(response);
return;
}
// Wrap http.request into fetch
const send = (options.protocol === 'https:' ? external_https_ : external_http_).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_stream_.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(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 => {
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
const locationURL = location === null ? null : new URL(location, request.url);
// 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':
// Node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
if (locationURL !== null) {
headers.set('Location', locationURL);
}
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: request.body,
signal: request.signal,
size: request.size
};
// HTTP-redirect fetch step 9
if (response_.statusCode !== 303 && request.body && options_.body instanceof external_stream_.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 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_stream_.pipeline)(response_, new external_stream_.PassThrough(), reject);
// see https://github.com/nodejs/node/pull/29376
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_zlib_.Z_SYNC_FLUSH,
finishFlush: external_zlib_.Z_SYNC_FLUSH
};
// For gzip
if (codings === 'gzip' || codings === 'x-gzip') {
body = (0,external_stream_.pipeline)(body, external_zlib_.createGunzip(zlibOptions), reject);
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_stream_.pipeline)(response_, new external_stream_.PassThrough(), reject);
raw.once('data', chunk => {
// See http://stackoverflow.com/questions/37519828
body = (chunk[0] & 0x0F) === 0x08 ? (0,external_stream_.pipeline)(body, external_zlib_.createInflate(), reject) : (0,external_stream_.pipeline)(body, external_zlib_.createInflateRaw(), reject);
response = new Response(body, responseOptions);
resolve(response);
});
return;
}
// For br
if (codings === 'br') {
body = (0,external_stream_.pipeline)(body, external_zlib_.createBrotliDecompress(), reject);
response = new Response(body, responseOptions);
resolve(response);
return;
}
// Otherwise, use response as-is
response = new Response(body, responseOptions);
resolve(response);
});
writeToStream(request_, request);
});
}
function fixResponseChunkedTransferBadEnding(request, errorCallback) {
const LAST_CHUNK = 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);
}
};
socket.prependListener('close', onSocketClose);
request.on('abort', () => {
socket.removeListener('close', onSocketClose);
});
socket.on('data', buf => {
properLastChunkReceived = 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 = (
Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&
Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0
);
}
previousChunk = buf;
});
});
}
2022-01-12 10:27:38 -05:00
;// CONCATENATED MODULE: ./src/utils/hash-utils.ts
function computeHash(path, algorithm) {
const hash = external_crypto_default().createHash(algorithm);
return new Promise(resolve => external_fs_default().createReadStream(path).on("data", data => hash.update(data)).on("end", () => resolve(hash)));
}
;// CONCATENATED MODULE: ./src/utils/soft-error.ts
class SoftError extends Error {
constructor(soft, message) {
super(message);
this.soft = soft;
}
}
2021-09-26 15:31:45 -04:00
;// CONCATENATED MODULE: ./src/utils/modrinth-utils.ts
var modrinth_utils_awaiter = (undefined && undefined.__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());
});
};
2022-01-12 10:27:38 -05:00
function createVersion(modId, data, files, token) {
2021-09-26 15:31:45 -04:00
return modrinth_utils_awaiter(this, void 0, void 0, function* () {
2022-01-12 10:27:38 -05:00
data = Object.assign(Object.assign({ dependencies: [] }, data), { mod_id: modId, file_parts: files.map((_, i) => i.toString()) });
2021-09-26 15:31:45 -04:00
const form = new FormData();
form.append("data", JSON.stringify(data));
for (let i = 0; i < files.length; ++i) {
const file = files[i];
form.append(i.toString(), yield fileFromPath(file.path), file.name);
}
const response = yield fetch("https://api.modrinth.com/api/v1/version", {
method: "POST",
headers: { Authorization: token },
body: form
});
if (!response.ok) {
let errorText = response.statusText;
try {
errorText += `, ${yield response.text()}`;
}
catch (_a) { }
2022-01-12 10:27:38 -05:00
const isServerError = response.status >= 500;
throw new SoftError(isServerError, `Failed to upload file: ${response.status} (${errorText})`);
2021-09-26 15:31:45 -04:00
}
2022-01-12 10:27:38 -05:00
const versionId = (yield response.json()).id;
const primaryFile = files[0];
if (primaryFile) {
yield makeFilePrimary(versionId, primaryFile.path, token);
}
return versionId;
});
}
function makeFilePrimary(versionId, filePath, token) {
return modrinth_utils_awaiter(this, void 0, void 0, function* () {
const algorithm = "sha1";
const hash = (yield computeHash(filePath, algorithm)).digest("hex");
const response = yield fetch(`https://api.modrinth.com/api/v1/version/${versionId}`, {
method: "PATCH",
headers: {
"Authorization": token,
"Content-Type": "application/json"
},
body: JSON.stringify({
primary_file: [algorithm, hash]
})
});
return response.ok;
2021-09-26 15:31:45 -04:00
});
}
;// CONCATENATED MODULE: ./src/utils/version.ts
class Version {
constructor(major, minor, build) {
if (typeof major === "string") {
[this.major, this.minor, this.build] = major.split(".").map(x => isNaN(+x) ? 0 : +x).concat(0, 0);
}
else {
this.major = major || 0;
this.minor = minor || 0;
this.build = build || 0;
}
}
2021-10-01 09:38:36 -04:00
equals(version) {
if (version instanceof Version) {
return this.major === version.major && this.minor === version.minor && this.build === version.build;
}
return typeof version === "string" && this.equals(new Version(version));
}
2021-09-26 15:31:45 -04:00
}
;// CONCATENATED MODULE: ./src/utils/minecraft-utils.ts
var minecraft_utils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var MinecraftVersionType;
(function (MinecraftVersionType) {
MinecraftVersionType["Release"] = "release";
MinecraftVersionType["Snapshot"] = "snapshot";
MinecraftVersionType["OldBeta"] = "old_beta";
MinecraftVersionType["OldAlpha"] = "old_alpha";
})(MinecraftVersionType || (MinecraftVersionType = {}));
class MinecraftVersion {
constructor(id, name, type, url, time, releaseTime) {
this.id = id;
this.name = name;
this.version = new Version(name);
this.type = type;
this.url = url;
this.time = time;
this.releaseTime = releaseTime;
}
get isRelease() {
return this.type === MinecraftVersionType.Release;
}
get isSnapshot() {
return this.type === MinecraftVersionType.Snapshot;
}
}
let cachedVersionsById = null;
function getVersionMap() {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
if (!cachedVersionsById) {
cachedVersionsById = yield loadVersions();
}
return cachedVersionsById;
});
}
function loadVersions() {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
const response = yield (yield fetch("https://launchermeta.mojang.com/mc/game/version_manifest.json")).json();
const versionsById = new Map();
for (let i = 0; i < response.versions.length; ++i) {
const version = response.versions[i];
versionsById.set(version.id, new MinecraftVersion(version.id, getNearestReleaseVersionName(response.versions, i), version.type, version.url, new Date(version.time), new Date(version.releaseTime)));
}
return versionsById;
});
}
function getNearestReleaseVersionName(versions, start) {
for (let i = start; i >= 0; --i) {
if (versions[i].type === MinecraftVersionType.Release) {
return versions[i].id;
}
}
const versionMatch = versions[start].id.match(/\d+\.\d+(?:\.\d+)?/);
if (versionMatch && versionMatch.length > 0) {
return versionMatch[0];
}
for (let i = start + 1; i < versions.length; ++i) {
if (versions[i].type === MinecraftVersionType.Release) {
return extractVersion(versions[i].id).split(".").map((x, i) => i === 1 ? (+x + 1) : x).filter((x, i) => i < 2).join(".");
}
}
return null;
}
function getVersions() {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
return [...(yield getVersionMap()).values()];
});
}
function getVersionById(id) {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
return (yield getVersionMap()).get(id.trim()) || null;
});
}
function findVersionByName(name, snapshot) {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
const versionMap = yield getVersionMap();
snapshot !== null && snapshot !== void 0 ? snapshot : (snapshot = isSnapshot(name));
const foundVersion = versionMap.get(name);
if (foundVersion && foundVersion.isSnapshot === !!snapshot) {
return foundVersion;
}
name = extractVersion(name);
for (const version of versionMap.values()) {
if (version.name === name && version.isSnapshot) {
return version;
}
}
return null;
});
}
function extractVersion(versionName) {
return versionName.match(/(?<![a-z][\w\s\-.]*)\d+/ig).join(".");
}
const weirdOldSnapshots = new Set(["1.7.1", "1.7", "1.6.3", "1.6", "1.5", "1.4.3", "1.4.1", "1.4", "1.3"]);
function isSnapshot(versionName) {
return !versionName.match(/^\s*\d+\.\d+/) || !!versionName.match(/pre|rc|snapshot/i) || weirdOldSnapshots.has(versionName);
}
function parseVersionNameFromFileVersion(fileVersion) {
const mcMatch = fileVersion.match(/mc(\d+\.\d+(?:\.\d+)?)/i);
if (mcMatch) {
return mcMatch[1];
}
else {
const versionCandidates = fileVersion.split(/[+-]/).map(x => x.match(/\d+\.\d+(?:\.\d+)?/)).filter(x => x).map(x => x[0]);
return versionCandidates.length > 1 ? versionCandidates.filter(x => x.startsWith("1.")).reverse()[0] : null;
}
}
2021-12-11 08:00:14 -05:00
function parseVersionName(version) {
const versionCandidates = [...(version.match(/\d+\.\d+(?:\.\d+)?/g) || [])];
return versionCandidates.filter(x => x.startsWith("1."))[0] || null;
}
2021-09-26 15:31:45 -04:00
function getLatestRelease() {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
return (yield getVersions()).find(x => x.isRelease) || null;
});
}
function getCompatibleBuilds(build) {
return minecraft_utils_awaiter(this, void 0, void 0, function* () {
if (!(build instanceof Version)) {
build = new Version(build);
}
const versions = new Array();
for (const version of yield getVersions()) {
if (version.version.major !== build.major) {
continue;
}
if (version.version.minor < build.minor) {
break;
}
if (version.version.minor === build.minor && version.version.build >= build.build) {
versions.push(version);
}
}
return versions;
});
}
2021-10-01 09:38:36 -04:00
;// CONCATENATED MODULE: ./src/utils/game-version-resolver.ts
var game_version_resolver_awaiter = (undefined && undefined.__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());
});
};
class GameVersionResolver {
constructor(filter) {
this._filter = filter || ((_, x) => x);
}
resolve(version) {
return game_version_resolver_awaiter(this, void 0, void 0, function* () {
return this.filter(version, yield this.getCompatibleVersions(version));
});
}
filter(version, versions) {
return this._filter(version, versions);
}
}
;// CONCATENATED MODULE: ./src/utils/minecraft-version-resolver.ts
class MinecraftVersionResolver extends GameVersionResolver {
static byName(name) {
for (const [key, value] of Object.entries(MinecraftVersionResolver)) {
if (value instanceof MinecraftVersionResolver && key.localeCompare(name, undefined, { sensitivity: "accent" }) === 0) {
return value;
}
}
return null;
}
getCompatibleVersions(version) {
return getCompatibleBuilds(version);
}
}
MinecraftVersionResolver.exact = new MinecraftVersionResolver((n, v) => [v.find(x => x.version.equals(n))].filter(x => x));
MinecraftVersionResolver.latest = new MinecraftVersionResolver((_, v) => v.find(x => x.isRelease) ? [v.find(x => x.isRelease)] : v.length ? [v[0]] : []);
MinecraftVersionResolver.all = new MinecraftVersionResolver((_, v) => v);
MinecraftVersionResolver.releases = new MinecraftVersionResolver((_, v) => v.filter(x => x.isRelease));
MinecraftVersionResolver.releasesIfAny = new MinecraftVersionResolver((_, v) => v.find(x => x.isRelease) ? v.filter(x => x.isRelease) : v);
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/metadata/mod-loader-type.ts
var ModLoaderType;
(function (ModLoaderType) {
ModLoaderType[ModLoaderType["Fabric"] = 1] = "Fabric";
ModLoaderType[ModLoaderType["Forge"] = 2] = "Forge";
})(ModLoaderType || (ModLoaderType = {}));
(function (ModLoaderType) {
function getValues() {
return Object.values(ModLoaderType).filter(x => typeof x === "number");
}
ModLoaderType.getValues = getValues;
function toString(target) {
var _a;
return (_a = ModLoaderType[target]) !== null && _a !== void 0 ? _a : target.toString();
}
ModLoaderType.toString = toString;
})(ModLoaderType || (ModLoaderType = {}));
/* harmony default export */ const mod_loader_type = (ModLoaderType);
// EXTERNAL MODULE: ./node_modules/node-stream-zip/node_stream_zip.js
var node_stream_zip = __nccwpck_require__(8119);
;// CONCATENATED MODULE: ./src/metadata/zipped-mod-metadata-reader.ts
var zipped_mod_metadata_reader_awaiter = (undefined && undefined.__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());
});
};
class ZippedModMetadataReader {
constructor(configEntryName) {
this.configEntryName = configEntryName;
}
readMetadata(modPath) {
return zipped_mod_metadata_reader_awaiter(this, void 0, void 0, function* () {
let zip = null;
try {
zip = new node_stream_zip.async({ file: modPath });
const buffer = yield zip.entryData(this.configEntryName).catch(_ => null);
if (buffer) {
return this.createMetadataFromConfig(this.loadConfig(buffer));
}
else {
return null;
}
}
catch (_a) {
return null;
}
finally {
yield (zip === null || zip === void 0 ? void 0 : zip.close());
}
});
}
}
;// CONCATENATED MODULE: ./package.json
const package_namespaceObject = {"u2":"mc-publish"};
;// CONCATENATED MODULE: ./src/metadata/mod-config.ts
class ModConfig {
constructor(config) {
this.config = config || {};
}
getProjectId(project) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
const projectName = publisher_target.toString(project).toLowerCase();
const custom = this.config["custom"];
const projects = this.config["projects"];
const projectId = ((_l = (_h = (_g = (_e = (_c = (_b = (_a = custom === null || custom === void 0 ? void 0 : custom[package_namespaceObject.u2]) === null || _a === void 0 ? void 0 : _a[projectName]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : (_d = custom === null || custom === void 0 ? void 0 : custom[package_namespaceObject.u2]) === null || _d === void 0 ? void 0 : _d[projectName]) !== null && _e !== void 0 ? _e : (_f = projects === null || projects === void 0 ? void 0 : projects[projectName]) === null || _f === void 0 ? void 0 : _f.id) !== null && _g !== void 0 ? _g : projects === null || projects === void 0 ? void 0 : projects[projectName]) !== null && _h !== void 0 ? _h : (_k = (_j = custom === null || custom === void 0 ? void 0 : custom.projects) === null || _j === void 0 ? void 0 : _j[projectName]) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : (_m = custom === null || custom === void 0 ? void 0 : custom.projects) === null || _m === void 0 ? void 0 : _m[projectName]);
return projectId === undefined ? projectId : String(projectId);
}
}
;// CONCATENATED MODULE: ./src/metadata/dependency-kind.ts
var DependencyKind;
(function (DependencyKind) {
DependencyKind[DependencyKind["Depends"] = 1] = "Depends";
DependencyKind[DependencyKind["Recommends"] = 2] = "Recommends";
DependencyKind[DependencyKind["Includes"] = 3] = "Includes";
DependencyKind[DependencyKind["Suggests"] = 4] = "Suggests";
DependencyKind[DependencyKind["Conflicts"] = 5] = "Conflicts";
DependencyKind[DependencyKind["Breaks"] = 6] = "Breaks";
})(DependencyKind || (DependencyKind = {}));
(function (DependencyKind) {
function getValues() {
return Object.values(DependencyKind).filter(x => typeof x === "number");
}
DependencyKind.getValues = getValues;
function parse(kindName) {
if (typeof DependencyKind[kindName] === "number") {
return DependencyKind[kindName];
}
for (const kind of Object.values(DependencyKind)) {
if (typeof kind === "number" && kindName.localeCompare(DependencyKind[kind], undefined, { sensitivity: "accent" }) === 0) {
return kind;
}
}
return undefined;
}
DependencyKind.parse = parse;
function toString(target) {
var _a;
return (_a = DependencyKind[target]) !== null && _a !== void 0 ? _a : target.toString();
}
DependencyKind.toString = toString;
})(DependencyKind || (DependencyKind = {}));
/* harmony default export */ const dependency_kind = (DependencyKind);
;// CONCATENATED MODULE: ./src/metadata/mod-config-dependency.ts
class ModConfigDependency {
constructor(metadata) {
var _a, _b, _c, _d, _e, _f, _g, _h;
this.id = String((_a = metadata.id) !== null && _a !== void 0 ? _a : "");
this.version = String((_b = metadata.version) !== null && _b !== void 0 ? _b : "*");
this.kind = metadata.kind || dependency_kind.Depends;
this.metadata = metadata;
this.ignore = (_h = (_g = (_e = (_d = (_c = this.metadata["custom"]) === null || _c === void 0 ? void 0 : _c[package_namespaceObject.u2]) === null || _d === void 0 ? void 0 : _d.ignore) !== null && _e !== void 0 ? _e : (_f = this.metadata[package_namespaceObject.u2]) === null || _f === void 0 ? void 0 : _f.ignore) !== null && _g !== void 0 ? _g : this.metadata.ignore) !== null && _h !== void 0 ? _h : false;
}
getProjectSlug(project) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
const projectName = publisher_target.toString(project).toLowerCase();
const custom = this.metadata["custom"];
const projects = this.metadata["projects"];
return String((_o = (_l = (_h = (_g = (_e = (_c = (_b = (_a = custom === null || custom === void 0 ? void 0 : custom[package_namespaceObject.u2]) === null || _a === void 0 ? void 0 : _a[projectName]) === null || _b === void 0 ? void 0 : _b.slug) !== null && _c !== void 0 ? _c : (_d = custom === null || custom === void 0 ? void 0 : custom[package_namespaceObject.u2]) === null || _d === void 0 ? void 0 : _d[projectName]) !== null && _e !== void 0 ? _e : (_f = projects === null || projects === void 0 ? void 0 : projects[projectName]) === null || _f === void 0 ? void 0 : _f.slug) !== null && _g !== void 0 ? _g : projects === null || projects === void 0 ? void 0 : projects[projectName]) !== null && _h !== void 0 ? _h : (_k = (_j = custom === null || custom === void 0 ? void 0 : custom.projects) === null || _j === void 0 ? void 0 : _j[projectName]) === null || _k === void 0 ? void 0 : _k.slug) !== null && _l !== void 0 ? _l : (_m = custom === null || custom === void 0 ? void 0 : custom.projects) === null || _m === void 0 ? void 0 : _m[projectName]) !== null && _o !== void 0 ? _o : this.id);
}
}
;// CONCATENATED MODULE: ./src/metadata/dependency.ts
var Dependency;
(function (Dependency) {
function create({ id, version = "*", kind = dependency_kind.Depends, ignore = false, aliases = null }) {
return {
id,
version: version !== null && version !== void 0 ? version : "*",
kind: kind !== null && kind !== void 0 ? kind : dependency_kind.Depends,
ignore: ignore !== null && ignore !== void 0 ? ignore : false,
getProjectSlug: target => (aliases === null || aliases === void 0 ? void 0 : aliases.has(target)) ? aliases.get(target) : id
};
}
Dependency.create = create;
})(Dependency || (Dependency = {}));
/* harmony default export */ const dependency = (Dependency);
;// CONCATENATED MODULE: ./src/metadata/fabric/fabric-mod-metadata.ts
const ignoredByDefault = ["minecraft", "java", "fabricloader"];
const aliases = new Map([
["fabric", "fabric-api"]
]);
function getDependenciesByKind(config, kind) {
const kindName = dependency_kind.toString(kind).toLowerCase();
const dependencies = new Array();
for (const [id, value] of Object.entries(config[kindName] || {})) {
const ignore = ignoredByDefault.includes(id);
if (typeof value === "string") {
const dependencyAliases = aliases.has(id) ? new Map(publisher_target.getValues().map(x => [x, aliases.get(id)])) : null;
dependencies.push(dependency.create({ id, kind, version: value, ignore, aliases: dependencyAliases }));
}
else {
const dependencyMetadata = Object.assign(Object.assign({ ignore }, value), { id, kind });
if (aliases.has(id)) {
if (!dependencyMetadata.custom) {
dependencyMetadata.custom = {};
}
if (!dependencyMetadata.custom[package_namespaceObject.u2]) {
dependencyMetadata.custom[package_namespaceObject.u2] = {};
}
for (const target of publisher_target.getValues()) {
const targetName = publisher_target.toString(target).toLowerCase();
if (typeof dependencyMetadata.custom[package_namespaceObject.u2][targetName] !== "string") {
dependencyMetadata.custom[package_namespaceObject.u2][targetName] = aliases.get(id);
}
}
}
dependencies.push(new ModConfigDependency(dependencyMetadata));
}
}
return dependencies;
}
class FabricModMetadata extends ModConfig {
constructor(config) {
var _a, _b, _c;
super(config);
this.id = String((_a = this.config.id) !== null && _a !== void 0 ? _a : "");
this.name = String((_b = this.config.name) !== null && _b !== void 0 ? _b : this.id);
this.version = String((_c = this.config.version) !== null && _c !== void 0 ? _c : "*");
this.loaders = ["fabric"];
this.dependencies = dependency_kind.getValues().flatMap(x => getDependenciesByKind(this.config, x));
}
getProjectId(project) {
var _a, _b, _c, _d;
const projectId = super.getProjectId(project);
if (projectId) {
return projectId;
}
const projectName = publisher_target.toString(project).toLowerCase();
const custom = this.config.custom;
const modManagerProjectId = (_c = (_b = (_a = custom === null || custom === void 0 ? void 0 : custom.modmanager) === null || _a === void 0 ? void 0 : _a[projectName]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : (_d = custom === null || custom === void 0 ? void 0 : custom.modmanager) === null || _d === void 0 ? void 0 : _d[projectName];
return modManagerProjectId === undefined ? modManagerProjectId : String(modManagerProjectId);
}
}
;// CONCATENATED MODULE: ./src/metadata/fabric/fabric-mod-metadata-reader.ts
class FabricModMetadataReader extends ZippedModMetadataReader {
constructor() {
super("fabric.mod.json");
}
loadConfig(buffer) {
return JSON.parse(buffer.toString("utf8"));
}
createMetadataFromConfig(config) {
return new FabricModMetadata(config);
}
}
// EXTERNAL MODULE: ./node_modules/toml/index.js
var toml = __nccwpck_require__(4920);
var toml_default = /*#__PURE__*/__nccwpck_require__.n(toml);
;// CONCATENATED MODULE: ./src/metadata/forge/forge-mod-metadata.ts
const forge_mod_metadata_ignoredByDefault = ["minecraft", "java", "forge"];
function createDependency(body) {
return new ModConfigDependency(Object.assign(Object.assign({ ignore: forge_mod_metadata_ignoredByDefault.includes(body.modId) }, body), { id: body.modId, version: body.versionRange, kind: body.incompatible && dependency_kind.Breaks || body.embedded && dependency_kind.Includes || body.mandatory && dependency_kind.Depends || dependency_kind.Recommends }));
}
class ForgeModMetadata extends ModConfig {
constructor(config) {
super(config);
const mods = Array.isArray(this.config.mods) && this.config.mods || [];
const mod = mods[0];
if (!mod) {
throw new Error("At least one mod should be specified");
}
this.id = mod.modId;
this.name = mod.displayName || this.id;
this.version = mod.version || "*";
this.loaders = ["forge"];
this.dependencies = Object
.values(this.config.dependencies || {})
.filter(Array.isArray)
.flatMap(x => x)
.map(createDependency)
.filter((x, i, self) => self.findIndex(y => x.id === y.id && x.kind === y.kind) === i);
}
}
;// CONCATENATED MODULE: ./src/metadata/forge/forge-mod-metadata-reader.ts
class ForgeModMetadataReader extends ZippedModMetadataReader {
constructor() {
super("META-INF/mods.toml");
}
loadConfig(buffer) {
return toml_default().parse(buffer.toString("utf8"));
}
createMetadataFromConfig(config) {
return new ForgeModMetadata(config);
}
}
;// CONCATENATED MODULE: ./src/metadata/mod-metadata-reader-factory.ts
class ModMetadataReaderFactory {
create(loaderType) {
switch (loaderType) {
case mod_loader_type.Fabric:
return new FabricModMetadataReader();
case mod_loader_type.Forge:
return new ForgeModMetadataReader();
default:
throw new Error(`Unknown mod loader "${mod_loader_type.toString(loaderType)}"`);
}
}
}
;// CONCATENATED MODULE: ./src/metadata/mod-metadata-reader.ts
var mod_metadata_reader_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var ModMetadataReader;
(function (ModMetadataReader) {
function readMetadata(modPath) {
return mod_metadata_reader_awaiter(this, void 0, void 0, function* () {
const factory = new ModMetadataReaderFactory();
for (const loaderType of mod_loader_type.getValues()) {
const metadata = yield factory.create(loaderType).readMetadata(modPath).catch(_ => null);
if (metadata) {
return metadata;
}
}
return null;
});
}
ModMetadataReader.readMetadata = readMetadata;
})(ModMetadataReader || (ModMetadataReader = {}));
/* harmony default export */ const mod_metadata_reader = (ModMetadataReader);
;// CONCATENATED MODULE: ./src/utils/version-utils.ts
function parseVersionFromName(name) {
const match = name.match(/[a-z]{0,2}\d+\.\d+.*/i);
return match ? match[0] : name;
}
function parseVersionTypeFromName(name) {
if (name.match(/[+-_]alpha/i)) {
return "alpha";
}
else if (name.match(/[+-_]beta/i)) {
return "beta";
}
else {
return "release";
}
}
2021-09-26 15:31:45 -04:00
;// CONCATENATED MODULE: ./src/publishing/mod-publisher.ts
var mod_publisher_awaiter = (undefined && undefined.__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());
});
};
2021-10-01 09:38:36 -04:00
2021-12-11 08:00:14 -05:00
2021-09-26 15:31:45 -04:00
function processMultilineInput(input, splitter) {
if (!input) {
return [];
}
return (typeof input === "string" ? input.split(splitter || /(\r?\n)+/) : input).map(x => x.trim()).filter(x => x);
}
2021-12-11 08:00:14 -05:00
function processDependenciesInput(input, inputSplitter, entrySplitter) {
return processMultilineInput(input, inputSplitter).map(x => {
var _a;
const parts = x.split(entrySplitter || /\|/);
const id = parts[0].trim();
return dependency.create({
id,
kind: parts[1] && dependency_kind.parse(parts[1].trim()) || dependency_kind.Depends,
version: ((_a = parts[2]) === null || _a === void 0 ? void 0 : _a.trim()) || "*"
});
});
}
function readChangelog(changelogPath) {
2021-09-26 15:31:45 -04:00
return mod_publisher_awaiter(this, void 0, void 0, function* () {
2021-12-11 08:00:14 -05:00
const file = (yield getFiles(changelogPath))[0];
2021-09-26 15:31:45 -04:00
if (!file) {
throw new Error("Changelog file was not found");
}
return (yield file.getBuffer()).toString("utf8");
});
}
class ModPublisher extends Publisher {
2021-10-01 09:38:36 -04:00
publish(files, options) {
2021-09-26 15:31:45 -04:00
var _a, _b;
return mod_publisher_awaiter(this, void 0, void 0, function* () {
2021-10-01 09:38:36 -04:00
this.validateOptions(options);
2021-09-26 15:31:45 -04:00
const releaseInfo = github.context.payload.release;
2021-12-11 08:00:14 -05:00
if (!Array.isArray(files) || !files.length) {
throw new Error("No upload files were specified");
2021-09-26 15:31:45 -04:00
}
2021-10-01 09:38:36 -04:00
const token = options.token;
2021-09-26 15:31:45 -04:00
if (!token) {
throw new Error(`Token is required to publish your assets to ${publisher_target.toString(this.target)}`);
}
2021-12-11 08:00:14 -05:00
const metadata = yield mod_metadata_reader.readMetadata(files[0].path);
const id = options.id || (metadata === null || metadata === void 0 ? void 0 : metadata.getProjectId(this.target));
if (!id) {
throw new Error(`Project id is required to publish your assets to ${publisher_target.toString(this.target)}`);
}
const filename = external_path_default().parse(files[0].path).name;
const version = (typeof options.version === "string" && options.version) || (releaseInfo === null || releaseInfo === void 0 ? void 0 : releaseInfo.tag_name) || (metadata === null || metadata === void 0 ? void 0 : metadata.version) || parseVersionFromName(filename);
const versionType = ((_a = options.versionType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || parseVersionTypeFromName((metadata === null || metadata === void 0 ? void 0 : metadata.version) || filename);
2021-10-01 09:38:36 -04:00
const name = typeof options.name === "string" ? options.name : ((releaseInfo === null || releaseInfo === void 0 ? void 0 : releaseInfo.name) || version);
2021-12-11 08:00:14 -05:00
const changelog = typeof options.changelog === "string"
? options.changelog
: ((_b = options.changelog) === null || _b === void 0 ? void 0 : _b.file)
? yield readChangelog(options.changelog.file)
: (releaseInfo === null || releaseInfo === void 0 ? void 0 : releaseInfo.body) || "";
2021-10-01 09:38:36 -04:00
const loaders = processMultilineInput(options.loaders, /\s+/);
2021-09-26 15:31:45 -04:00
if (!loaders.length) {
2021-12-11 08:00:14 -05:00
if (metadata) {
loaders.push(...metadata.loaders);
}
if (!loaders.length) {
throw new Error("At least one mod loader should be specified");
}
2021-09-26 15:31:45 -04:00
}
2021-10-01 09:38:36 -04:00
const gameVersions = processMultilineInput(options.gameVersions);
2021-09-26 15:31:45 -04:00
if (!gameVersions.length) {
2021-12-11 08:00:14 -05:00
const minecraftVersion = (metadata === null || metadata === void 0 ? void 0 : metadata.dependencies.filter(x => x.id === "minecraft").map(x => parseVersionName(x.version))[0]) ||
parseVersionNameFromFileVersion(version);
2021-09-26 15:31:45 -04:00
if (minecraftVersion) {
2021-10-01 09:38:36 -04:00
const resolver = options.versionResolver && MinecraftVersionResolver.byName(options.versionResolver) || MinecraftVersionResolver.releasesIfAny;
gameVersions.push(...(yield resolver.resolve(minecraftVersion)).map(x => x.id));
2021-09-26 15:31:45 -04:00
}
if (!gameVersions.length) {
throw new Error("At least one game version should be specified");
}
}
2021-10-01 09:38:36 -04:00
const java = processMultilineInput(options.java);
2021-12-11 08:00:14 -05:00
const dependencies = typeof options.dependencies === "string"
? processDependenciesInput(options.dependencies)
: (metadata === null || metadata === void 0 ? void 0 : metadata.dependencies) || [];
const uniqueDependencies = dependencies.filter((x, i, self) => !x.ignore && self.findIndex(y => y.id === x.id && y.kind === x.kind) === i);
yield this.publishMod(id, token, name, version, versionType, loaders, gameVersions, java, changelog, files, uniqueDependencies);
2021-09-26 15:31:45 -04:00
});
}
}
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/publishing/modrinth/modrinth-publisher.ts
2021-09-26 15:31:45 -04:00
var modrinth_publisher_awaiter = (undefined && undefined.__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());
});
};
class ModrinthPublisher extends ModPublisher {
get target() {
return publisher_target.Modrinth;
}
publishMod(id, token, name, version, channel, loaders, gameVersions, _java, changelog, files) {
return modrinth_publisher_awaiter(this, void 0, void 0, function* () {
const data = {
2021-10-01 09:38:36 -04:00
version_title: name || version,
2021-09-26 15:31:45 -04:00
version_number: version,
version_body: changelog,
release_channel: channel,
game_versions: gameVersions,
loaders,
featured: true,
};
yield createVersion(id, data, files, token);
});
}
}
;// CONCATENATED MODULE: ./src/utils/curseforge-utils.ts
var curseforge_utils_awaiter = (undefined && undefined.__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());
});
};
2022-01-12 10:27:38 -05:00
2021-09-26 15:31:45 -04:00
const baseUrl = "https://minecraft.curseforge.com/api";
2022-01-12 10:27:38 -05:00
class CurseForgeUploadError extends SoftError {
constructor(soft, message, info) {
super(soft, message);
2021-12-11 08:00:14 -05:00
this.info = info;
}
}
2021-09-26 15:31:45 -04:00
let cachedCurseForgeVersions = null;
function getCurseForgeVersions(token) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
if (!cachedCurseForgeVersions) {
cachedCurseForgeVersions = yield loadCurseForgeVersions(token);
}
return cachedCurseForgeVersions;
});
}
function loadCurseForgeVersions(token) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
const versionTypes = yield (yield fetch(`${baseUrl}/game/version-types?token=${token}`)).json();
const javaVersionTypes = versionTypes.filter(x => x.slug.startsWith("java")).map(x => x.id);
const minecraftVersionTypes = versionTypes.filter(x => x.slug.startsWith("minecraft")).map(x => x.id);
const loaderVersionTypes = versionTypes.filter(x => x.slug.startsWith("modloader")).map(x => x.id);
const versions = yield (yield fetch(`${baseUrl}/game/versions?token=${token}`)).json();
return versions.reduce((container, version) => {
if (javaVersionTypes.includes(version.gameVersionTypeID)) {
container.java.push(version);
}
else if (minecraftVersionTypes.includes(version.gameVersionTypeID)) {
container.gameVersions.push(version);
}
else if (loaderVersionTypes.includes(version.gameVersionTypeID)) {
container.loaders.push(version);
}
return container;
}, { gameVersions: new Array(), loaders: new Array(), java: new Array() });
});
}
function unifyGameVersion(gameVersion) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
gameVersion = gameVersion.trim();
const minecraftVersion = yield findVersionByName(gameVersion);
if (minecraftVersion) {
return `${minecraftVersion.name}${(minecraftVersion.isSnapshot ? "-Snapshot" : "")}`;
}
return gameVersion.replace(/([^\w]|_)+/g, ".").replace(/[.-][a-zA-Z]\w+$/, "-Snapshot");
});
}
function unifyJava(java) {
java = java.trim();
const match = java.match(/(?:\d+\D)?(\d+)$/);
if (match && match.length === 2) {
return `Java ${match[1]}`;
}
return java;
}
function addVersionIntersectionToSet(curseForgeVersions, versions, unify, comparer, intersection) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
for (const version of versions) {
const unifiedVersion = yield unify(version);
const curseForgeVersion = curseForgeVersions.find(x => comparer(x, unifiedVersion));
if (curseForgeVersion) {
intersection.add(curseForgeVersion.id);
}
}
});
}
function convertToCurseForgeVersions(gameVersions, loaders, java, token) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
const versions = new Set();
const curseForgeVersions = yield getCurseForgeVersions(token);
yield addVersionIntersectionToSet(curseForgeVersions.gameVersions, gameVersions, unifyGameVersion, (cfv, v) => cfv.name === v, versions);
yield addVersionIntersectionToSet(curseForgeVersions.loaders, loaders, x => x.trim().toLowerCase(), (cfv, v) => cfv.slug === v, versions);
yield addVersionIntersectionToSet(curseForgeVersions.java, java, unifyJava, (cfv, v) => cfv.name === v, versions);
return [...versions];
});
}
function uploadFile(id, data, file, token) {
return curseforge_utils_awaiter(this, void 0, void 0, function* () {
const form = new FormData();
form.append("file", yield fileFromPath(file.path), file.name);
form.append("metadata", JSON.stringify(data));
const response = yield fetch(`${baseUrl}/projects/${id}/upload-file?token=${token}`, {
method: "POST",
body: form
});
if (!response.ok) {
let errorText = response.statusText;
2021-12-11 08:00:14 -05:00
let info;
2021-09-26 15:31:45 -04:00
try {
2021-12-11 08:00:14 -05:00
info = (yield response.json());
errorText += `, ${JSON.stringify(info)}`;
2021-09-26 15:31:45 -04:00
}
catch (_a) { }
2022-01-12 10:27:38 -05:00
const isServerError = response.status >= 500;
throw new CurseForgeUploadError(isServerError, `Failed to upload file: ${response.status} (${errorText})`, info);
2021-09-26 15:31:45 -04:00
}
return (yield response.json()).id;
});
}
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/publishing/curseforge/curseforge-publisher.ts
var curseforge_publisher_awaiter = (undefined && undefined.__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());
});
};
const forgeDependencyKinds = new Map([
[dependency_kind.Depends, "requiredDependency"],
[dependency_kind.Recommends, "optionalDependency"],
[dependency_kind.Suggests, "optionalDependency"],
[dependency_kind.Includes, "embeddedLibrary"],
[dependency_kind.Breaks, "incompatible"],
]);
class CurseForgePublisher extends ModPublisher {
get target() {
return publisher_target.CurseForge;
}
publishMod(id, token, name, _version, channel, loaders, gameVersions, java, changelog, files, dependencies) {
return curseforge_publisher_awaiter(this, void 0, void 0, function* () {
let parentFileId = undefined;
const versions = yield convertToCurseForgeVersions(gameVersions, loaders, java, token);
const projects = dependencies
.filter((x, _, self) => x.kind !== dependency_kind.Suggests || !self.find(y => y.id === x.id && y.kind !== dependency_kind.Suggests))
.map(x => ({
slug: x.getProjectSlug(this.target),
type: forgeDependencyKinds.get(x.kind)
}))
.filter(x => x.slug && x.type);
for (const file of files) {
const data = {
changelog,
changelogType: "markdown",
displayName: (parentFileId || !name) ? file.name : name,
parentFileID: parentFileId,
releaseType: channel,
gameVersions: parentFileId ? undefined : versions,
relations: (parentFileId || !projects.length) ? undefined : { projects }
};
const fileId = yield this.upload(id, data, file, token);
if (!parentFileId) {
parentFileId = fileId;
}
}
});
}
upload(id, data, file, token) {
var _a, _b;
return curseforge_publisher_awaiter(this, void 0, void 0, function* () {
while (true) {
try {
return yield uploadFile(id, data, file, token);
}
catch (error) {
if (((_a = error === null || error === void 0 ? void 0 : error.info) === null || _a === void 0 ? void 0 : _a.errorCode) === 1018 && typeof error.info.errorMessage === "string") {
const match = error.info.errorMessage.match(/Invalid slug in project relations: '([^']+)'/);
const projects = (_b = data.relations) === null || _b === void 0 ? void 0 : _b.projects;
if (match && (projects === null || projects === void 0 ? void 0 : projects.length)) {
const invalidSlugIndex = projects.findIndex(x => x.slug === match[1]);
if (invalidSlugIndex !== -1) {
projects.splice(invalidSlugIndex, 1);
continue;
}
}
}
throw error;
}
}
});
}
}
;// CONCATENATED MODULE: ./src/publishing/publisher-factory.ts
class PublisherFactory {
create(target, logger) {
switch (target) {
case publisher_target.GitHub:
return new GitHubPublisher(logger);
case publisher_target.Modrinth:
return new ModrinthPublisher(logger);
case publisher_target.CurseForge:
return new CurseForgePublisher(logger);
default:
throw new Error(`Unknown target "${publisher_target.toString(target)}"`);
}
}
}
;// CONCATENATED MODULE: external "process"
const external_process_namespaceObject = require("process");
var external_process_default = /*#__PURE__*/__nccwpck_require__.n(external_process_namespaceObject);
;// CONCATENATED MODULE: ./src/utils/input-utils.ts
const undefinedValue = "${undefined}";
function getInputAsObject() {
const inputs = Object.entries((external_process_default()).env).filter(([key, _]) => key.startsWith("INPUT_"));
const input = {};
for (const [name, value] of inputs) {
const words = name.substring(6).toLowerCase().split(/[\W_]/).filter(x => x);
init(input, words, value);
}
return input;
}
function init(root, path, value) {
if (value === undefinedValue) {
return;
}
const name = path.reduce((a, b, i) => a + (i === 0 ? b : (b.substring(0, 1).toUpperCase() + b.substring(1))), "");
root[name] = value;
if (path.length === 1) {
return;
}
const innerPath = path[0];
const inner = root[innerPath] ? root[innerPath] : (root[innerPath] = {});
if (typeof inner === "object") {
init(inner, path.slice(1), value);
}
}
2022-01-12 10:27:38 -05:00
;// CONCATENATED MODULE: ./src/utils/sleep.ts
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
;// CONCATENATED MODULE: ./src/utils/function-utils.ts
var function_utils_awaiter = (undefined && undefined.__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());
});
};
function retry({ func, delay = 0, maxAttempts = -1, softErrorPredicate, errorCallback }) {
return function_utils_awaiter(this, void 0, void 0, function* () {
let attempts = 0;
while (true) {
try {
return yield func();
}
catch (e) {
const isSoft = softErrorPredicate ? softErrorPredicate(e) : e === null || e === void 0 ? void 0 : e.soft;
if (!isSoft || maxAttempts >= 0 && ++attempts >= maxAttempts) {
throw e;
}
if (errorCallback) {
errorCallback(e);
}
}
yield sleep(delay);
}
});
}
2021-12-11 08:00:14 -05:00
;// CONCATENATED MODULE: ./src/index.ts
var src_awaiter = (undefined && undefined.__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());
});
};
2022-01-12 10:27:38 -05:00
2021-12-11 08:00:14 -05:00
function main() {
2022-01-12 10:27:38 -05:00
var _a, _b;
2021-12-11 08:00:14 -05:00
return src_awaiter(this, void 0, void 0, function* () {
const commonOptions = getInputAsObject();
const publisherFactory = new PublisherFactory();
const logger = getDefaultLogger();
const publishedTo = new Array();
for (const target of publisher_target.getValues()) {
const targetName = publisher_target.toString(target);
const publisherOptions = commonOptions[targetName.toLowerCase()];
if (!(publisherOptions === null || publisherOptions === void 0 ? void 0 : publisherOptions.token) || typeof publisherOptions.token !== "string") {
continue;
}
const options = Object.assign(Object.assign({}, commonOptions), publisherOptions);
const fileSelector = options.files && (typeof (options.files) === "string" || options.files.primary) ? options.files : gradleOutputSelector;
const files = yield getRequiredFiles(fileSelector);
2022-01-12 10:27:38 -05:00
const retryAttempts = +((_a = options.retry) === null || _a === void 0 ? void 0 : _a["attempts"]) || 0;
const retryDelay = +((_b = options.retry) === null || _b === void 0 ? void 0 : _b["delay"]) || 0;
2021-12-11 08:00:14 -05:00
const publisher = publisherFactory.create(target, logger);
logger.info(`Publishing assets to ${targetName}...`);
const start = new Date();
2022-01-12 10:27:38 -05:00
yield retry({
func: () => publisher.publish(files, options),
maxAttempts: retryAttempts,
delay: retryDelay,
errorCallback: e => {
logger.error(`${e}`);
logger.info(`Retrying to publish assets to ${targetName} in ${retryDelay} ms...`);
}
});
const end = new Date();
logger.info(`Successfully published assets to ${targetName} (in ${end.getTime() - start.getTime()} ms)`);
2021-12-11 08:00:14 -05:00
publishedTo.push(targetName);
}
if (publishedTo.length) {
logger.info(`Your assets have been successfully published to: ${publishedTo.join(", ")}`);
}
else {
logger.warn("You didn't specify any targets, your assets have not been published");
}
});
}
2022-01-12 10:27:38 -05:00
main().catch(error => getDefaultLogger().fatal(error instanceof Error ? `${error}` : `Something went horribly wrong: ${error}`));
2021-12-11 08:00:14 -05:00
/***/ }),
/***/ 2877:
/***/ ((module) => {
module.exports = eval("require")("encoding");
/***/ }),
/***/ 9081:
/***/ ((module) => {
module.exports = eval("require")("stream/web");
/***/ }),
/***/ 8010:
/***/ ((__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) {
try {
Object.assign(globalThis, __nccwpck_require__(9081))
} catch (error) {
// TODO: Remove when only supporting node >= 16.5.0
Object.assign(globalThis, __nccwpck_require__(1452))
}
}
try {
const {Blob} = __nccwpck_require__(4293)
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 */
/***/ }),
/***/ 2357:
/***/ ((module) => {
"use strict";
module.exports = require("assert");
/***/ }),
/***/ 4293:
/***/ ((module) => {
"use strict";
module.exports = require("buffer");
/***/ }),
/***/ 8614:
/***/ ((module) => {
"use strict";
module.exports = require("events");
/***/ }),
/***/ 5747:
/***/ ((module) => {
"use strict";
module.exports = require("fs");
/***/ }),
/***/ 8605:
/***/ ((module) => {
"use strict";
module.exports = require("http");
/***/ }),
/***/ 7211:
/***/ ((module) => {
"use strict";
module.exports = require("https");
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 1631:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("net");
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 2087:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("os");
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 5622:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("path");
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 4213:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("punycode");
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 2413:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("stream");
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ }),
2021-10-01 09:38:36 -04:00
2021-12-11 08:00:14 -05:00
/***/ 4016:
/***/ ((module) => {
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
"use strict";
module.exports = require("tls");
/***/ }),
/***/ 8835:
/***/ ((module) => {
"use strict";
module.exports = require("url");
/***/ }),
/***/ 1669:
/***/ ((module) => {
"use strict";
module.exports = require("util");
/***/ }),
2021-09-26 15:31:45 -04:00
2021-12-11 08:00:14 -05:00
/***/ 5013:
/***/ ((module) => {
"use strict";
module.exports = require("worker_threads");
/***/ }),
/***/ 8761:
/***/ ((module) => {
"use strict";
module.exports = require("zlib");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __nccwpck_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __nccwpck_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // 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/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 = __dirname + "/";
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module doesn't tell about it's top-level declarations so it can't be inlined
2022-01-12 10:27:38 -05:00
/******/ var __webpack_exports__ = __nccwpck_require__(9500);
2021-12-11 08:00:14 -05:00
/******/ module.exports = __webpack_exports__;
/******/
2021-09-26 15:31:45 -04:00
/******/ })()
;
//# sourceMappingURL=index.js.map