github.com/yogeshkumararora/slsa-github-generator@v1.10.1-0.20240520161934-11278bd5afb4/.github/actions/sign-attestations/dist/index.js (about) 1 require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap 2 /******/ var __webpack_modules__ = ({ 3 4 /***/ 3109: 5 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 6 7 "use strict"; 8 9 // Copyright 2023 SLSA Authors 10 // 11 // Licensed under the Apache License, Version 2.0 (the "License"); 12 // you may not use this file except in compliance with the License. 13 // You may obtain a copy of the License at 14 // 15 // http://www.apache.org/licenses/LICENSE-2.0 16 // 17 // Unless required by applicable law or agreed to in writing, software 18 // distributed under the License is distributed on an "AS IS" BASIS, 19 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 // See the License for the specific language governing permissions and 21 // limitations under the License. 22 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 23 if (k2 === undefined) k2 = k; 24 var desc = Object.getOwnPropertyDescriptor(m, k); 25 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 26 desc = { enumerable: true, get: function() { return m[k]; } }; 27 } 28 Object.defineProperty(o, k2, desc); 29 }) : (function(o, m, k, k2) { 30 if (k2 === undefined) k2 = k; 31 o[k2] = m[k]; 32 })); 33 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 34 Object.defineProperty(o, "default", { enumerable: true, value: v }); 35 }) : function(o, v) { 36 o["default"] = v; 37 }); 38 var __importStar = (this && this.__importStar) || function (mod) { 39 if (mod && mod.__esModule) return mod; 40 var result = {}; 41 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 42 __setModuleDefault(result, mod); 43 return result; 44 }; 45 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 46 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 47 return new (P || (P = Promise))(function (resolve, reject) { 48 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 49 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 50 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 51 step((generator = generator.apply(thisArg, _arguments || [])).next()); 52 }); 53 }; 54 Object.defineProperty(exports, "__esModule", ({ value: true })); 55 const core = __importStar(__nccwpck_require__(2186)); 56 const sigstore_1 = __nccwpck_require__(9149); 57 const path = __importStar(__nccwpck_require__(1017)); 58 const tscommon = __importStar(__nccwpck_require__(6634)); 59 function run() { 60 return __awaiter(this, void 0, void 0, function* () { 61 try { 62 /* Test locally: 63 $ env INPUT_ATTESTATIONS="testdata/attestations" \ 64 INPUT_OUTPUT-FOLDER="outputs" \ 65 GITHUB_WORKSPACE="$(pwd)" \ 66 nodejs ./dist/index.js 67 */ 68 // Attestations 69 const attestationFolder = core.getInput("attestations"); 70 const payloadType = core.getInput("payload-type"); 71 // Output folder 72 const outputFolder = core.getInput("output-folder"); 73 tscommon.safeMkdirSync(outputFolder, { recursive: true }); 74 const files = yield tscommon.safePromises_readdir(attestationFolder); 75 for (const file of files) { 76 const fpath = path.join(attestationFolder, file); 77 const stat = yield tscommon.safePromises_stat(fpath); 78 if (stat.isFile()) { 79 core.debug(`Signing ${fpath}...`); 80 const buffer = tscommon.safeReadFileSync(fpath); 81 const bundle = yield (0, sigstore_1.attest)(buffer, payloadType); 82 const bundleStr = JSON.stringify(bundle); 83 const outputPath = path.join(outputFolder, `${path.basename(fpath)}.build.slsa`); 84 // We detect path traversal for outputPath in safeWriteFileSync. 85 tscommon.safeWriteFileSync(outputPath, bundleStr); 86 core.debug(`Wrote signed attestation to '${outputPath}.`); 87 } 88 } 89 } 90 catch (error) { 91 if (error instanceof sigstore_1.InternalError) { 92 core.setFailed(`${error}: ${error.cause}`); 93 } 94 else { 95 core.setFailed(`Unexpected error: ${error}`); 96 } 97 } 98 }); 99 } 100 run(); 101 102 103 /***/ }), 104 105 /***/ 7351: 106 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 107 108 "use strict"; 109 110 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 111 if (k2 === undefined) k2 = k; 112 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); 113 }) : (function(o, m, k, k2) { 114 if (k2 === undefined) k2 = k; 115 o[k2] = m[k]; 116 })); 117 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 118 Object.defineProperty(o, "default", { enumerable: true, value: v }); 119 }) : function(o, v) { 120 o["default"] = v; 121 }); 122 var __importStar = (this && this.__importStar) || function (mod) { 123 if (mod && mod.__esModule) return mod; 124 var result = {}; 125 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 126 __setModuleDefault(result, mod); 127 return result; 128 }; 129 Object.defineProperty(exports, "__esModule", ({ value: true })); 130 exports.issue = exports.issueCommand = void 0; 131 const os = __importStar(__nccwpck_require__(2037)); 132 const utils_1 = __nccwpck_require__(5278); 133 /** 134 * Commands 135 * 136 * Command Format: 137 * ::name key=value,key=value::message 138 * 139 * Examples: 140 * ::warning::This is the message 141 * ::set-env name=MY_VAR::some value 142 */ 143 function issueCommand(command, properties, message) { 144 const cmd = new Command(command, properties, message); 145 process.stdout.write(cmd.toString() + os.EOL); 146 } 147 exports.issueCommand = issueCommand; 148 function issue(name, message = '') { 149 issueCommand(name, {}, message); 150 } 151 exports.issue = issue; 152 const CMD_STRING = '::'; 153 class Command { 154 constructor(command, properties, message) { 155 if (!command) { 156 command = 'missing.command'; 157 } 158 this.command = command; 159 this.properties = properties; 160 this.message = message; 161 } 162 toString() { 163 let cmdStr = CMD_STRING + this.command; 164 if (this.properties && Object.keys(this.properties).length > 0) { 165 cmdStr += ' '; 166 let first = true; 167 for (const key in this.properties) { 168 if (this.properties.hasOwnProperty(key)) { 169 const val = this.properties[key]; 170 if (val) { 171 if (first) { 172 first = false; 173 } 174 else { 175 cmdStr += ','; 176 } 177 cmdStr += `${key}=${escapeProperty(val)}`; 178 } 179 } 180 } 181 } 182 cmdStr += `${CMD_STRING}${escapeData(this.message)}`; 183 return cmdStr; 184 } 185 } 186 function escapeData(s) { 187 return utils_1.toCommandValue(s) 188 .replace(/%/g, '%25') 189 .replace(/\r/g, '%0D') 190 .replace(/\n/g, '%0A'); 191 } 192 function escapeProperty(s) { 193 return utils_1.toCommandValue(s) 194 .replace(/%/g, '%25') 195 .replace(/\r/g, '%0D') 196 .replace(/\n/g, '%0A') 197 .replace(/:/g, '%3A') 198 .replace(/,/g, '%2C'); 199 } 200 //# sourceMappingURL=command.js.map 201 202 /***/ }), 203 204 /***/ 2186: 205 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 206 207 "use strict"; 208 209 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 210 if (k2 === undefined) k2 = k; 211 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); 212 }) : (function(o, m, k, k2) { 213 if (k2 === undefined) k2 = k; 214 o[k2] = m[k]; 215 })); 216 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 217 Object.defineProperty(o, "default", { enumerable: true, value: v }); 218 }) : function(o, v) { 219 o["default"] = v; 220 }); 221 var __importStar = (this && this.__importStar) || function (mod) { 222 if (mod && mod.__esModule) return mod; 223 var result = {}; 224 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 225 __setModuleDefault(result, mod); 226 return result; 227 }; 228 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 229 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 230 return new (P || (P = Promise))(function (resolve, reject) { 231 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 232 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 233 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 234 step((generator = generator.apply(thisArg, _arguments || [])).next()); 235 }); 236 }; 237 Object.defineProperty(exports, "__esModule", ({ value: true })); 238 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; 239 const command_1 = __nccwpck_require__(7351); 240 const file_command_1 = __nccwpck_require__(717); 241 const utils_1 = __nccwpck_require__(5278); 242 const os = __importStar(__nccwpck_require__(2037)); 243 const path = __importStar(__nccwpck_require__(1017)); 244 const oidc_utils_1 = __nccwpck_require__(8041); 245 /** 246 * The code to exit an action 247 */ 248 var ExitCode; 249 (function (ExitCode) { 250 /** 251 * A code indicating that the action was successful 252 */ 253 ExitCode[ExitCode["Success"] = 0] = "Success"; 254 /** 255 * A code indicating that the action was a failure 256 */ 257 ExitCode[ExitCode["Failure"] = 1] = "Failure"; 258 })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); 259 //----------------------------------------------------------------------- 260 // Variables 261 //----------------------------------------------------------------------- 262 /** 263 * Sets env variable for this action and future actions in the job 264 * @param name the name of the variable to set 265 * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify 266 */ 267 // eslint-disable-next-line @typescript-eslint/no-explicit-any 268 function exportVariable(name, val) { 269 const convertedVal = utils_1.toCommandValue(val); 270 process.env[name] = convertedVal; 271 const filePath = process.env['GITHUB_ENV'] || ''; 272 if (filePath) { 273 return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); 274 } 275 command_1.issueCommand('set-env', { name }, convertedVal); 276 } 277 exports.exportVariable = exportVariable; 278 /** 279 * Registers a secret which will get masked from logs 280 * @param secret value of the secret 281 */ 282 function setSecret(secret) { 283 command_1.issueCommand('add-mask', {}, secret); 284 } 285 exports.setSecret = setSecret; 286 /** 287 * Prepends inputPath to the PATH (for this action and future actions) 288 * @param inputPath 289 */ 290 function addPath(inputPath) { 291 const filePath = process.env['GITHUB_PATH'] || ''; 292 if (filePath) { 293 file_command_1.issueFileCommand('PATH', inputPath); 294 } 295 else { 296 command_1.issueCommand('add-path', {}, inputPath); 297 } 298 process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; 299 } 300 exports.addPath = addPath; 301 /** 302 * Gets the value of an input. 303 * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. 304 * Returns an empty string if the value is not defined. 305 * 306 * @param name name of the input to get 307 * @param options optional. See InputOptions. 308 * @returns string 309 */ 310 function getInput(name, options) { 311 const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; 312 if (options && options.required && !val) { 313 throw new Error(`Input required and not supplied: ${name}`); 314 } 315 if (options && options.trimWhitespace === false) { 316 return val; 317 } 318 return val.trim(); 319 } 320 exports.getInput = getInput; 321 /** 322 * Gets the values of an multiline input. Each value is also trimmed. 323 * 324 * @param name name of the input to get 325 * @param options optional. See InputOptions. 326 * @returns string[] 327 * 328 */ 329 function getMultilineInput(name, options) { 330 const inputs = getInput(name, options) 331 .split('\n') 332 .filter(x => x !== ''); 333 if (options && options.trimWhitespace === false) { 334 return inputs; 335 } 336 return inputs.map(input => input.trim()); 337 } 338 exports.getMultilineInput = getMultilineInput; 339 /** 340 * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. 341 * Support boolean input list: `true | True | TRUE | false | False | FALSE` . 342 * The return value is also in boolean type. 343 * ref: https://yaml.org/spec/1.2/spec.html#id2804923 344 * 345 * @param name name of the input to get 346 * @param options optional. See InputOptions. 347 * @returns boolean 348 */ 349 function getBooleanInput(name, options) { 350 const trueValue = ['true', 'True', 'TRUE']; 351 const falseValue = ['false', 'False', 'FALSE']; 352 const val = getInput(name, options); 353 if (trueValue.includes(val)) 354 return true; 355 if (falseValue.includes(val)) 356 return false; 357 throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + 358 `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); 359 } 360 exports.getBooleanInput = getBooleanInput; 361 /** 362 * Sets the value of an output. 363 * 364 * @param name name of the output to set 365 * @param value value to store. Non-string values will be converted to a string via JSON.stringify 366 */ 367 // eslint-disable-next-line @typescript-eslint/no-explicit-any 368 function setOutput(name, value) { 369 const filePath = process.env['GITHUB_OUTPUT'] || ''; 370 if (filePath) { 371 return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); 372 } 373 process.stdout.write(os.EOL); 374 command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); 375 } 376 exports.setOutput = setOutput; 377 /** 378 * Enables or disables the echoing of commands into stdout for the rest of the step. 379 * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. 380 * 381 */ 382 function setCommandEcho(enabled) { 383 command_1.issue('echo', enabled ? 'on' : 'off'); 384 } 385 exports.setCommandEcho = setCommandEcho; 386 //----------------------------------------------------------------------- 387 // Results 388 //----------------------------------------------------------------------- 389 /** 390 * Sets the action status to failed. 391 * When the action exits it will be with an exit code of 1 392 * @param message add error issue message 393 */ 394 function setFailed(message) { 395 process.exitCode = ExitCode.Failure; 396 error(message); 397 } 398 exports.setFailed = setFailed; 399 //----------------------------------------------------------------------- 400 // Logging Commands 401 //----------------------------------------------------------------------- 402 /** 403 * Gets whether Actions Step Debug is on or not 404 */ 405 function isDebug() { 406 return process.env['RUNNER_DEBUG'] === '1'; 407 } 408 exports.isDebug = isDebug; 409 /** 410 * Writes debug message to user log 411 * @param message debug message 412 */ 413 function debug(message) { 414 command_1.issueCommand('debug', {}, message); 415 } 416 exports.debug = debug; 417 /** 418 * Adds an error issue 419 * @param message error issue message. Errors will be converted to string via toString() 420 * @param properties optional properties to add to the annotation. 421 */ 422 function error(message, properties = {}) { 423 command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); 424 } 425 exports.error = error; 426 /** 427 * Adds a warning issue 428 * @param message warning issue message. Errors will be converted to string via toString() 429 * @param properties optional properties to add to the annotation. 430 */ 431 function warning(message, properties = {}) { 432 command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); 433 } 434 exports.warning = warning; 435 /** 436 * Adds a notice issue 437 * @param message notice issue message. Errors will be converted to string via toString() 438 * @param properties optional properties to add to the annotation. 439 */ 440 function notice(message, properties = {}) { 441 command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); 442 } 443 exports.notice = notice; 444 /** 445 * Writes info to log with console.log. 446 * @param message info message 447 */ 448 function info(message) { 449 process.stdout.write(message + os.EOL); 450 } 451 exports.info = info; 452 /** 453 * Begin an output group. 454 * 455 * Output until the next `groupEnd` will be foldable in this group 456 * 457 * @param name The name of the output group 458 */ 459 function startGroup(name) { 460 command_1.issue('group', name); 461 } 462 exports.startGroup = startGroup; 463 /** 464 * End an output group. 465 */ 466 function endGroup() { 467 command_1.issue('endgroup'); 468 } 469 exports.endGroup = endGroup; 470 /** 471 * Wrap an asynchronous function call in a group. 472 * 473 * Returns the same type as the function itself. 474 * 475 * @param name The name of the group 476 * @param fn The function to wrap in the group 477 */ 478 function group(name, fn) { 479 return __awaiter(this, void 0, void 0, function* () { 480 startGroup(name); 481 let result; 482 try { 483 result = yield fn(); 484 } 485 finally { 486 endGroup(); 487 } 488 return result; 489 }); 490 } 491 exports.group = group; 492 //----------------------------------------------------------------------- 493 // Wrapper action state 494 //----------------------------------------------------------------------- 495 /** 496 * Saves state for current action, the state can only be retrieved by this action's post job execution. 497 * 498 * @param name name of the state to store 499 * @param value value to store. Non-string values will be converted to a string via JSON.stringify 500 */ 501 // eslint-disable-next-line @typescript-eslint/no-explicit-any 502 function saveState(name, value) { 503 const filePath = process.env['GITHUB_STATE'] || ''; 504 if (filePath) { 505 return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); 506 } 507 command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); 508 } 509 exports.saveState = saveState; 510 /** 511 * Gets the value of an state set by this action's main execution. 512 * 513 * @param name name of the state to get 514 * @returns string 515 */ 516 function getState(name) { 517 return process.env[`STATE_${name}`] || ''; 518 } 519 exports.getState = getState; 520 function getIDToken(aud) { 521 return __awaiter(this, void 0, void 0, function* () { 522 return yield oidc_utils_1.OidcClient.getIDToken(aud); 523 }); 524 } 525 exports.getIDToken = getIDToken; 526 /** 527 * Summary exports 528 */ 529 var summary_1 = __nccwpck_require__(1327); 530 Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); 531 /** 532 * @deprecated use core.summary 533 */ 534 var summary_2 = __nccwpck_require__(1327); 535 Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); 536 /** 537 * Path exports 538 */ 539 var path_utils_1 = __nccwpck_require__(2981); 540 Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); 541 Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); 542 Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); 543 //# sourceMappingURL=core.js.map 544 545 /***/ }), 546 547 /***/ 717: 548 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 549 550 "use strict"; 551 552 // For internal use, subject to change. 553 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 554 if (k2 === undefined) k2 = k; 555 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); 556 }) : (function(o, m, k, k2) { 557 if (k2 === undefined) k2 = k; 558 o[k2] = m[k]; 559 })); 560 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 561 Object.defineProperty(o, "default", { enumerable: true, value: v }); 562 }) : function(o, v) { 563 o["default"] = v; 564 }); 565 var __importStar = (this && this.__importStar) || function (mod) { 566 if (mod && mod.__esModule) return mod; 567 var result = {}; 568 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 569 __setModuleDefault(result, mod); 570 return result; 571 }; 572 Object.defineProperty(exports, "__esModule", ({ value: true })); 573 exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; 574 // We use any as a valid input type 575 /* eslint-disable @typescript-eslint/no-explicit-any */ 576 const fs = __importStar(__nccwpck_require__(7147)); 577 const os = __importStar(__nccwpck_require__(2037)); 578 const uuid_1 = __nccwpck_require__(5840); 579 const utils_1 = __nccwpck_require__(5278); 580 function issueFileCommand(command, message) { 581 const filePath = process.env[`GITHUB_${command}`]; 582 if (!filePath) { 583 throw new Error(`Unable to find environment variable for file command ${command}`); 584 } 585 if (!fs.existsSync(filePath)) { 586 throw new Error(`Missing file at path: ${filePath}`); 587 } 588 fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { 589 encoding: 'utf8' 590 }); 591 } 592 exports.issueFileCommand = issueFileCommand; 593 function prepareKeyValueMessage(key, value) { 594 const delimiter = `ghadelimiter_${uuid_1.v4()}`; 595 const convertedValue = utils_1.toCommandValue(value); 596 // These should realistically never happen, but just in case someone finds a 597 // way to exploit uuid generation let's not allow keys or values that contain 598 // the delimiter. 599 if (key.includes(delimiter)) { 600 throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); 601 } 602 if (convertedValue.includes(delimiter)) { 603 throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); 604 } 605 return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; 606 } 607 exports.prepareKeyValueMessage = prepareKeyValueMessage; 608 //# sourceMappingURL=file-command.js.map 609 610 /***/ }), 611 612 /***/ 8041: 613 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 614 615 "use strict"; 616 617 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 618 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 619 return new (P || (P = Promise))(function (resolve, reject) { 620 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 621 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 622 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 623 step((generator = generator.apply(thisArg, _arguments || [])).next()); 624 }); 625 }; 626 Object.defineProperty(exports, "__esModule", ({ value: true })); 627 exports.OidcClient = void 0; 628 const http_client_1 = __nccwpck_require__(6255); 629 const auth_1 = __nccwpck_require__(5526); 630 const core_1 = __nccwpck_require__(2186); 631 class OidcClient { 632 static createHttpClient(allowRetry = true, maxRetry = 10) { 633 const requestOptions = { 634 allowRetries: allowRetry, 635 maxRetries: maxRetry 636 }; 637 return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); 638 } 639 static getRequestToken() { 640 const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; 641 if (!token) { 642 throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); 643 } 644 return token; 645 } 646 static getIDTokenUrl() { 647 const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; 648 if (!runtimeUrl) { 649 throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); 650 } 651 return runtimeUrl; 652 } 653 static getCall(id_token_url) { 654 var _a; 655 return __awaiter(this, void 0, void 0, function* () { 656 const httpclient = OidcClient.createHttpClient(); 657 const res = yield httpclient 658 .getJson(id_token_url) 659 .catch(error => { 660 throw new Error(`Failed to get ID Token. \n 661 Error Code : ${error.statusCode}\n 662 Error Message: ${error.message}`); 663 }); 664 const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; 665 if (!id_token) { 666 throw new Error('Response json body do not have ID Token field'); 667 } 668 return id_token; 669 }); 670 } 671 static getIDToken(audience) { 672 return __awaiter(this, void 0, void 0, function* () { 673 try { 674 // New ID Token is requested from action service 675 let id_token_url = OidcClient.getIDTokenUrl(); 676 if (audience) { 677 const encodedAudience = encodeURIComponent(audience); 678 id_token_url = `${id_token_url}&audience=${encodedAudience}`; 679 } 680 core_1.debug(`ID token url is ${id_token_url}`); 681 const id_token = yield OidcClient.getCall(id_token_url); 682 core_1.setSecret(id_token); 683 return id_token; 684 } 685 catch (error) { 686 throw new Error(`Error message: ${error.message}`); 687 } 688 }); 689 } 690 } 691 exports.OidcClient = OidcClient; 692 //# sourceMappingURL=oidc-utils.js.map 693 694 /***/ }), 695 696 /***/ 2981: 697 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 698 699 "use strict"; 700 701 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 702 if (k2 === undefined) k2 = k; 703 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); 704 }) : (function(o, m, k, k2) { 705 if (k2 === undefined) k2 = k; 706 o[k2] = m[k]; 707 })); 708 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 709 Object.defineProperty(o, "default", { enumerable: true, value: v }); 710 }) : function(o, v) { 711 o["default"] = v; 712 }); 713 var __importStar = (this && this.__importStar) || function (mod) { 714 if (mod && mod.__esModule) return mod; 715 var result = {}; 716 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 717 __setModuleDefault(result, mod); 718 return result; 719 }; 720 Object.defineProperty(exports, "__esModule", ({ value: true })); 721 exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; 722 const path = __importStar(__nccwpck_require__(1017)); 723 /** 724 * toPosixPath converts the given path to the posix form. On Windows, \\ will be 725 * replaced with /. 726 * 727 * @param pth. Path to transform. 728 * @return string Posix path. 729 */ 730 function toPosixPath(pth) { 731 return pth.replace(/[\\]/g, '/'); 732 } 733 exports.toPosixPath = toPosixPath; 734 /** 735 * toWin32Path converts the given path to the win32 form. On Linux, / will be 736 * replaced with \\. 737 * 738 * @param pth. Path to transform. 739 * @return string Win32 path. 740 */ 741 function toWin32Path(pth) { 742 return pth.replace(/[/]/g, '\\'); 743 } 744 exports.toWin32Path = toWin32Path; 745 /** 746 * toPlatformPath converts the given path to a platform-specific path. It does 747 * this by replacing instances of / and \ with the platform-specific path 748 * separator. 749 * 750 * @param pth The path to platformize. 751 * @return string The platform-specific path. 752 */ 753 function toPlatformPath(pth) { 754 return pth.replace(/[/\\]/g, path.sep); 755 } 756 exports.toPlatformPath = toPlatformPath; 757 //# sourceMappingURL=path-utils.js.map 758 759 /***/ }), 760 761 /***/ 1327: 762 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 763 764 "use strict"; 765 766 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 767 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 768 return new (P || (P = Promise))(function (resolve, reject) { 769 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 770 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 771 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 772 step((generator = generator.apply(thisArg, _arguments || [])).next()); 773 }); 774 }; 775 Object.defineProperty(exports, "__esModule", ({ value: true })); 776 exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; 777 const os_1 = __nccwpck_require__(2037); 778 const fs_1 = __nccwpck_require__(7147); 779 const { access, appendFile, writeFile } = fs_1.promises; 780 exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; 781 exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; 782 class Summary { 783 constructor() { 784 this._buffer = ''; 785 } 786 /** 787 * Finds the summary file path from the environment, rejects if env var is not found or file does not exist 788 * Also checks r/w permissions. 789 * 790 * @returns step summary file path 791 */ 792 filePath() { 793 return __awaiter(this, void 0, void 0, function* () { 794 if (this._filePath) { 795 return this._filePath; 796 } 797 const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; 798 if (!pathFromEnv) { 799 throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); 800 } 801 try { 802 yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); 803 } 804 catch (_a) { 805 throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); 806 } 807 this._filePath = pathFromEnv; 808 return this._filePath; 809 }); 810 } 811 /** 812 * Wraps content in an HTML tag, adding any HTML attributes 813 * 814 * @param {string} tag HTML tag to wrap 815 * @param {string | null} content content within the tag 816 * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add 817 * 818 * @returns {string} content wrapped in HTML element 819 */ 820 wrap(tag, content, attrs = {}) { 821 const htmlAttrs = Object.entries(attrs) 822 .map(([key, value]) => ` ${key}="${value}"`) 823 .join(''); 824 if (!content) { 825 return `<${tag}${htmlAttrs}>`; 826 } 827 return `<${tag}${htmlAttrs}>${content}</${tag}>`; 828 } 829 /** 830 * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. 831 * 832 * @param {SummaryWriteOptions} [options] (optional) options for write operation 833 * 834 * @returns {Promise<Summary>} summary instance 835 */ 836 write(options) { 837 return __awaiter(this, void 0, void 0, function* () { 838 const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); 839 const filePath = yield this.filePath(); 840 const writeFunc = overwrite ? writeFile : appendFile; 841 yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); 842 return this.emptyBuffer(); 843 }); 844 } 845 /** 846 * Clears the summary buffer and wipes the summary file 847 * 848 * @returns {Summary} summary instance 849 */ 850 clear() { 851 return __awaiter(this, void 0, void 0, function* () { 852 return this.emptyBuffer().write({ overwrite: true }); 853 }); 854 } 855 /** 856 * Returns the current summary buffer as a string 857 * 858 * @returns {string} string of summary buffer 859 */ 860 stringify() { 861 return this._buffer; 862 } 863 /** 864 * If the summary buffer is empty 865 * 866 * @returns {boolen} true if the buffer is empty 867 */ 868 isEmptyBuffer() { 869 return this._buffer.length === 0; 870 } 871 /** 872 * Resets the summary buffer without writing to summary file 873 * 874 * @returns {Summary} summary instance 875 */ 876 emptyBuffer() { 877 this._buffer = ''; 878 return this; 879 } 880 /** 881 * Adds raw text to the summary buffer 882 * 883 * @param {string} text content to add 884 * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) 885 * 886 * @returns {Summary} summary instance 887 */ 888 addRaw(text, addEOL = false) { 889 this._buffer += text; 890 return addEOL ? this.addEOL() : this; 891 } 892 /** 893 * Adds the operating system-specific end-of-line marker to the buffer 894 * 895 * @returns {Summary} summary instance 896 */ 897 addEOL() { 898 return this.addRaw(os_1.EOL); 899 } 900 /** 901 * Adds an HTML codeblock to the summary buffer 902 * 903 * @param {string} code content to render within fenced code block 904 * @param {string} lang (optional) language to syntax highlight code 905 * 906 * @returns {Summary} summary instance 907 */ 908 addCodeBlock(code, lang) { 909 const attrs = Object.assign({}, (lang && { lang })); 910 const element = this.wrap('pre', this.wrap('code', code), attrs); 911 return this.addRaw(element).addEOL(); 912 } 913 /** 914 * Adds an HTML list to the summary buffer 915 * 916 * @param {string[]} items list of items to render 917 * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) 918 * 919 * @returns {Summary} summary instance 920 */ 921 addList(items, ordered = false) { 922 const tag = ordered ? 'ol' : 'ul'; 923 const listItems = items.map(item => this.wrap('li', item)).join(''); 924 const element = this.wrap(tag, listItems); 925 return this.addRaw(element).addEOL(); 926 } 927 /** 928 * Adds an HTML table to the summary buffer 929 * 930 * @param {SummaryTableCell[]} rows table rows 931 * 932 * @returns {Summary} summary instance 933 */ 934 addTable(rows) { 935 const tableBody = rows 936 .map(row => { 937 const cells = row 938 .map(cell => { 939 if (typeof cell === 'string') { 940 return this.wrap('td', cell); 941 } 942 const { header, data, colspan, rowspan } = cell; 943 const tag = header ? 'th' : 'td'; 944 const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); 945 return this.wrap(tag, data, attrs); 946 }) 947 .join(''); 948 return this.wrap('tr', cells); 949 }) 950 .join(''); 951 const element = this.wrap('table', tableBody); 952 return this.addRaw(element).addEOL(); 953 } 954 /** 955 * Adds a collapsable HTML details element to the summary buffer 956 * 957 * @param {string} label text for the closed state 958 * @param {string} content collapsable content 959 * 960 * @returns {Summary} summary instance 961 */ 962 addDetails(label, content) { 963 const element = this.wrap('details', this.wrap('summary', label) + content); 964 return this.addRaw(element).addEOL(); 965 } 966 /** 967 * Adds an HTML image tag to the summary buffer 968 * 969 * @param {string} src path to the image you to embed 970 * @param {string} alt text description of the image 971 * @param {SummaryImageOptions} options (optional) addition image attributes 972 * 973 * @returns {Summary} summary instance 974 */ 975 addImage(src, alt, options) { 976 const { width, height } = options || {}; 977 const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); 978 const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); 979 return this.addRaw(element).addEOL(); 980 } 981 /** 982 * Adds an HTML section heading element 983 * 984 * @param {string} text heading text 985 * @param {number | string} [level=1] (optional) the heading level, default: 1 986 * 987 * @returns {Summary} summary instance 988 */ 989 addHeading(text, level) { 990 const tag = `h${level}`; 991 const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) 992 ? tag 993 : 'h1'; 994 const element = this.wrap(allowedTag, text); 995 return this.addRaw(element).addEOL(); 996 } 997 /** 998 * Adds an HTML thematic break (<hr>) to the summary buffer 999 * 1000 * @returns {Summary} summary instance 1001 */ 1002 addSeparator() { 1003 const element = this.wrap('hr', null); 1004 return this.addRaw(element).addEOL(); 1005 } 1006 /** 1007 * Adds an HTML line break (<br>) to the summary buffer 1008 * 1009 * @returns {Summary} summary instance 1010 */ 1011 addBreak() { 1012 const element = this.wrap('br', null); 1013 return this.addRaw(element).addEOL(); 1014 } 1015 /** 1016 * Adds an HTML blockquote to the summary buffer 1017 * 1018 * @param {string} text quote text 1019 * @param {string} cite (optional) citation url 1020 * 1021 * @returns {Summary} summary instance 1022 */ 1023 addQuote(text, cite) { 1024 const attrs = Object.assign({}, (cite && { cite })); 1025 const element = this.wrap('blockquote', text, attrs); 1026 return this.addRaw(element).addEOL(); 1027 } 1028 /** 1029 * Adds an HTML anchor tag to the summary buffer 1030 * 1031 * @param {string} text link text/content 1032 * @param {string} href hyperlink 1033 * 1034 * @returns {Summary} summary instance 1035 */ 1036 addLink(text, href) { 1037 const element = this.wrap('a', text, { href }); 1038 return this.addRaw(element).addEOL(); 1039 } 1040 } 1041 const _summary = new Summary(); 1042 /** 1043 * @deprecated use `core.summary` 1044 */ 1045 exports.markdownSummary = _summary; 1046 exports.summary = _summary; 1047 //# sourceMappingURL=summary.js.map 1048 1049 /***/ }), 1050 1051 /***/ 5278: 1052 /***/ ((__unused_webpack_module, exports) => { 1053 1054 "use strict"; 1055 1056 // We use any as a valid input type 1057 /* eslint-disable @typescript-eslint/no-explicit-any */ 1058 Object.defineProperty(exports, "__esModule", ({ value: true })); 1059 exports.toCommandProperties = exports.toCommandValue = void 0; 1060 /** 1061 * Sanitizes an input into a string so it can be passed into issueCommand safely 1062 * @param input input to sanitize into a string 1063 */ 1064 function toCommandValue(input) { 1065 if (input === null || input === undefined) { 1066 return ''; 1067 } 1068 else if (typeof input === 'string' || input instanceof String) { 1069 return input; 1070 } 1071 return JSON.stringify(input); 1072 } 1073 exports.toCommandValue = toCommandValue; 1074 /** 1075 * 1076 * @param annotationProperties 1077 * @returns The command properties to send with the actual annotation command 1078 * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 1079 */ 1080 function toCommandProperties(annotationProperties) { 1081 if (!Object.keys(annotationProperties).length) { 1082 return {}; 1083 } 1084 return { 1085 title: annotationProperties.title, 1086 file: annotationProperties.file, 1087 line: annotationProperties.startLine, 1088 endLine: annotationProperties.endLine, 1089 col: annotationProperties.startColumn, 1090 endColumn: annotationProperties.endColumn 1091 }; 1092 } 1093 exports.toCommandProperties = toCommandProperties; 1094 //# sourceMappingURL=utils.js.map 1095 1096 /***/ }), 1097 1098 /***/ 5526: 1099 /***/ (function(__unused_webpack_module, exports) { 1100 1101 "use strict"; 1102 1103 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 1104 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 1105 return new (P || (P = Promise))(function (resolve, reject) { 1106 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 1107 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 1108 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 1109 step((generator = generator.apply(thisArg, _arguments || [])).next()); 1110 }); 1111 }; 1112 Object.defineProperty(exports, "__esModule", ({ value: true })); 1113 exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; 1114 class BasicCredentialHandler { 1115 constructor(username, password) { 1116 this.username = username; 1117 this.password = password; 1118 } 1119 prepareRequest(options) { 1120 if (!options.headers) { 1121 throw Error('The request has no headers'); 1122 } 1123 options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; 1124 } 1125 // This handler cannot handle 401 1126 canHandleAuthentication() { 1127 return false; 1128 } 1129 handleAuthentication() { 1130 return __awaiter(this, void 0, void 0, function* () { 1131 throw new Error('not implemented'); 1132 }); 1133 } 1134 } 1135 exports.BasicCredentialHandler = BasicCredentialHandler; 1136 class BearerCredentialHandler { 1137 constructor(token) { 1138 this.token = token; 1139 } 1140 // currently implements pre-authorization 1141 // TODO: support preAuth = false where it hooks on 401 1142 prepareRequest(options) { 1143 if (!options.headers) { 1144 throw Error('The request has no headers'); 1145 } 1146 options.headers['Authorization'] = `Bearer ${this.token}`; 1147 } 1148 // This handler cannot handle 401 1149 canHandleAuthentication() { 1150 return false; 1151 } 1152 handleAuthentication() { 1153 return __awaiter(this, void 0, void 0, function* () { 1154 throw new Error('not implemented'); 1155 }); 1156 } 1157 } 1158 exports.BearerCredentialHandler = BearerCredentialHandler; 1159 class PersonalAccessTokenCredentialHandler { 1160 constructor(token) { 1161 this.token = token; 1162 } 1163 // currently implements pre-authorization 1164 // TODO: support preAuth = false where it hooks on 401 1165 prepareRequest(options) { 1166 if (!options.headers) { 1167 throw Error('The request has no headers'); 1168 } 1169 options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; 1170 } 1171 // This handler cannot handle 401 1172 canHandleAuthentication() { 1173 return false; 1174 } 1175 handleAuthentication() { 1176 return __awaiter(this, void 0, void 0, function* () { 1177 throw new Error('not implemented'); 1178 }); 1179 } 1180 } 1181 exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; 1182 //# sourceMappingURL=auth.js.map 1183 1184 /***/ }), 1185 1186 /***/ 6255: 1187 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 1188 1189 "use strict"; 1190 1191 /* eslint-disable @typescript-eslint/no-explicit-any */ 1192 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 1193 if (k2 === undefined) k2 = k; 1194 var desc = Object.getOwnPropertyDescriptor(m, k); 1195 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 1196 desc = { enumerable: true, get: function() { return m[k]; } }; 1197 } 1198 Object.defineProperty(o, k2, desc); 1199 }) : (function(o, m, k, k2) { 1200 if (k2 === undefined) k2 = k; 1201 o[k2] = m[k]; 1202 })); 1203 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 1204 Object.defineProperty(o, "default", { enumerable: true, value: v }); 1205 }) : function(o, v) { 1206 o["default"] = v; 1207 }); 1208 var __importStar = (this && this.__importStar) || function (mod) { 1209 if (mod && mod.__esModule) return mod; 1210 var result = {}; 1211 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 1212 __setModuleDefault(result, mod); 1213 return result; 1214 }; 1215 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 1216 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 1217 return new (P || (P = Promise))(function (resolve, reject) { 1218 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 1219 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 1220 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 1221 step((generator = generator.apply(thisArg, _arguments || [])).next()); 1222 }); 1223 }; 1224 Object.defineProperty(exports, "__esModule", ({ value: true })); 1225 exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; 1226 const http = __importStar(__nccwpck_require__(3685)); 1227 const https = __importStar(__nccwpck_require__(5687)); 1228 const pm = __importStar(__nccwpck_require__(9835)); 1229 const tunnel = __importStar(__nccwpck_require__(4294)); 1230 const undici_1 = __nccwpck_require__(1773); 1231 var HttpCodes; 1232 (function (HttpCodes) { 1233 HttpCodes[HttpCodes["OK"] = 200] = "OK"; 1234 HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; 1235 HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; 1236 HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; 1237 HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; 1238 HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; 1239 HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; 1240 HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; 1241 HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; 1242 HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; 1243 HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; 1244 HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; 1245 HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; 1246 HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; 1247 HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; 1248 HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; 1249 HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; 1250 HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; 1251 HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; 1252 HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; 1253 HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; 1254 HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; 1255 HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; 1256 HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; 1257 HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; 1258 HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; 1259 HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; 1260 })(HttpCodes || (exports.HttpCodes = HttpCodes = {})); 1261 var Headers; 1262 (function (Headers) { 1263 Headers["Accept"] = "accept"; 1264 Headers["ContentType"] = "content-type"; 1265 })(Headers || (exports.Headers = Headers = {})); 1266 var MediaTypes; 1267 (function (MediaTypes) { 1268 MediaTypes["ApplicationJson"] = "application/json"; 1269 })(MediaTypes || (exports.MediaTypes = MediaTypes = {})); 1270 /** 1271 * Returns the proxy URL, depending upon the supplied url and proxy environment variables. 1272 * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com 1273 */ 1274 function getProxyUrl(serverUrl) { 1275 const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); 1276 return proxyUrl ? proxyUrl.href : ''; 1277 } 1278 exports.getProxyUrl = getProxyUrl; 1279 const HttpRedirectCodes = [ 1280 HttpCodes.MovedPermanently, 1281 HttpCodes.ResourceMoved, 1282 HttpCodes.SeeOther, 1283 HttpCodes.TemporaryRedirect, 1284 HttpCodes.PermanentRedirect 1285 ]; 1286 const HttpResponseRetryCodes = [ 1287 HttpCodes.BadGateway, 1288 HttpCodes.ServiceUnavailable, 1289 HttpCodes.GatewayTimeout 1290 ]; 1291 const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; 1292 const ExponentialBackoffCeiling = 10; 1293 const ExponentialBackoffTimeSlice = 5; 1294 class HttpClientError extends Error { 1295 constructor(message, statusCode) { 1296 super(message); 1297 this.name = 'HttpClientError'; 1298 this.statusCode = statusCode; 1299 Object.setPrototypeOf(this, HttpClientError.prototype); 1300 } 1301 } 1302 exports.HttpClientError = HttpClientError; 1303 class HttpClientResponse { 1304 constructor(message) { 1305 this.message = message; 1306 } 1307 readBody() { 1308 return __awaiter(this, void 0, void 0, function* () { 1309 return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { 1310 let output = Buffer.alloc(0); 1311 this.message.on('data', (chunk) => { 1312 output = Buffer.concat([output, chunk]); 1313 }); 1314 this.message.on('end', () => { 1315 resolve(output.toString()); 1316 }); 1317 })); 1318 }); 1319 } 1320 readBodyBuffer() { 1321 return __awaiter(this, void 0, void 0, function* () { 1322 return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { 1323 const chunks = []; 1324 this.message.on('data', (chunk) => { 1325 chunks.push(chunk); 1326 }); 1327 this.message.on('end', () => { 1328 resolve(Buffer.concat(chunks)); 1329 }); 1330 })); 1331 }); 1332 } 1333 } 1334 exports.HttpClientResponse = HttpClientResponse; 1335 function isHttps(requestUrl) { 1336 const parsedUrl = new URL(requestUrl); 1337 return parsedUrl.protocol === 'https:'; 1338 } 1339 exports.isHttps = isHttps; 1340 class HttpClient { 1341 constructor(userAgent, handlers, requestOptions) { 1342 this._ignoreSslError = false; 1343 this._allowRedirects = true; 1344 this._allowRedirectDowngrade = false; 1345 this._maxRedirects = 50; 1346 this._allowRetries = false; 1347 this._maxRetries = 1; 1348 this._keepAlive = false; 1349 this._disposed = false; 1350 this.userAgent = userAgent; 1351 this.handlers = handlers || []; 1352 this.requestOptions = requestOptions; 1353 if (requestOptions) { 1354 if (requestOptions.ignoreSslError != null) { 1355 this._ignoreSslError = requestOptions.ignoreSslError; 1356 } 1357 this._socketTimeout = requestOptions.socketTimeout; 1358 if (requestOptions.allowRedirects != null) { 1359 this._allowRedirects = requestOptions.allowRedirects; 1360 } 1361 if (requestOptions.allowRedirectDowngrade != null) { 1362 this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; 1363 } 1364 if (requestOptions.maxRedirects != null) { 1365 this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); 1366 } 1367 if (requestOptions.keepAlive != null) { 1368 this._keepAlive = requestOptions.keepAlive; 1369 } 1370 if (requestOptions.allowRetries != null) { 1371 this._allowRetries = requestOptions.allowRetries; 1372 } 1373 if (requestOptions.maxRetries != null) { 1374 this._maxRetries = requestOptions.maxRetries; 1375 } 1376 } 1377 } 1378 options(requestUrl, additionalHeaders) { 1379 return __awaiter(this, void 0, void 0, function* () { 1380 return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); 1381 }); 1382 } 1383 get(requestUrl, additionalHeaders) { 1384 return __awaiter(this, void 0, void 0, function* () { 1385 return this.request('GET', requestUrl, null, additionalHeaders || {}); 1386 }); 1387 } 1388 del(requestUrl, additionalHeaders) { 1389 return __awaiter(this, void 0, void 0, function* () { 1390 return this.request('DELETE', requestUrl, null, additionalHeaders || {}); 1391 }); 1392 } 1393 post(requestUrl, data, additionalHeaders) { 1394 return __awaiter(this, void 0, void 0, function* () { 1395 return this.request('POST', requestUrl, data, additionalHeaders || {}); 1396 }); 1397 } 1398 patch(requestUrl, data, additionalHeaders) { 1399 return __awaiter(this, void 0, void 0, function* () { 1400 return this.request('PATCH', requestUrl, data, additionalHeaders || {}); 1401 }); 1402 } 1403 put(requestUrl, data, additionalHeaders) { 1404 return __awaiter(this, void 0, void 0, function* () { 1405 return this.request('PUT', requestUrl, data, additionalHeaders || {}); 1406 }); 1407 } 1408 head(requestUrl, additionalHeaders) { 1409 return __awaiter(this, void 0, void 0, function* () { 1410 return this.request('HEAD', requestUrl, null, additionalHeaders || {}); 1411 }); 1412 } 1413 sendStream(verb, requestUrl, stream, additionalHeaders) { 1414 return __awaiter(this, void 0, void 0, function* () { 1415 return this.request(verb, requestUrl, stream, additionalHeaders); 1416 }); 1417 } 1418 /** 1419 * Gets a typed object from an endpoint 1420 * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise 1421 */ 1422 getJson(requestUrl, additionalHeaders = {}) { 1423 return __awaiter(this, void 0, void 0, function* () { 1424 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); 1425 const res = yield this.get(requestUrl, additionalHeaders); 1426 return this._processResponse(res, this.requestOptions); 1427 }); 1428 } 1429 postJson(requestUrl, obj, additionalHeaders = {}) { 1430 return __awaiter(this, void 0, void 0, function* () { 1431 const data = JSON.stringify(obj, null, 2); 1432 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); 1433 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); 1434 const res = yield this.post(requestUrl, data, additionalHeaders); 1435 return this._processResponse(res, this.requestOptions); 1436 }); 1437 } 1438 putJson(requestUrl, obj, additionalHeaders = {}) { 1439 return __awaiter(this, void 0, void 0, function* () { 1440 const data = JSON.stringify(obj, null, 2); 1441 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); 1442 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); 1443 const res = yield this.put(requestUrl, data, additionalHeaders); 1444 return this._processResponse(res, this.requestOptions); 1445 }); 1446 } 1447 patchJson(requestUrl, obj, additionalHeaders = {}) { 1448 return __awaiter(this, void 0, void 0, function* () { 1449 const data = JSON.stringify(obj, null, 2); 1450 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); 1451 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); 1452 const res = yield this.patch(requestUrl, data, additionalHeaders); 1453 return this._processResponse(res, this.requestOptions); 1454 }); 1455 } 1456 /** 1457 * Makes a raw http request. 1458 * All other methods such as get, post, patch, and request ultimately call this. 1459 * Prefer get, del, post and patch 1460 */ 1461 request(verb, requestUrl, data, headers) { 1462 return __awaiter(this, void 0, void 0, function* () { 1463 if (this._disposed) { 1464 throw new Error('Client has already been disposed.'); 1465 } 1466 const parsedUrl = new URL(requestUrl); 1467 let info = this._prepareRequest(verb, parsedUrl, headers); 1468 // Only perform retries on reads since writes may not be idempotent. 1469 const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) 1470 ? this._maxRetries + 1 1471 : 1; 1472 let numTries = 0; 1473 let response; 1474 do { 1475 response = yield this.requestRaw(info, data); 1476 // Check if it's an authentication challenge 1477 if (response && 1478 response.message && 1479 response.message.statusCode === HttpCodes.Unauthorized) { 1480 let authenticationHandler; 1481 for (const handler of this.handlers) { 1482 if (handler.canHandleAuthentication(response)) { 1483 authenticationHandler = handler; 1484 break; 1485 } 1486 } 1487 if (authenticationHandler) { 1488 return authenticationHandler.handleAuthentication(this, info, data); 1489 } 1490 else { 1491 // We have received an unauthorized response but have no handlers to handle it. 1492 // Let the response return to the caller. 1493 return response; 1494 } 1495 } 1496 let redirectsRemaining = this._maxRedirects; 1497 while (response.message.statusCode && 1498 HttpRedirectCodes.includes(response.message.statusCode) && 1499 this._allowRedirects && 1500 redirectsRemaining > 0) { 1501 const redirectUrl = response.message.headers['location']; 1502 if (!redirectUrl) { 1503 // if there's no location to redirect to, we won't 1504 break; 1505 } 1506 const parsedRedirectUrl = new URL(redirectUrl); 1507 if (parsedUrl.protocol === 'https:' && 1508 parsedUrl.protocol !== parsedRedirectUrl.protocol && 1509 !this._allowRedirectDowngrade) { 1510 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.'); 1511 } 1512 // we need to finish reading the response before reassigning response 1513 // which will leak the open socket. 1514 yield response.readBody(); 1515 // strip authorization header if redirected to a different hostname 1516 if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { 1517 for (const header in headers) { 1518 // header names are case insensitive 1519 if (header.toLowerCase() === 'authorization') { 1520 delete headers[header]; 1521 } 1522 } 1523 } 1524 // let's make the request with the new redirectUrl 1525 info = this._prepareRequest(verb, parsedRedirectUrl, headers); 1526 response = yield this.requestRaw(info, data); 1527 redirectsRemaining--; 1528 } 1529 if (!response.message.statusCode || 1530 !HttpResponseRetryCodes.includes(response.message.statusCode)) { 1531 // If not a retry code, return immediately instead of retrying 1532 return response; 1533 } 1534 numTries += 1; 1535 if (numTries < maxTries) { 1536 yield response.readBody(); 1537 yield this._performExponentialBackoff(numTries); 1538 } 1539 } while (numTries < maxTries); 1540 return response; 1541 }); 1542 } 1543 /** 1544 * Needs to be called if keepAlive is set to true in request options. 1545 */ 1546 dispose() { 1547 if (this._agent) { 1548 this._agent.destroy(); 1549 } 1550 this._disposed = true; 1551 } 1552 /** 1553 * Raw request. 1554 * @param info 1555 * @param data 1556 */ 1557 requestRaw(info, data) { 1558 return __awaiter(this, void 0, void 0, function* () { 1559 return new Promise((resolve, reject) => { 1560 function callbackForResult(err, res) { 1561 if (err) { 1562 reject(err); 1563 } 1564 else if (!res) { 1565 // If `err` is not passed, then `res` must be passed. 1566 reject(new Error('Unknown error')); 1567 } 1568 else { 1569 resolve(res); 1570 } 1571 } 1572 this.requestRawWithCallback(info, data, callbackForResult); 1573 }); 1574 }); 1575 } 1576 /** 1577 * Raw request with callback. 1578 * @param info 1579 * @param data 1580 * @param onResult 1581 */ 1582 requestRawWithCallback(info, data, onResult) { 1583 if (typeof data === 'string') { 1584 if (!info.options.headers) { 1585 info.options.headers = {}; 1586 } 1587 info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); 1588 } 1589 let callbackCalled = false; 1590 function handleResult(err, res) { 1591 if (!callbackCalled) { 1592 callbackCalled = true; 1593 onResult(err, res); 1594 } 1595 } 1596 const req = info.httpModule.request(info.options, (msg) => { 1597 const res = new HttpClientResponse(msg); 1598 handleResult(undefined, res); 1599 }); 1600 let socket; 1601 req.on('socket', sock => { 1602 socket = sock; 1603 }); 1604 // If we ever get disconnected, we want the socket to timeout eventually 1605 req.setTimeout(this._socketTimeout || 3 * 60000, () => { 1606 if (socket) { 1607 socket.end(); 1608 } 1609 handleResult(new Error(`Request timeout: ${info.options.path}`)); 1610 }); 1611 req.on('error', function (err) { 1612 // err has statusCode property 1613 // res should have headers 1614 handleResult(err); 1615 }); 1616 if (data && typeof data === 'string') { 1617 req.write(data, 'utf8'); 1618 } 1619 if (data && typeof data !== 'string') { 1620 data.on('close', function () { 1621 req.end(); 1622 }); 1623 data.pipe(req); 1624 } 1625 else { 1626 req.end(); 1627 } 1628 } 1629 /** 1630 * Gets an http agent. This function is useful when you need an http agent that handles 1631 * routing through a proxy server - depending upon the url and proxy environment variables. 1632 * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com 1633 */ 1634 getAgent(serverUrl) { 1635 const parsedUrl = new URL(serverUrl); 1636 return this._getAgent(parsedUrl); 1637 } 1638 getAgentDispatcher(serverUrl) { 1639 const parsedUrl = new URL(serverUrl); 1640 const proxyUrl = pm.getProxyUrl(parsedUrl); 1641 const useProxy = proxyUrl && proxyUrl.hostname; 1642 if (!useProxy) { 1643 return; 1644 } 1645 return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); 1646 } 1647 _prepareRequest(method, requestUrl, headers) { 1648 const info = {}; 1649 info.parsedUrl = requestUrl; 1650 const usingSsl = info.parsedUrl.protocol === 'https:'; 1651 info.httpModule = usingSsl ? https : http; 1652 const defaultPort = usingSsl ? 443 : 80; 1653 info.options = {}; 1654 info.options.host = info.parsedUrl.hostname; 1655 info.options.port = info.parsedUrl.port 1656 ? parseInt(info.parsedUrl.port) 1657 : defaultPort; 1658 info.options.path = 1659 (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); 1660 info.options.method = method; 1661 info.options.headers = this._mergeHeaders(headers); 1662 if (this.userAgent != null) { 1663 info.options.headers['user-agent'] = this.userAgent; 1664 } 1665 info.options.agent = this._getAgent(info.parsedUrl); 1666 // gives handlers an opportunity to participate 1667 if (this.handlers) { 1668 for (const handler of this.handlers) { 1669 handler.prepareRequest(info.options); 1670 } 1671 } 1672 return info; 1673 } 1674 _mergeHeaders(headers) { 1675 if (this.requestOptions && this.requestOptions.headers) { 1676 return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); 1677 } 1678 return lowercaseKeys(headers || {}); 1679 } 1680 _getExistingOrDefaultHeader(additionalHeaders, header, _default) { 1681 let clientHeader; 1682 if (this.requestOptions && this.requestOptions.headers) { 1683 clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; 1684 } 1685 return additionalHeaders[header] || clientHeader || _default; 1686 } 1687 _getAgent(parsedUrl) { 1688 let agent; 1689 const proxyUrl = pm.getProxyUrl(parsedUrl); 1690 const useProxy = proxyUrl && proxyUrl.hostname; 1691 if (this._keepAlive && useProxy) { 1692 agent = this._proxyAgent; 1693 } 1694 if (!useProxy) { 1695 agent = this._agent; 1696 } 1697 // if agent is already assigned use that agent. 1698 if (agent) { 1699 return agent; 1700 } 1701 const usingSsl = parsedUrl.protocol === 'https:'; 1702 let maxSockets = 100; 1703 if (this.requestOptions) { 1704 maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; 1705 } 1706 // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. 1707 if (proxyUrl && proxyUrl.hostname) { 1708 const agentOptions = { 1709 maxSockets, 1710 keepAlive: this._keepAlive, 1711 proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { 1712 proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` 1713 })), { host: proxyUrl.hostname, port: proxyUrl.port }) 1714 }; 1715 let tunnelAgent; 1716 const overHttps = proxyUrl.protocol === 'https:'; 1717 if (usingSsl) { 1718 tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; 1719 } 1720 else { 1721 tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; 1722 } 1723 agent = tunnelAgent(agentOptions); 1724 this._proxyAgent = agent; 1725 } 1726 // if tunneling agent isn't assigned create a new agent 1727 if (!agent) { 1728 const options = { keepAlive: this._keepAlive, maxSockets }; 1729 agent = usingSsl ? new https.Agent(options) : new http.Agent(options); 1730 this._agent = agent; 1731 } 1732 if (usingSsl && this._ignoreSslError) { 1733 // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process 1734 // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options 1735 // we have to cast it to any and change it directly 1736 agent.options = Object.assign(agent.options || {}, { 1737 rejectUnauthorized: false 1738 }); 1739 } 1740 return agent; 1741 } 1742 _getProxyAgentDispatcher(parsedUrl, proxyUrl) { 1743 let proxyAgent; 1744 if (this._keepAlive) { 1745 proxyAgent = this._proxyAgentDispatcher; 1746 } 1747 // if agent is already assigned use that agent. 1748 if (proxyAgent) { 1749 return proxyAgent; 1750 } 1751 const usingSsl = parsedUrl.protocol === 'https:'; 1752 proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { 1753 token: `${proxyUrl.username}:${proxyUrl.password}` 1754 }))); 1755 this._proxyAgentDispatcher = proxyAgent; 1756 if (usingSsl && this._ignoreSslError) { 1757 // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process 1758 // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options 1759 // we have to cast it to any and change it directly 1760 proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { 1761 rejectUnauthorized: false 1762 }); 1763 } 1764 return proxyAgent; 1765 } 1766 _performExponentialBackoff(retryNumber) { 1767 return __awaiter(this, void 0, void 0, function* () { 1768 retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); 1769 const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); 1770 return new Promise(resolve => setTimeout(() => resolve(), ms)); 1771 }); 1772 } 1773 _processResponse(res, options) { 1774 return __awaiter(this, void 0, void 0, function* () { 1775 return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { 1776 const statusCode = res.message.statusCode || 0; 1777 const response = { 1778 statusCode, 1779 result: null, 1780 headers: {} 1781 }; 1782 // not found leads to null obj returned 1783 if (statusCode === HttpCodes.NotFound) { 1784 resolve(response); 1785 } 1786 // get the result from the body 1787 function dateTimeDeserializer(key, value) { 1788 if (typeof value === 'string') { 1789 const a = new Date(value); 1790 if (!isNaN(a.valueOf())) { 1791 return a; 1792 } 1793 } 1794 return value; 1795 } 1796 let obj; 1797 let contents; 1798 try { 1799 contents = yield res.readBody(); 1800 if (contents && contents.length > 0) { 1801 if (options && options.deserializeDates) { 1802 obj = JSON.parse(contents, dateTimeDeserializer); 1803 } 1804 else { 1805 obj = JSON.parse(contents); 1806 } 1807 response.result = obj; 1808 } 1809 response.headers = res.message.headers; 1810 } 1811 catch (err) { 1812 // Invalid resource (contents not json); leaving result obj null 1813 } 1814 // note that 3xx redirects are handled by the http layer. 1815 if (statusCode > 299) { 1816 let msg; 1817 // if exception/error in body, attempt to get better error 1818 if (obj && obj.message) { 1819 msg = obj.message; 1820 } 1821 else if (contents && contents.length > 0) { 1822 // it may be the case that the exception is in the body message as string 1823 msg = contents; 1824 } 1825 else { 1826 msg = `Failed request: (${statusCode})`; 1827 } 1828 const err = new HttpClientError(msg, statusCode); 1829 err.result = response.result; 1830 reject(err); 1831 } 1832 else { 1833 resolve(response); 1834 } 1835 })); 1836 }); 1837 } 1838 } 1839 exports.HttpClient = HttpClient; 1840 const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); 1841 //# sourceMappingURL=index.js.map 1842 1843 /***/ }), 1844 1845 /***/ 9835: 1846 /***/ ((__unused_webpack_module, exports) => { 1847 1848 "use strict"; 1849 1850 Object.defineProperty(exports, "__esModule", ({ value: true })); 1851 exports.checkBypass = exports.getProxyUrl = void 0; 1852 function getProxyUrl(reqUrl) { 1853 const usingSsl = reqUrl.protocol === 'https:'; 1854 if (checkBypass(reqUrl)) { 1855 return undefined; 1856 } 1857 const proxyVar = (() => { 1858 if (usingSsl) { 1859 return process.env['https_proxy'] || process.env['HTTPS_PROXY']; 1860 } 1861 else { 1862 return process.env['http_proxy'] || process.env['HTTP_PROXY']; 1863 } 1864 })(); 1865 if (proxyVar) { 1866 try { 1867 return new URL(proxyVar); 1868 } 1869 catch (_a) { 1870 if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) 1871 return new URL(`http://${proxyVar}`); 1872 } 1873 } 1874 else { 1875 return undefined; 1876 } 1877 } 1878 exports.getProxyUrl = getProxyUrl; 1879 function checkBypass(reqUrl) { 1880 if (!reqUrl.hostname) { 1881 return false; 1882 } 1883 const reqHost = reqUrl.hostname; 1884 if (isLoopbackAddress(reqHost)) { 1885 return true; 1886 } 1887 const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; 1888 if (!noProxy) { 1889 return false; 1890 } 1891 // Determine the request port 1892 let reqPort; 1893 if (reqUrl.port) { 1894 reqPort = Number(reqUrl.port); 1895 } 1896 else if (reqUrl.protocol === 'http:') { 1897 reqPort = 80; 1898 } 1899 else if (reqUrl.protocol === 'https:') { 1900 reqPort = 443; 1901 } 1902 // Format the request hostname and hostname with port 1903 const upperReqHosts = [reqUrl.hostname.toUpperCase()]; 1904 if (typeof reqPort === 'number') { 1905 upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); 1906 } 1907 // Compare request host against noproxy 1908 for (const upperNoProxyItem of noProxy 1909 .split(',') 1910 .map(x => x.trim().toUpperCase()) 1911 .filter(x => x)) { 1912 if (upperNoProxyItem === '*' || 1913 upperReqHosts.some(x => x === upperNoProxyItem || 1914 x.endsWith(`.${upperNoProxyItem}`) || 1915 (upperNoProxyItem.startsWith('.') && 1916 x.endsWith(`${upperNoProxyItem}`)))) { 1917 return true; 1918 } 1919 } 1920 return false; 1921 } 1922 exports.checkBypass = checkBypass; 1923 function isLoopbackAddress(host) { 1924 const hostLower = host.toLowerCase(); 1925 return (hostLower === 'localhost' || 1926 hostLower.startsWith('127.') || 1927 hostLower.startsWith('[::1]') || 1928 hostLower.startsWith('[0:0:0:0:0:0:0:1]')); 1929 } 1930 //# sourceMappingURL=proxy.js.map 1931 1932 /***/ }), 1933 1934 /***/ 8520: 1935 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 1936 1937 "use strict"; 1938 1939 1940 const net = __nccwpck_require__(1808) 1941 const tls = __nccwpck_require__(4404) 1942 const { once } = __nccwpck_require__(2361) 1943 const timers = __nccwpck_require__(8670) 1944 const { normalizeOptions, cacheOptions } = __nccwpck_require__(1709) 1945 const { getProxy, getProxyAgent, proxyCache } = __nccwpck_require__(8443) 1946 const Errors = __nccwpck_require__(4724) 1947 const { Agent: AgentBase } = __nccwpck_require__(694) 1948 1949 module.exports = class Agent extends AgentBase { 1950 #options 1951 #timeouts 1952 #proxy 1953 #noProxy 1954 #ProxyAgent 1955 1956 constructor (options = {}) { 1957 const { timeouts, proxy, noProxy, ...normalizedOptions } = normalizeOptions(options) 1958 1959 super(normalizedOptions) 1960 1961 this.#options = normalizedOptions 1962 this.#timeouts = timeouts 1963 1964 if (proxy) { 1965 this.#proxy = new URL(proxy) 1966 this.#noProxy = noProxy 1967 this.#ProxyAgent = getProxyAgent(proxy) 1968 } 1969 } 1970 1971 get proxy () { 1972 return this.#proxy ? { url: this.#proxy } : {} 1973 } 1974 1975 #getProxy (options) { 1976 if (!this.#proxy) { 1977 return 1978 } 1979 1980 const proxy = getProxy(`${options.protocol}//${options.host}:${options.port}`, { 1981 proxy: this.#proxy, 1982 noProxy: this.#noProxy, 1983 }) 1984 1985 if (!proxy) { 1986 return 1987 } 1988 1989 const cacheKey = cacheOptions({ 1990 ...options, 1991 ...this.#options, 1992 timeouts: this.#timeouts, 1993 proxy, 1994 }) 1995 1996 if (proxyCache.has(cacheKey)) { 1997 return proxyCache.get(cacheKey) 1998 } 1999 2000 let ProxyAgent = this.#ProxyAgent 2001 if (Array.isArray(ProxyAgent)) { 2002 ProxyAgent = this.isSecureEndpoint(options) ? ProxyAgent[1] : ProxyAgent[0] 2003 } 2004 2005 const proxyAgent = new ProxyAgent(proxy, this.#options) 2006 proxyCache.set(cacheKey, proxyAgent) 2007 2008 return proxyAgent 2009 } 2010 2011 // takes an array of promises and races them against the connection timeout 2012 // which will throw the necessary error if it is hit. This will return the 2013 // result of the promise race. 2014 async #timeoutConnection ({ promises, options, timeout }, ac = new AbortController()) { 2015 if (timeout) { 2016 const connectionTimeout = timers.setTimeout(timeout, null, { signal: ac.signal }) 2017 .then(() => { 2018 throw new Errors.ConnectionTimeoutError(`${options.host}:${options.port}`) 2019 }).catch((err) => { 2020 if (err.name === 'AbortError') { 2021 return 2022 } 2023 throw err 2024 }) 2025 promises.push(connectionTimeout) 2026 } 2027 2028 let result 2029 try { 2030 result = await Promise.race(promises) 2031 ac.abort() 2032 } catch (err) { 2033 ac.abort() 2034 throw err 2035 } 2036 return result 2037 } 2038 2039 async connect (request, options) { 2040 // if the connection does not have its own lookup function 2041 // set, then use the one from our options 2042 options.lookup ??= this.#options.lookup 2043 2044 let socket 2045 let timeout = this.#timeouts.connection 2046 const isSecureEndpoint = this.isSecureEndpoint(options) 2047 2048 const proxy = this.#getProxy(options) 2049 if (proxy) { 2050 // some of the proxies will wait for the socket to fully connect before 2051 // returning so we have to await this while also racing it against the 2052 // connection timeout. 2053 const start = Date.now() 2054 socket = await this.#timeoutConnection({ 2055 options, 2056 timeout, 2057 promises: [proxy.connect(request, options)], 2058 }) 2059 // see how much time proxy.connect took and subtract it from 2060 // the timeout 2061 if (timeout) { 2062 timeout = timeout - (Date.now() - start) 2063 } 2064 } else { 2065 socket = (isSecureEndpoint ? tls : net).connect(options) 2066 } 2067 2068 socket.setKeepAlive(this.keepAlive, this.keepAliveMsecs) 2069 socket.setNoDelay(this.keepAlive) 2070 2071 const abortController = new AbortController() 2072 const { signal } = abortController 2073 2074 const connectPromise = socket[isSecureEndpoint ? 'secureConnecting' : 'connecting'] 2075 ? once(socket, isSecureEndpoint ? 'secureConnect' : 'connect', { signal }) 2076 : Promise.resolve() 2077 2078 await this.#timeoutConnection({ 2079 options, 2080 timeout, 2081 promises: [ 2082 connectPromise, 2083 once(socket, 'error', { signal }).then((err) => { 2084 throw err[0] 2085 }), 2086 ], 2087 }, abortController) 2088 2089 if (this.#timeouts.idle) { 2090 socket.setTimeout(this.#timeouts.idle, () => { 2091 socket.destroy(new Errors.IdleTimeoutError(`${options.host}:${options.port}`)) 2092 }) 2093 } 2094 2095 return socket 2096 } 2097 2098 addRequest (request, options) { 2099 const proxy = this.#getProxy(options) 2100 // it would be better to call proxy.addRequest here but this causes the 2101 // http-proxy-agent to call its super.addRequest which causes the request 2102 // to be added to the agent twice. since we only support 3 agents 2103 // currently (see the required agents in proxy.js) we have manually 2104 // checked that the only public methods we need to call are called in the 2105 // next block. this could change in the future and presumably we would get 2106 // failing tests until we have properly called the necessary methods on 2107 // each of our proxy agents 2108 if (proxy?.setRequestProps) { 2109 proxy.setRequestProps(request, options) 2110 } 2111 2112 request.setHeader('connection', this.keepAlive ? 'keep-alive' : 'close') 2113 2114 if (this.#timeouts.response) { 2115 let responseTimeout 2116 request.once('finish', () => { 2117 setTimeout(() => { 2118 request.destroy(new Errors.ResponseTimeoutError(request, this.#proxy)) 2119 }, this.#timeouts.response) 2120 }) 2121 request.once('response', () => { 2122 clearTimeout(responseTimeout) 2123 }) 2124 } 2125 2126 if (this.#timeouts.transfer) { 2127 let transferTimeout 2128 request.once('response', (res) => { 2129 setTimeout(() => { 2130 res.destroy(new Errors.TransferTimeoutError(request, this.#proxy)) 2131 }, this.#timeouts.transfer) 2132 res.once('close', () => { 2133 clearTimeout(transferTimeout) 2134 }) 2135 }) 2136 } 2137 2138 return super.addRequest(request, options) 2139 } 2140 } 2141 2142 2143 /***/ }), 2144 2145 /***/ 2292: 2146 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2147 2148 "use strict"; 2149 2150 2151 const { LRUCache } = __nccwpck_require__(4446) 2152 const dns = __nccwpck_require__(9523) 2153 2154 // this is a factory so that each request can have its own opts (i.e. ttl) 2155 // while still sharing the cache across all requests 2156 const cache = new LRUCache({ max: 50 }) 2157 2158 const getOptions = ({ 2159 family = 0, 2160 hints = dns.ADDRCONFIG, 2161 all = false, 2162 verbatim = undefined, 2163 ttl = 5 * 60 * 1000, 2164 lookup = dns.lookup, 2165 }) => ({ 2166 // hints and lookup are returned since both are top level properties to (net|tls).connect 2167 hints, 2168 lookup: (hostname, ...args) => { 2169 const callback = args.pop() // callback is always last arg 2170 const lookupOptions = args[0] ?? {} 2171 2172 const options = { 2173 family, 2174 hints, 2175 all, 2176 verbatim, 2177 ...(typeof lookupOptions === 'number' ? { family: lookupOptions } : lookupOptions), 2178 } 2179 2180 const key = JSON.stringify({ hostname, ...options }) 2181 2182 if (cache.has(key)) { 2183 const cached = cache.get(key) 2184 return process.nextTick(callback, null, ...cached) 2185 } 2186 2187 lookup(hostname, options, (err, ...result) => { 2188 if (err) { 2189 return callback(err) 2190 } 2191 2192 cache.set(key, result, { ttl }) 2193 return callback(null, ...result) 2194 }) 2195 }, 2196 }) 2197 2198 module.exports = { 2199 cache, 2200 getOptions, 2201 } 2202 2203 2204 /***/ }), 2205 2206 /***/ 4724: 2207 /***/ ((module) => { 2208 2209 "use strict"; 2210 2211 2212 class InvalidProxyProtocolError extends Error { 2213 constructor (url) { 2214 super(`Invalid protocol \`${url.protocol}\` connecting to proxy \`${url.host}\``) 2215 this.code = 'EINVALIDPROXY' 2216 this.proxy = url 2217 } 2218 } 2219 2220 class ConnectionTimeoutError extends Error { 2221 constructor (host) { 2222 super(`Timeout connecting to host \`${host}\``) 2223 this.code = 'ECONNECTIONTIMEOUT' 2224 this.host = host 2225 } 2226 } 2227 2228 class IdleTimeoutError extends Error { 2229 constructor (host) { 2230 super(`Idle timeout reached for host \`${host}\``) 2231 this.code = 'EIDLETIMEOUT' 2232 this.host = host 2233 } 2234 } 2235 2236 class ResponseTimeoutError extends Error { 2237 constructor (request, proxy) { 2238 let msg = 'Response timeout ' 2239 if (proxy) { 2240 msg += `from proxy \`${proxy.host}\` ` 2241 } 2242 msg += `connecting to host \`${request.host}\`` 2243 super(msg) 2244 this.code = 'ERESPONSETIMEOUT' 2245 this.proxy = proxy 2246 this.request = request 2247 } 2248 } 2249 2250 class TransferTimeoutError extends Error { 2251 constructor (request, proxy) { 2252 let msg = 'Transfer timeout ' 2253 if (proxy) { 2254 msg += `from proxy \`${proxy.host}\` ` 2255 } 2256 msg += `for \`${request.host}\`` 2257 super(msg) 2258 this.code = 'ETRANSFERTIMEOUT' 2259 this.proxy = proxy 2260 this.request = request 2261 } 2262 } 2263 2264 module.exports = { 2265 InvalidProxyProtocolError, 2266 ConnectionTimeoutError, 2267 IdleTimeoutError, 2268 ResponseTimeoutError, 2269 TransferTimeoutError, 2270 } 2271 2272 2273 /***/ }), 2274 2275 /***/ 9907: 2276 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2277 2278 "use strict"; 2279 2280 2281 const { LRUCache } = __nccwpck_require__(4446) 2282 const { normalizeOptions, cacheOptions } = __nccwpck_require__(1709) 2283 const { getProxy, proxyCache } = __nccwpck_require__(8443) 2284 const dns = __nccwpck_require__(2292) 2285 const Agent = __nccwpck_require__(8520) 2286 2287 const agentCache = new LRUCache({ max: 20 }) 2288 2289 const getAgent = (url, { agent, proxy, noProxy, ...options } = {}) => { 2290 // false has meaning so this can't be a simple truthiness check 2291 if (agent != null) { 2292 return agent 2293 } 2294 2295 url = new URL(url) 2296 2297 const proxyForUrl = getProxy(url, { proxy, noProxy }) 2298 const normalizedOptions = { 2299 ...normalizeOptions(options), 2300 proxy: proxyForUrl, 2301 } 2302 2303 const cacheKey = cacheOptions({ 2304 ...normalizedOptions, 2305 secureEndpoint: url.protocol === 'https:', 2306 }) 2307 2308 if (agentCache.has(cacheKey)) { 2309 return agentCache.get(cacheKey) 2310 } 2311 2312 const newAgent = new Agent(normalizedOptions) 2313 agentCache.set(cacheKey, newAgent) 2314 2315 return newAgent 2316 } 2317 2318 module.exports = { 2319 getAgent, 2320 Agent, 2321 // these are exported for backwards compatability 2322 HttpAgent: Agent, 2323 HttpsAgent: Agent, 2324 cache: { 2325 proxy: proxyCache, 2326 agent: agentCache, 2327 dns: dns.cache, 2328 clear: () => { 2329 proxyCache.clear() 2330 agentCache.clear() 2331 dns.cache.clear() 2332 }, 2333 }, 2334 } 2335 2336 2337 /***/ }), 2338 2339 /***/ 1709: 2340 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2341 2342 "use strict"; 2343 2344 2345 const dns = __nccwpck_require__(2292) 2346 2347 const normalizeOptions = (opts) => { 2348 const family = parseInt(opts.family ?? '0', 10) 2349 const keepAlive = opts.keepAlive ?? true 2350 2351 const normalized = { 2352 // nodejs http agent options. these are all the defaults 2353 // but kept here to increase the likelihood of cache hits 2354 // https://nodejs.org/api/http.html#new-agentoptions 2355 keepAliveMsecs: keepAlive ? 1000 : undefined, 2356 maxSockets: opts.maxSockets ?? 15, 2357 maxTotalSockets: Infinity, 2358 maxFreeSockets: keepAlive ? 256 : undefined, 2359 scheduling: 'fifo', 2360 // then spread the rest of the options 2361 ...opts, 2362 // we already set these to their defaults that we want 2363 family, 2364 keepAlive, 2365 // our custom timeout options 2366 timeouts: { 2367 // the standard timeout option is mapped to our idle timeout 2368 // and then deleted below 2369 idle: opts.timeout ?? 0, 2370 connection: 0, 2371 response: 0, 2372 transfer: 0, 2373 ...opts.timeouts, 2374 }, 2375 // get the dns options that go at the top level of socket connection 2376 ...dns.getOptions({ family, ...opts.dns }), 2377 } 2378 2379 // remove timeout since we already used it to set our own idle timeout 2380 delete normalized.timeout 2381 2382 return normalized 2383 } 2384 2385 const createKey = (obj) => { 2386 let key = '' 2387 const sorted = Object.entries(obj).sort((a, b) => a[0] - b[0]) 2388 for (let [k, v] of sorted) { 2389 if (v == null) { 2390 v = 'null' 2391 } else if (v instanceof URL) { 2392 v = v.toString() 2393 } else if (typeof v === 'object') { 2394 v = createKey(v) 2395 } 2396 key += `${k}:${v}:` 2397 } 2398 return key 2399 } 2400 2401 const cacheOptions = ({ secureEndpoint, ...options }) => createKey({ 2402 secureEndpoint: !!secureEndpoint, 2403 // socket connect options 2404 family: options.family, 2405 hints: options.hints, 2406 localAddress: options.localAddress, 2407 // tls specific connect options 2408 strictSsl: secureEndpoint ? !!options.rejectUnauthorized : false, 2409 ca: secureEndpoint ? options.ca : null, 2410 cert: secureEndpoint ? options.cert : null, 2411 key: secureEndpoint ? options.key : null, 2412 // http agent options 2413 keepAlive: options.keepAlive, 2414 keepAliveMsecs: options.keepAliveMsecs, 2415 maxSockets: options.maxSockets, 2416 maxTotalSockets: options.maxTotalSockets, 2417 maxFreeSockets: options.maxFreeSockets, 2418 scheduling: options.scheduling, 2419 // timeout options 2420 timeouts: options.timeouts, 2421 // proxy 2422 proxy: options.proxy, 2423 }) 2424 2425 module.exports = { 2426 normalizeOptions, 2427 cacheOptions, 2428 } 2429 2430 2431 /***/ }), 2432 2433 /***/ 8443: 2434 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2435 2436 "use strict"; 2437 2438 2439 const { HttpProxyAgent } = __nccwpck_require__(3764) 2440 const { HttpsProxyAgent } = __nccwpck_require__(7219) 2441 const { SocksProxyAgent } = __nccwpck_require__(5038) 2442 const { LRUCache } = __nccwpck_require__(4446) 2443 const { InvalidProxyProtocolError } = __nccwpck_require__(4724) 2444 2445 const PROXY_CACHE = new LRUCache({ max: 20 }) 2446 2447 const SOCKS_PROTOCOLS = new Set(SocksProxyAgent.protocols) 2448 2449 const PROXY_ENV_KEYS = new Set(['https_proxy', 'http_proxy', 'proxy', 'no_proxy']) 2450 2451 const PROXY_ENV = Object.entries(process.env).reduce((acc, [key, value]) => { 2452 key = key.toLowerCase() 2453 if (PROXY_ENV_KEYS.has(key)) { 2454 acc[key] = value 2455 } 2456 return acc 2457 }, {}) 2458 2459 const getProxyAgent = (url) => { 2460 url = new URL(url) 2461 2462 const protocol = url.protocol.slice(0, -1) 2463 if (SOCKS_PROTOCOLS.has(protocol)) { 2464 return SocksProxyAgent 2465 } 2466 if (protocol === 'https' || protocol === 'http') { 2467 return [HttpProxyAgent, HttpsProxyAgent] 2468 } 2469 2470 throw new InvalidProxyProtocolError(url) 2471 } 2472 2473 const isNoProxy = (url, noProxy) => { 2474 if (typeof noProxy === 'string') { 2475 noProxy = noProxy.split(',').map((p) => p.trim()).filter(Boolean) 2476 } 2477 2478 if (!noProxy || !noProxy.length) { 2479 return false 2480 } 2481 2482 const hostSegments = url.hostname.split('.').reverse() 2483 2484 return noProxy.some((no) => { 2485 const noSegments = no.split('.').filter(Boolean).reverse() 2486 if (!noSegments.length) { 2487 return false 2488 } 2489 2490 for (let i = 0; i < noSegments.length; i++) { 2491 if (hostSegments[i] !== noSegments[i]) { 2492 return false 2493 } 2494 } 2495 2496 return true 2497 }) 2498 } 2499 2500 const getProxy = (url, { proxy, noProxy }) => { 2501 url = new URL(url) 2502 2503 if (!proxy) { 2504 proxy = url.protocol === 'https:' 2505 ? PROXY_ENV.https_proxy 2506 : PROXY_ENV.https_proxy || PROXY_ENV.http_proxy || PROXY_ENV.proxy 2507 } 2508 2509 if (!noProxy) { 2510 noProxy = PROXY_ENV.no_proxy 2511 } 2512 2513 if (!proxy || isNoProxy(url, noProxy)) { 2514 return null 2515 } 2516 2517 return new URL(proxy) 2518 } 2519 2520 module.exports = { 2521 getProxyAgent, 2522 getProxy, 2523 proxyCache: PROXY_CACHE, 2524 } 2525 2526 2527 /***/ }), 2528 2529 /***/ 1573: 2530 /***/ ((module) => { 2531 2532 // given an input that may or may not be an object, return an object that has 2533 // a copy of every defined property listed in 'copy'. if the input is not an 2534 // object, assign it to the property named by 'wrap' 2535 const getOptions = (input, { copy, wrap }) => { 2536 const result = {} 2537 2538 if (input && typeof input === 'object') { 2539 for (const prop of copy) { 2540 if (input[prop] !== undefined) { 2541 result[prop] = input[prop] 2542 } 2543 } 2544 } else { 2545 result[wrap] = input 2546 } 2547 2548 return result 2549 } 2550 2551 module.exports = getOptions 2552 2553 2554 /***/ }), 2555 2556 /***/ 2486: 2557 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2558 2559 const semver = __nccwpck_require__(1383) 2560 2561 const satisfies = (range) => { 2562 return semver.satisfies(process.version, range, { includePrerelease: true }) 2563 } 2564 2565 module.exports = { 2566 satisfies, 2567 } 2568 2569 2570 /***/ }), 2571 2572 /***/ 8025: 2573 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2574 2575 "use strict"; 2576 2577 const { inspect } = __nccwpck_require__(3837) 2578 2579 // adapted from node's internal/errors 2580 // https://github.com/nodejs/node/blob/c8a04049/lib/internal/errors.js 2581 2582 // close copy of node's internal SystemError class. 2583 class SystemError { 2584 constructor (code, prefix, context) { 2585 // XXX context.code is undefined in all constructors used in cp/polyfill 2586 // that may be a bug copied from node, maybe the constructor should use 2587 // `code` not `errno`? nodejs/node#41104 2588 let message = `${prefix}: ${context.syscall} returned ` + 2589 `${context.code} (${context.message})` 2590 2591 if (context.path !== undefined) { 2592 message += ` ${context.path}` 2593 } 2594 if (context.dest !== undefined) { 2595 message += ` => ${context.dest}` 2596 } 2597 2598 this.code = code 2599 Object.defineProperties(this, { 2600 name: { 2601 value: 'SystemError', 2602 enumerable: false, 2603 writable: true, 2604 configurable: true, 2605 }, 2606 message: { 2607 value: message, 2608 enumerable: false, 2609 writable: true, 2610 configurable: true, 2611 }, 2612 info: { 2613 value: context, 2614 enumerable: true, 2615 configurable: true, 2616 writable: false, 2617 }, 2618 errno: { 2619 get () { 2620 return context.errno 2621 }, 2622 set (value) { 2623 context.errno = value 2624 }, 2625 enumerable: true, 2626 configurable: true, 2627 }, 2628 syscall: { 2629 get () { 2630 return context.syscall 2631 }, 2632 set (value) { 2633 context.syscall = value 2634 }, 2635 enumerable: true, 2636 configurable: true, 2637 }, 2638 }) 2639 2640 if (context.path !== undefined) { 2641 Object.defineProperty(this, 'path', { 2642 get () { 2643 return context.path 2644 }, 2645 set (value) { 2646 context.path = value 2647 }, 2648 enumerable: true, 2649 configurable: true, 2650 }) 2651 } 2652 2653 if (context.dest !== undefined) { 2654 Object.defineProperty(this, 'dest', { 2655 get () { 2656 return context.dest 2657 }, 2658 set (value) { 2659 context.dest = value 2660 }, 2661 enumerable: true, 2662 configurable: true, 2663 }) 2664 } 2665 } 2666 2667 toString () { 2668 return `${this.name} [${this.code}]: ${this.message}` 2669 } 2670 2671 [Symbol.for('nodejs.util.inspect.custom')] (_recurseTimes, ctx) { 2672 return inspect(this, { 2673 ...ctx, 2674 getters: true, 2675 customInspect: false, 2676 }) 2677 } 2678 } 2679 2680 function E (code, message) { 2681 module.exports[code] = class NodeError extends SystemError { 2682 constructor (ctx) { 2683 super(code, message, ctx) 2684 } 2685 } 2686 } 2687 2688 E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite directory with non-directory') 2689 E('ERR_FS_CP_EEXIST', 'Target already exists') 2690 E('ERR_FS_CP_EINVAL', 'Invalid src or dest') 2691 E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe') 2692 E('ERR_FS_CP_NON_DIR_TO_DIR', 'Cannot overwrite non-directory with directory') 2693 E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file') 2694 E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY', 'Cannot overwrite symlink in subdirectory of self') 2695 E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type') 2696 E('ERR_FS_EISDIR', 'Path is a directory') 2697 2698 module.exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends Error { 2699 constructor (name, expected, actual) { 2700 super() 2701 this.code = 'ERR_INVALID_ARG_TYPE' 2702 this.message = `The ${name} argument must be ${expected}. Received ${typeof actual}` 2703 } 2704 } 2705 2706 2707 /***/ }), 2708 2709 /***/ 2702: 2710 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2711 2712 const fs = __nccwpck_require__(3292) 2713 const getOptions = __nccwpck_require__(1573) 2714 const node = __nccwpck_require__(2486) 2715 const polyfill = __nccwpck_require__(2613) 2716 2717 // node 16.7.0 added fs.cp 2718 const useNative = node.satisfies('>=16.7.0') 2719 2720 const cp = async (src, dest, opts) => { 2721 const options = getOptions(opts, { 2722 copy: ['dereference', 'errorOnExist', 'filter', 'force', 'preserveTimestamps', 'recursive'], 2723 }) 2724 2725 // the polyfill is tested separately from this module, no need to hack 2726 // process.version to try to trigger it just for coverage 2727 // istanbul ignore next 2728 return useNative 2729 ? fs.cp(src, dest, options) 2730 : polyfill(src, dest, options) 2731 } 2732 2733 module.exports = cp 2734 2735 2736 /***/ }), 2737 2738 /***/ 2613: 2739 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 2740 2741 "use strict"; 2742 // this file is a modified version of the code in node 17.2.0 2743 // which is, in turn, a modified version of the fs-extra module on npm 2744 // node core changes: 2745 // - Use of the assert module has been replaced with core's error system. 2746 // - All code related to the glob dependency has been removed. 2747 // - Bring your own custom fs module is not currently supported. 2748 // - Some basic code cleanup. 2749 // changes here: 2750 // - remove all callback related code 2751 // - drop sync support 2752 // - change assertions back to non-internal methods (see options.js) 2753 // - throws ENOTDIR when rmdir gets an ENOENT for a path that exists in Windows 2754 2755 2756 const { 2757 ERR_FS_CP_DIR_TO_NON_DIR, 2758 ERR_FS_CP_EEXIST, 2759 ERR_FS_CP_EINVAL, 2760 ERR_FS_CP_FIFO_PIPE, 2761 ERR_FS_CP_NON_DIR_TO_DIR, 2762 ERR_FS_CP_SOCKET, 2763 ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, 2764 ERR_FS_CP_UNKNOWN, 2765 ERR_FS_EISDIR, 2766 ERR_INVALID_ARG_TYPE, 2767 } = __nccwpck_require__(8025) 2768 const { 2769 constants: { 2770 errno: { 2771 EEXIST, 2772 EISDIR, 2773 EINVAL, 2774 ENOTDIR, 2775 }, 2776 }, 2777 } = __nccwpck_require__(2037) 2778 const { 2779 chmod, 2780 copyFile, 2781 lstat, 2782 mkdir, 2783 readdir, 2784 readlink, 2785 stat, 2786 symlink, 2787 unlink, 2788 utimes, 2789 } = __nccwpck_require__(3292) 2790 const { 2791 dirname, 2792 isAbsolute, 2793 join, 2794 parse, 2795 resolve, 2796 sep, 2797 toNamespacedPath, 2798 } = __nccwpck_require__(1017) 2799 const { fileURLToPath } = __nccwpck_require__(7310) 2800 2801 const defaultOptions = { 2802 dereference: false, 2803 errorOnExist: false, 2804 filter: undefined, 2805 force: true, 2806 preserveTimestamps: false, 2807 recursive: false, 2808 } 2809 2810 async function cp (src, dest, opts) { 2811 if (opts != null && typeof opts !== 'object') { 2812 throw new ERR_INVALID_ARG_TYPE('options', ['Object'], opts) 2813 } 2814 return cpFn( 2815 toNamespacedPath(getValidatedPath(src)), 2816 toNamespacedPath(getValidatedPath(dest)), 2817 { ...defaultOptions, ...opts }) 2818 } 2819 2820 function getValidatedPath (fileURLOrPath) { 2821 const path = fileURLOrPath != null && fileURLOrPath.href 2822 && fileURLOrPath.origin 2823 ? fileURLToPath(fileURLOrPath) 2824 : fileURLOrPath 2825 return path 2826 } 2827 2828 async function cpFn (src, dest, opts) { 2829 // Warn about using preserveTimestamps on 32-bit node 2830 // istanbul ignore next 2831 if (opts.preserveTimestamps && process.arch === 'ia32') { 2832 const warning = 'Using the preserveTimestamps option in 32-bit ' + 2833 'node is not recommended' 2834 process.emitWarning(warning, 'TimestampPrecisionWarning') 2835 } 2836 const stats = await checkPaths(src, dest, opts) 2837 const { srcStat, destStat } = stats 2838 await checkParentPaths(src, srcStat, dest) 2839 if (opts.filter) { 2840 return handleFilter(checkParentDir, destStat, src, dest, opts) 2841 } 2842 return checkParentDir(destStat, src, dest, opts) 2843 } 2844 2845 async function checkPaths (src, dest, opts) { 2846 const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts) 2847 if (destStat) { 2848 if (areIdentical(srcStat, destStat)) { 2849 throw new ERR_FS_CP_EINVAL({ 2850 message: 'src and dest cannot be the same', 2851 path: dest, 2852 syscall: 'cp', 2853 errno: EINVAL, 2854 }) 2855 } 2856 if (srcStat.isDirectory() && !destStat.isDirectory()) { 2857 throw new ERR_FS_CP_DIR_TO_NON_DIR({ 2858 message: `cannot overwrite directory ${src} ` + 2859 `with non-directory ${dest}`, 2860 path: dest, 2861 syscall: 'cp', 2862 errno: EISDIR, 2863 }) 2864 } 2865 if (!srcStat.isDirectory() && destStat.isDirectory()) { 2866 throw new ERR_FS_CP_NON_DIR_TO_DIR({ 2867 message: `cannot overwrite non-directory ${src} ` + 2868 `with directory ${dest}`, 2869 path: dest, 2870 syscall: 'cp', 2871 errno: ENOTDIR, 2872 }) 2873 } 2874 } 2875 2876 if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { 2877 throw new ERR_FS_CP_EINVAL({ 2878 message: `cannot copy ${src} to a subdirectory of self ${dest}`, 2879 path: dest, 2880 syscall: 'cp', 2881 errno: EINVAL, 2882 }) 2883 } 2884 return { srcStat, destStat } 2885 } 2886 2887 function areIdentical (srcStat, destStat) { 2888 return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && 2889 destStat.dev === srcStat.dev 2890 } 2891 2892 function getStats (src, dest, opts) { 2893 const statFunc = opts.dereference ? 2894 (file) => stat(file, { bigint: true }) : 2895 (file) => lstat(file, { bigint: true }) 2896 return Promise.all([ 2897 statFunc(src), 2898 statFunc(dest).catch((err) => { 2899 // istanbul ignore next: unsure how to cover. 2900 if (err.code === 'ENOENT') { 2901 return null 2902 } 2903 // istanbul ignore next: unsure how to cover. 2904 throw err 2905 }), 2906 ]) 2907 } 2908 2909 async function checkParentDir (destStat, src, dest, opts) { 2910 const destParent = dirname(dest) 2911 const dirExists = await pathExists(destParent) 2912 if (dirExists) { 2913 return getStatsForCopy(destStat, src, dest, opts) 2914 } 2915 await mkdir(destParent, { recursive: true }) 2916 return getStatsForCopy(destStat, src, dest, opts) 2917 } 2918 2919 function pathExists (dest) { 2920 return stat(dest).then( 2921 () => true, 2922 // istanbul ignore next: not sure when this would occur 2923 (err) => (err.code === 'ENOENT' ? false : Promise.reject(err))) 2924 } 2925 2926 // Recursively check if dest parent is a subdirectory of src. 2927 // It works for all file types including symlinks since it 2928 // checks the src and dest inodes. It starts from the deepest 2929 // parent and stops once it reaches the src parent or the root path. 2930 async function checkParentPaths (src, srcStat, dest) { 2931 const srcParent = resolve(dirname(src)) 2932 const destParent = resolve(dirname(dest)) 2933 if (destParent === srcParent || destParent === parse(destParent).root) { 2934 return 2935 } 2936 let destStat 2937 try { 2938 destStat = await stat(destParent, { bigint: true }) 2939 } catch (err) { 2940 // istanbul ignore else: not sure when this would occur 2941 if (err.code === 'ENOENT') { 2942 return 2943 } 2944 // istanbul ignore next: not sure when this would occur 2945 throw err 2946 } 2947 if (areIdentical(srcStat, destStat)) { 2948 throw new ERR_FS_CP_EINVAL({ 2949 message: `cannot copy ${src} to a subdirectory of self ${dest}`, 2950 path: dest, 2951 syscall: 'cp', 2952 errno: EINVAL, 2953 }) 2954 } 2955 return checkParentPaths(src, srcStat, destParent) 2956 } 2957 2958 const normalizePathToArray = (path) => 2959 resolve(path).split(sep).filter(Boolean) 2960 2961 // Return true if dest is a subdir of src, otherwise false. 2962 // It only checks the path strings. 2963 function isSrcSubdir (src, dest) { 2964 const srcArr = normalizePathToArray(src) 2965 const destArr = normalizePathToArray(dest) 2966 return srcArr.every((cur, i) => destArr[i] === cur) 2967 } 2968 2969 async function handleFilter (onInclude, destStat, src, dest, opts, cb) { 2970 const include = await opts.filter(src, dest) 2971 if (include) { 2972 return onInclude(destStat, src, dest, opts, cb) 2973 } 2974 } 2975 2976 function startCopy (destStat, src, dest, opts) { 2977 if (opts.filter) { 2978 return handleFilter(getStatsForCopy, destStat, src, dest, opts) 2979 } 2980 return getStatsForCopy(destStat, src, dest, opts) 2981 } 2982 2983 async function getStatsForCopy (destStat, src, dest, opts) { 2984 const statFn = opts.dereference ? stat : lstat 2985 const srcStat = await statFn(src) 2986 // istanbul ignore else: can't portably test FIFO 2987 if (srcStat.isDirectory() && opts.recursive) { 2988 return onDir(srcStat, destStat, src, dest, opts) 2989 } else if (srcStat.isDirectory()) { 2990 throw new ERR_FS_EISDIR({ 2991 message: `${src} is a directory (not copied)`, 2992 path: src, 2993 syscall: 'cp', 2994 errno: EINVAL, 2995 }) 2996 } else if (srcStat.isFile() || 2997 srcStat.isCharacterDevice() || 2998 srcStat.isBlockDevice()) { 2999 return onFile(srcStat, destStat, src, dest, opts) 3000 } else if (srcStat.isSymbolicLink()) { 3001 return onLink(destStat, src, dest) 3002 } else if (srcStat.isSocket()) { 3003 throw new ERR_FS_CP_SOCKET({ 3004 message: `cannot copy a socket file: ${dest}`, 3005 path: dest, 3006 syscall: 'cp', 3007 errno: EINVAL, 3008 }) 3009 } else if (srcStat.isFIFO()) { 3010 throw new ERR_FS_CP_FIFO_PIPE({ 3011 message: `cannot copy a FIFO pipe: ${dest}`, 3012 path: dest, 3013 syscall: 'cp', 3014 errno: EINVAL, 3015 }) 3016 } 3017 // istanbul ignore next: should be unreachable 3018 throw new ERR_FS_CP_UNKNOWN({ 3019 message: `cannot copy an unknown file type: ${dest}`, 3020 path: dest, 3021 syscall: 'cp', 3022 errno: EINVAL, 3023 }) 3024 } 3025 3026 function onFile (srcStat, destStat, src, dest, opts) { 3027 if (!destStat) { 3028 return _copyFile(srcStat, src, dest, opts) 3029 } 3030 return mayCopyFile(srcStat, src, dest, opts) 3031 } 3032 3033 async function mayCopyFile (srcStat, src, dest, opts) { 3034 if (opts.force) { 3035 await unlink(dest) 3036 return _copyFile(srcStat, src, dest, opts) 3037 } else if (opts.errorOnExist) { 3038 throw new ERR_FS_CP_EEXIST({ 3039 message: `${dest} already exists`, 3040 path: dest, 3041 syscall: 'cp', 3042 errno: EEXIST, 3043 }) 3044 } 3045 } 3046 3047 async function _copyFile (srcStat, src, dest, opts) { 3048 await copyFile(src, dest) 3049 if (opts.preserveTimestamps) { 3050 return handleTimestampsAndMode(srcStat.mode, src, dest) 3051 } 3052 return setDestMode(dest, srcStat.mode) 3053 } 3054 3055 async function handleTimestampsAndMode (srcMode, src, dest) { 3056 // Make sure the file is writable before setting the timestamp 3057 // otherwise open fails with EPERM when invoked with 'r+' 3058 // (through utimes call) 3059 if (fileIsNotWritable(srcMode)) { 3060 await makeFileWritable(dest, srcMode) 3061 return setDestTimestampsAndMode(srcMode, src, dest) 3062 } 3063 return setDestTimestampsAndMode(srcMode, src, dest) 3064 } 3065 3066 function fileIsNotWritable (srcMode) { 3067 return (srcMode & 0o200) === 0 3068 } 3069 3070 function makeFileWritable (dest, srcMode) { 3071 return setDestMode(dest, srcMode | 0o200) 3072 } 3073 3074 async function setDestTimestampsAndMode (srcMode, src, dest) { 3075 await setDestTimestamps(src, dest) 3076 return setDestMode(dest, srcMode) 3077 } 3078 3079 function setDestMode (dest, srcMode) { 3080 return chmod(dest, srcMode) 3081 } 3082 3083 async function setDestTimestamps (src, dest) { 3084 // The initial srcStat.atime cannot be trusted 3085 // because it is modified by the read(2) system call 3086 // (See https://nodejs.org/api/fs.html#fs_stat_time_values) 3087 const updatedSrcStat = await stat(src) 3088 return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime) 3089 } 3090 3091 function onDir (srcStat, destStat, src, dest, opts) { 3092 if (!destStat) { 3093 return mkDirAndCopy(srcStat.mode, src, dest, opts) 3094 } 3095 return copyDir(src, dest, opts) 3096 } 3097 3098 async function mkDirAndCopy (srcMode, src, dest, opts) { 3099 await mkdir(dest) 3100 await copyDir(src, dest, opts) 3101 return setDestMode(dest, srcMode) 3102 } 3103 3104 async function copyDir (src, dest, opts) { 3105 const dir = await readdir(src) 3106 for (let i = 0; i < dir.length; i++) { 3107 const item = dir[i] 3108 const srcItem = join(src, item) 3109 const destItem = join(dest, item) 3110 const { destStat } = await checkPaths(srcItem, destItem, opts) 3111 await startCopy(destStat, srcItem, destItem, opts) 3112 } 3113 } 3114 3115 async function onLink (destStat, src, dest) { 3116 let resolvedSrc = await readlink(src) 3117 if (!isAbsolute(resolvedSrc)) { 3118 resolvedSrc = resolve(dirname(src), resolvedSrc) 3119 } 3120 if (!destStat) { 3121 return symlink(resolvedSrc, dest) 3122 } 3123 let resolvedDest 3124 try { 3125 resolvedDest = await readlink(dest) 3126 } catch (err) { 3127 // Dest exists and is a regular file or directory, 3128 // Windows may throw UNKNOWN error. If dest already exists, 3129 // fs throws error anyway, so no need to guard against it here. 3130 // istanbul ignore next: can only test on windows 3131 if (err.code === 'EINVAL' || err.code === 'UNKNOWN') { 3132 return symlink(resolvedSrc, dest) 3133 } 3134 // istanbul ignore next: should not be possible 3135 throw err 3136 } 3137 if (!isAbsolute(resolvedDest)) { 3138 resolvedDest = resolve(dirname(dest), resolvedDest) 3139 } 3140 if (isSrcSubdir(resolvedSrc, resolvedDest)) { 3141 throw new ERR_FS_CP_EINVAL({ 3142 message: `cannot copy ${resolvedSrc} to a subdirectory of self ` + 3143 `${resolvedDest}`, 3144 path: dest, 3145 syscall: 'cp', 3146 errno: EINVAL, 3147 }) 3148 } 3149 // Do not copy if src is a subdir of dest since unlinking 3150 // dest in this case would result in removing src contents 3151 // and therefore a broken symlink would be created. 3152 const srcStat = await stat(src) 3153 if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) { 3154 throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({ 3155 message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`, 3156 path: dest, 3157 syscall: 'cp', 3158 errno: EINVAL, 3159 }) 3160 } 3161 return copyLink(resolvedSrc, dest) 3162 } 3163 3164 async function copyLink (resolvedSrc, dest) { 3165 await unlink(dest) 3166 return symlink(resolvedSrc, dest) 3167 } 3168 3169 module.exports = cp 3170 3171 3172 /***/ }), 3173 3174 /***/ 575: 3175 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 3176 3177 "use strict"; 3178 3179 3180 const cp = __nccwpck_require__(2702) 3181 const withTempDir = __nccwpck_require__(1045) 3182 const readdirScoped = __nccwpck_require__(7339) 3183 const moveFile = __nccwpck_require__(1690) 3184 3185 module.exports = { 3186 cp, 3187 withTempDir, 3188 readdirScoped, 3189 moveFile, 3190 } 3191 3192 3193 /***/ }), 3194 3195 /***/ 1690: 3196 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 3197 3198 const { dirname, join, resolve, relative, isAbsolute } = __nccwpck_require__(1017) 3199 const fs = __nccwpck_require__(3292) 3200 3201 const pathExists = async path => { 3202 try { 3203 await fs.access(path) 3204 return true 3205 } catch (er) { 3206 return er.code !== 'ENOENT' 3207 } 3208 } 3209 3210 const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { 3211 if (!source || !destination) { 3212 throw new TypeError('`source` and `destination` file required') 3213 } 3214 3215 options = { 3216 overwrite: true, 3217 ...options, 3218 } 3219 3220 if (!options.overwrite && await pathExists(destination)) { 3221 throw new Error(`The destination file exists: ${destination}`) 3222 } 3223 3224 await fs.mkdir(dirname(destination), { recursive: true }) 3225 3226 try { 3227 await fs.rename(source, destination) 3228 } catch (error) { 3229 if (error.code === 'EXDEV' || error.code === 'EPERM') { 3230 const sourceStat = await fs.lstat(source) 3231 if (sourceStat.isDirectory()) { 3232 const files = await fs.readdir(source) 3233 await Promise.all(files.map((file) => 3234 moveFile(join(source, file), join(destination, file), options, false, symlinks) 3235 )) 3236 } else if (sourceStat.isSymbolicLink()) { 3237 symlinks.push({ source, destination }) 3238 } else { 3239 await fs.copyFile(source, destination) 3240 } 3241 } else { 3242 throw error 3243 } 3244 } 3245 3246 if (root) { 3247 await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { 3248 let target = await fs.readlink(symSource) 3249 // junction symlinks in windows will be absolute paths, so we need to 3250 // make sure they point to the symlink destination 3251 if (isAbsolute(target)) { 3252 target = resolve(symDestination, relative(symSource, target)) 3253 } 3254 // try to determine what the actual file is so we can create the correct 3255 // type of symlink in windows 3256 let targetStat = 'file' 3257 try { 3258 targetStat = await fs.stat(resolve(dirname(symSource), target)) 3259 if (targetStat.isDirectory()) { 3260 targetStat = 'junction' 3261 } 3262 } catch { 3263 // targetStat remains 'file' 3264 } 3265 await fs.symlink( 3266 target, 3267 symDestination, 3268 targetStat 3269 ) 3270 })) 3271 await fs.rm(source, { recursive: true, force: true }) 3272 } 3273 } 3274 3275 module.exports = moveFile 3276 3277 3278 /***/ }), 3279 3280 /***/ 7339: 3281 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 3282 3283 const { readdir } = __nccwpck_require__(3292) 3284 const { join } = __nccwpck_require__(1017) 3285 3286 const readdirScoped = async (dir) => { 3287 const results = [] 3288 3289 for (const item of await readdir(dir)) { 3290 if (item.startsWith('@')) { 3291 for (const scopedItem of await readdir(join(dir, item))) { 3292 results.push(join(item, scopedItem)) 3293 } 3294 } else { 3295 results.push(item) 3296 } 3297 } 3298 3299 return results 3300 } 3301 3302 module.exports = readdirScoped 3303 3304 3305 /***/ }), 3306 3307 /***/ 1045: 3308 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 3309 3310 const { join, sep } = __nccwpck_require__(1017) 3311 3312 const getOptions = __nccwpck_require__(1573) 3313 const { mkdir, mkdtemp, rm } = __nccwpck_require__(3292) 3314 3315 // create a temp directory, ensure its permissions match its parent, then call 3316 // the supplied function passing it the path to the directory. clean up after 3317 // the function finishes, whether it throws or not 3318 const withTempDir = async (root, fn, opts) => { 3319 const options = getOptions(opts, { 3320 copy: ['tmpPrefix'], 3321 }) 3322 // create the directory 3323 await mkdir(root, { recursive: true }) 3324 3325 const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || '')) 3326 let err 3327 let result 3328 3329 try { 3330 result = await fn(target) 3331 } catch (_err) { 3332 err = _err 3333 } 3334 3335 try { 3336 await rm(target, { force: true, recursive: true }) 3337 } catch { 3338 // ignore errors 3339 } 3340 3341 if (err) { 3342 throw err 3343 } 3344 3345 return result 3346 } 3347 3348 module.exports = withTempDir 3349 3350 3351 /***/ }), 3352 3353 /***/ 6833: 3354 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3355 3356 "use strict"; 3357 3358 Object.defineProperty(exports, "__esModule", ({ value: true })); 3359 exports.toDSSEBundle = exports.toMessageSignatureBundle = void 0; 3360 /* 3361 Copyright 2023 The Sigstore Authors. 3362 3363 Licensed under the Apache License, Version 2.0 (the "License"); 3364 you may not use this file except in compliance with the License. 3365 You may obtain a copy of the License at 3366 3367 http://www.apache.org/licenses/LICENSE-2.0 3368 3369 Unless required by applicable law or agreed to in writing, software 3370 distributed under the License is distributed on an "AS IS" BASIS, 3371 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3372 See the License for the specific language governing permissions and 3373 limitations under the License. 3374 */ 3375 const protobuf_specs_1 = __nccwpck_require__(530); 3376 const bundle_1 = __nccwpck_require__(2712); 3377 // Message signature bundle - $case: 'messageSignature' 3378 function toMessageSignatureBundle(options) { 3379 return { 3380 mediaType: options.singleCertificate 3381 ? bundle_1.BUNDLE_V03_MEDIA_TYPE 3382 : bundle_1.BUNDLE_V02_MEDIA_TYPE, 3383 content: { 3384 $case: 'messageSignature', 3385 messageSignature: { 3386 messageDigest: { 3387 algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256, 3388 digest: options.digest, 3389 }, 3390 signature: options.signature, 3391 }, 3392 }, 3393 verificationMaterial: toVerificationMaterial(options), 3394 }; 3395 } 3396 exports.toMessageSignatureBundle = toMessageSignatureBundle; 3397 // DSSE envelope bundle - $case: 'dsseEnvelope' 3398 function toDSSEBundle(options) { 3399 return { 3400 mediaType: options.singleCertificate 3401 ? bundle_1.BUNDLE_V03_MEDIA_TYPE 3402 : bundle_1.BUNDLE_V02_MEDIA_TYPE, 3403 content: { 3404 $case: 'dsseEnvelope', 3405 dsseEnvelope: toEnvelope(options), 3406 }, 3407 verificationMaterial: toVerificationMaterial(options), 3408 }; 3409 } 3410 exports.toDSSEBundle = toDSSEBundle; 3411 function toEnvelope(options) { 3412 return { 3413 payloadType: options.artifactType, 3414 payload: options.artifact, 3415 signatures: [toSignature(options)], 3416 }; 3417 } 3418 function toSignature(options) { 3419 return { 3420 keyid: options.keyHint || '', 3421 sig: options.signature, 3422 }; 3423 } 3424 // Verification material 3425 function toVerificationMaterial(options) { 3426 return { 3427 content: toKeyContent(options), 3428 tlogEntries: [], 3429 timestampVerificationData: { rfc3161Timestamps: [] }, 3430 }; 3431 } 3432 function toKeyContent(options) { 3433 if (options.certificate) { 3434 if (options.singleCertificate) { 3435 return { 3436 $case: 'certificate', 3437 certificate: { rawBytes: options.certificate }, 3438 }; 3439 } 3440 else { 3441 return { 3442 $case: 'x509CertificateChain', 3443 x509CertificateChain: { 3444 certificates: [{ rawBytes: options.certificate }], 3445 }, 3446 }; 3447 } 3448 } 3449 else { 3450 return { 3451 $case: 'publicKey', 3452 publicKey: { 3453 hint: options.keyHint || '', 3454 }, 3455 }; 3456 } 3457 } 3458 3459 3460 /***/ }), 3461 3462 /***/ 2712: 3463 /***/ ((__unused_webpack_module, exports) => { 3464 3465 "use strict"; 3466 3467 Object.defineProperty(exports, "__esModule", ({ value: true })); 3468 exports.isBundleWithDsseEnvelope = exports.isBundleWithMessageSignature = exports.isBundleWithPublicKey = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0; 3469 exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1'; 3470 exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2'; 3471 exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3'; 3472 exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json'; 3473 // Type guards for bundle variants. 3474 function isBundleWithCertificateChain(b) { 3475 return b.verificationMaterial.content.$case === 'x509CertificateChain'; 3476 } 3477 exports.isBundleWithCertificateChain = isBundleWithCertificateChain; 3478 function isBundleWithPublicKey(b) { 3479 return b.verificationMaterial.content.$case === 'publicKey'; 3480 } 3481 exports.isBundleWithPublicKey = isBundleWithPublicKey; 3482 function isBundleWithMessageSignature(b) { 3483 return b.content.$case === 'messageSignature'; 3484 } 3485 exports.isBundleWithMessageSignature = isBundleWithMessageSignature; 3486 function isBundleWithDsseEnvelope(b) { 3487 return b.content.$case === 'dsseEnvelope'; 3488 } 3489 exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope; 3490 3491 3492 /***/ }), 3493 3494 /***/ 3802: 3495 /***/ ((__unused_webpack_module, exports) => { 3496 3497 "use strict"; 3498 3499 Object.defineProperty(exports, "__esModule", ({ value: true })); 3500 exports.ValidationError = void 0; 3501 /* 3502 Copyright 2023 The Sigstore Authors. 3503 3504 Licensed under the Apache License, Version 2.0 (the "License"); 3505 you may not use this file except in compliance with the License. 3506 You may obtain a copy of the License at 3507 3508 http://www.apache.org/licenses/LICENSE-2.0 3509 3510 Unless required by applicable law or agreed to in writing, software 3511 distributed under the License is distributed on an "AS IS" BASIS, 3512 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3513 See the License for the specific language governing permissions and 3514 limitations under the License. 3515 */ 3516 class ValidationError extends Error { 3517 constructor(message, fields) { 3518 super(message); 3519 this.fields = fields; 3520 } 3521 } 3522 exports.ValidationError = ValidationError; 3523 3524 3525 /***/ }), 3526 3527 /***/ 9715: 3528 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3529 3530 "use strict"; 3531 3532 Object.defineProperty(exports, "__esModule", ({ value: true })); 3533 exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0; 3534 /* 3535 Copyright 2023 The Sigstore Authors. 3536 3537 Licensed under the Apache License, Version 2.0 (the "License"); 3538 you may not use this file except in compliance with the License. 3539 You may obtain a copy of the License at 3540 3541 http://www.apache.org/licenses/LICENSE-2.0 3542 3543 Unless required by applicable law or agreed to in writing, software 3544 distributed under the License is distributed on an "AS IS" BASIS, 3545 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3546 See the License for the specific language governing permissions and 3547 limitations under the License. 3548 */ 3549 var build_1 = __nccwpck_require__(6833); 3550 Object.defineProperty(exports, "toDSSEBundle", ({ enumerable: true, get: function () { return build_1.toDSSEBundle; } })); 3551 Object.defineProperty(exports, "toMessageSignatureBundle", ({ enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } })); 3552 var bundle_1 = __nccwpck_require__(2712); 3553 Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } })); 3554 Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } })); 3555 Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } })); 3556 Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } })); 3557 Object.defineProperty(exports, "isBundleWithCertificateChain", ({ enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } })); 3558 Object.defineProperty(exports, "isBundleWithDsseEnvelope", ({ enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } })); 3559 Object.defineProperty(exports, "isBundleWithMessageSignature", ({ enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } })); 3560 Object.defineProperty(exports, "isBundleWithPublicKey", ({ enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } })); 3561 var error_1 = __nccwpck_require__(3802); 3562 Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return error_1.ValidationError; } })); 3563 var serialized_1 = __nccwpck_require__(9875); 3564 Object.defineProperty(exports, "bundleFromJSON", ({ enumerable: true, get: function () { return serialized_1.bundleFromJSON; } })); 3565 Object.defineProperty(exports, "bundleToJSON", ({ enumerable: true, get: function () { return serialized_1.bundleToJSON; } })); 3566 Object.defineProperty(exports, "envelopeFromJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } })); 3567 Object.defineProperty(exports, "envelopeToJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeToJSON; } })); 3568 var validate_1 = __nccwpck_require__(9599); 3569 Object.defineProperty(exports, "assertBundle", ({ enumerable: true, get: function () { return validate_1.assertBundle; } })); 3570 Object.defineProperty(exports, "assertBundleLatest", ({ enumerable: true, get: function () { return validate_1.assertBundleLatest; } })); 3571 Object.defineProperty(exports, "assertBundleV01", ({ enumerable: true, get: function () { return validate_1.assertBundleV01; } })); 3572 Object.defineProperty(exports, "assertBundleV02", ({ enumerable: true, get: function () { return validate_1.assertBundleV02; } })); 3573 Object.defineProperty(exports, "isBundleV01", ({ enumerable: true, get: function () { return validate_1.isBundleV01; } })); 3574 3575 3576 /***/ }), 3577 3578 /***/ 9875: 3579 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3580 3581 "use strict"; 3582 3583 Object.defineProperty(exports, "__esModule", ({ value: true })); 3584 exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0; 3585 /* 3586 Copyright 2023 The Sigstore Authors. 3587 3588 Licensed under the Apache License, Version 2.0 (the "License"); 3589 you may not use this file except in compliance with the License. 3590 You may obtain a copy of the License at 3591 3592 http://www.apache.org/licenses/LICENSE-2.0 3593 3594 Unless required by applicable law or agreed to in writing, software 3595 distributed under the License is distributed on an "AS IS" BASIS, 3596 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3597 See the License for the specific language governing permissions and 3598 limitations under the License. 3599 */ 3600 const protobuf_specs_1 = __nccwpck_require__(530); 3601 const bundle_1 = __nccwpck_require__(2712); 3602 const validate_1 = __nccwpck_require__(9599); 3603 const bundleFromJSON = (obj) => { 3604 const bundle = protobuf_specs_1.Bundle.fromJSON(obj); 3605 switch (bundle.mediaType) { 3606 case bundle_1.BUNDLE_V01_MEDIA_TYPE: 3607 (0, validate_1.assertBundleV01)(bundle); 3608 break; 3609 case bundle_1.BUNDLE_V02_MEDIA_TYPE: 3610 (0, validate_1.assertBundleV02)(bundle); 3611 break; 3612 default: 3613 (0, validate_1.assertBundleLatest)(bundle); 3614 break; 3615 } 3616 return bundle; 3617 }; 3618 exports.bundleFromJSON = bundleFromJSON; 3619 const bundleToJSON = (bundle) => { 3620 return protobuf_specs_1.Bundle.toJSON(bundle); 3621 }; 3622 exports.bundleToJSON = bundleToJSON; 3623 const envelopeFromJSON = (obj) => { 3624 return protobuf_specs_1.Envelope.fromJSON(obj); 3625 }; 3626 exports.envelopeFromJSON = envelopeFromJSON; 3627 const envelopeToJSON = (envelope) => { 3628 return protobuf_specs_1.Envelope.toJSON(envelope); 3629 }; 3630 exports.envelopeToJSON = envelopeToJSON; 3631 3632 3633 /***/ }), 3634 3635 /***/ 9599: 3636 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3637 3638 "use strict"; 3639 3640 Object.defineProperty(exports, "__esModule", ({ value: true })); 3641 exports.assertBundleLatest = exports.assertBundleV02 = exports.isBundleV01 = exports.assertBundleV01 = exports.assertBundle = void 0; 3642 /* 3643 Copyright 2023 The Sigstore Authors. 3644 3645 Licensed under the Apache License, Version 2.0 (the "License"); 3646 you may not use this file except in compliance with the License. 3647 You may obtain a copy of the License at 3648 3649 http://www.apache.org/licenses/LICENSE-2.0 3650 3651 Unless required by applicable law or agreed to in writing, software 3652 distributed under the License is distributed on an "AS IS" BASIS, 3653 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3654 See the License for the specific language governing permissions and 3655 limitations under the License. 3656 */ 3657 const error_1 = __nccwpck_require__(3802); 3658 // Performs basic validation of a Sigstore bundle to ensure that all required 3659 // fields are populated. This is not a complete validation of the bundle, but 3660 // rather a check that the bundle is in a valid state to be processed by the 3661 // rest of the code. 3662 function assertBundle(b) { 3663 const invalidValues = validateBundleBase(b); 3664 if (invalidValues.length > 0) { 3665 throw new error_1.ValidationError('invalid bundle', invalidValues); 3666 } 3667 } 3668 exports.assertBundle = assertBundle; 3669 // Asserts that the given bundle conforms to the v0.1 bundle format. 3670 function assertBundleV01(b) { 3671 const invalidValues = []; 3672 invalidValues.push(...validateBundleBase(b)); 3673 invalidValues.push(...validateInclusionPromise(b)); 3674 if (invalidValues.length > 0) { 3675 throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues); 3676 } 3677 } 3678 exports.assertBundleV01 = assertBundleV01; 3679 // Type guard to determine if Bundle is a v0.1 bundle. 3680 function isBundleV01(b) { 3681 try { 3682 assertBundleV01(b); 3683 return true; 3684 } 3685 catch (e) { 3686 return false; 3687 } 3688 } 3689 exports.isBundleV01 = isBundleV01; 3690 // Asserts that the given bundle conforms to the v0.2 bundle format. 3691 function assertBundleV02(b) { 3692 const invalidValues = []; 3693 invalidValues.push(...validateBundleBase(b)); 3694 invalidValues.push(...validateInclusionProof(b)); 3695 if (invalidValues.length > 0) { 3696 throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues); 3697 } 3698 } 3699 exports.assertBundleV02 = assertBundleV02; 3700 // Asserts that the given bundle conforms to the newest (0.3) bundle format. 3701 function assertBundleLatest(b) { 3702 const invalidValues = []; 3703 invalidValues.push(...validateBundleBase(b)); 3704 invalidValues.push(...validateInclusionProof(b)); 3705 invalidValues.push(...validateNoCertificateChain(b)); 3706 if (invalidValues.length > 0) { 3707 throw new error_1.ValidationError('invalid bundle', invalidValues); 3708 } 3709 } 3710 exports.assertBundleLatest = assertBundleLatest; 3711 function validateBundleBase(b) { 3712 const invalidValues = []; 3713 // Media type validation 3714 if (b.mediaType === undefined || 3715 (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) && 3716 !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) { 3717 invalidValues.push('mediaType'); 3718 } 3719 // Content-related validation 3720 if (b.content === undefined) { 3721 invalidValues.push('content'); 3722 } 3723 else { 3724 switch (b.content.$case) { 3725 case 'messageSignature': 3726 if (b.content.messageSignature.messageDigest === undefined) { 3727 invalidValues.push('content.messageSignature.messageDigest'); 3728 } 3729 else { 3730 if (b.content.messageSignature.messageDigest.digest.length === 0) { 3731 invalidValues.push('content.messageSignature.messageDigest.digest'); 3732 } 3733 } 3734 if (b.content.messageSignature.signature.length === 0) { 3735 invalidValues.push('content.messageSignature.signature'); 3736 } 3737 break; 3738 case 'dsseEnvelope': 3739 if (b.content.dsseEnvelope.payload.length === 0) { 3740 invalidValues.push('content.dsseEnvelope.payload'); 3741 } 3742 if (b.content.dsseEnvelope.signatures.length !== 1) { 3743 invalidValues.push('content.dsseEnvelope.signatures'); 3744 } 3745 else { 3746 if (b.content.dsseEnvelope.signatures[0].sig.length === 0) { 3747 invalidValues.push('content.dsseEnvelope.signatures[0].sig'); 3748 } 3749 } 3750 break; 3751 } 3752 } 3753 // Verification material-related validation 3754 if (b.verificationMaterial === undefined) { 3755 invalidValues.push('verificationMaterial'); 3756 } 3757 else { 3758 if (b.verificationMaterial.content === undefined) { 3759 invalidValues.push('verificationMaterial.content'); 3760 } 3761 else { 3762 switch (b.verificationMaterial.content.$case) { 3763 case 'x509CertificateChain': 3764 if (b.verificationMaterial.content.x509CertificateChain.certificates 3765 .length === 0) { 3766 invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates'); 3767 } 3768 b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => { 3769 if (cert.rawBytes.length === 0) { 3770 invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`); 3771 } 3772 }); 3773 break; 3774 case 'certificate': 3775 if (b.verificationMaterial.content.certificate.rawBytes.length === 0) { 3776 invalidValues.push('verificationMaterial.content.certificate.rawBytes'); 3777 } 3778 break; 3779 } 3780 } 3781 if (b.verificationMaterial.tlogEntries === undefined) { 3782 invalidValues.push('verificationMaterial.tlogEntries'); 3783 } 3784 else { 3785 if (b.verificationMaterial.tlogEntries.length > 0) { 3786 b.verificationMaterial.tlogEntries.forEach((entry, i) => { 3787 if (entry.logId === undefined) { 3788 invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`); 3789 } 3790 if (entry.kindVersion === undefined) { 3791 invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`); 3792 } 3793 }); 3794 } 3795 } 3796 } 3797 return invalidValues; 3798 } 3799 // Necessary for V01 bundles 3800 function validateInclusionPromise(b) { 3801 const invalidValues = []; 3802 if (b.verificationMaterial && 3803 b.verificationMaterial.tlogEntries?.length > 0) { 3804 b.verificationMaterial.tlogEntries.forEach((entry, i) => { 3805 if (entry.inclusionPromise === undefined) { 3806 invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`); 3807 } 3808 }); 3809 } 3810 return invalidValues; 3811 } 3812 // Necessary for V02 and later bundles 3813 function validateInclusionProof(b) { 3814 const invalidValues = []; 3815 if (b.verificationMaterial && 3816 b.verificationMaterial.tlogEntries?.length > 0) { 3817 b.verificationMaterial.tlogEntries.forEach((entry, i) => { 3818 if (entry.inclusionProof === undefined) { 3819 invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`); 3820 } 3821 else { 3822 if (entry.inclusionProof.checkpoint === undefined) { 3823 invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`); 3824 } 3825 } 3826 }); 3827 } 3828 return invalidValues; 3829 } 3830 // Necessary for V03 and later bundles 3831 function validateNoCertificateChain(b) { 3832 const invalidValues = []; 3833 if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') { 3834 invalidValues.push('verificationMaterial.content.$case'); 3835 } 3836 return invalidValues; 3837 } 3838 3839 3840 /***/ }), 3841 3842 /***/ 6136: 3843 /***/ ((__unused_webpack_module, exports) => { 3844 3845 "use strict"; 3846 3847 Object.defineProperty(exports, "__esModule", ({ value: true })); 3848 exports.ASN1TypeError = exports.ASN1ParseError = void 0; 3849 /* 3850 Copyright 2023 The Sigstore Authors. 3851 3852 Licensed under the Apache License, Version 2.0 (the "License"); 3853 you may not use this file except in compliance with the License. 3854 You may obtain a copy of the License at 3855 3856 http://www.apache.org/licenses/LICENSE-2.0 3857 3858 Unless required by applicable law or agreed to in writing, software 3859 distributed under the License is distributed on an "AS IS" BASIS, 3860 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3861 See the License for the specific language governing permissions and 3862 limitations under the License. 3863 */ 3864 class ASN1ParseError extends Error { 3865 } 3866 exports.ASN1ParseError = ASN1ParseError; 3867 class ASN1TypeError extends Error { 3868 } 3869 exports.ASN1TypeError = ASN1TypeError; 3870 3871 3872 /***/ }), 3873 3874 /***/ 4095: 3875 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3876 3877 "use strict"; 3878 3879 Object.defineProperty(exports, "__esModule", ({ value: true })); 3880 exports.ASN1Obj = void 0; 3881 /* 3882 Copyright 2023 The Sigstore Authors. 3883 3884 Licensed under the Apache License, Version 2.0 (the "License"); 3885 you may not use this file except in compliance with the License. 3886 You may obtain a copy of the License at 3887 3888 http://www.apache.org/licenses/LICENSE-2.0 3889 3890 Unless required by applicable law or agreed to in writing, software 3891 distributed under the License is distributed on an "AS IS" BASIS, 3892 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3893 See the License for the specific language governing permissions and 3894 limitations under the License. 3895 */ 3896 var obj_1 = __nccwpck_require__(2988); 3897 Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return obj_1.ASN1Obj; } })); 3898 3899 3900 /***/ }), 3901 3902 /***/ 5088: 3903 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3904 3905 "use strict"; 3906 3907 /* 3908 Copyright 2023 The Sigstore Authors. 3909 3910 Licensed under the Apache License, Version 2.0 (the "License"); 3911 you may not use this file except in compliance with the License. 3912 You may obtain a copy of the License at 3913 3914 http://www.apache.org/licenses/LICENSE-2.0 3915 3916 Unless required by applicable law or agreed to in writing, software 3917 distributed under the License is distributed on an "AS IS" BASIS, 3918 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3919 See the License for the specific language governing permissions and 3920 limitations under the License. 3921 */ 3922 Object.defineProperty(exports, "__esModule", ({ value: true })); 3923 exports.encodeLength = exports.decodeLength = void 0; 3924 const error_1 = __nccwpck_require__(6136); 3925 // Decodes the length of a DER-encoded ANS.1 element from the supplied stream. 3926 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes 3927 function decodeLength(stream) { 3928 const buf = stream.getUint8(); 3929 // If the most significant bit is UNSET the length is just the value of the 3930 // byte. 3931 if ((buf & 0x80) === 0x00) { 3932 return buf; 3933 } 3934 // Otherwise, the lower 7 bits of the first byte indicate the number of bytes 3935 // that follow to encode the length. 3936 const byteCount = buf & 0x7f; 3937 // Ensure the encoded length can safely fit in a JS number. 3938 if (byteCount > 6) { 3939 throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); 3940 } 3941 // Iterate over the bytes that encode the length. 3942 let len = 0; 3943 for (let i = 0; i < byteCount; i++) { 3944 len = len * 256 + stream.getUint8(); 3945 } 3946 // This is a valid ASN.1 length encoding, but we don't support it. 3947 if (len === 0) { 3948 throw new error_1.ASN1ParseError('indefinite length encoding not supported'); 3949 } 3950 return len; 3951 } 3952 exports.decodeLength = decodeLength; 3953 // Translates the supplied value to a DER-encoded length. 3954 function encodeLength(len) { 3955 if (len < 128) { 3956 return Buffer.from([len]); 3957 } 3958 // Bitwise operations on large numbers are not supported in JS, so we need to 3959 // use BigInts. 3960 let val = BigInt(len); 3961 const bytes = []; 3962 while (val > 0n) { 3963 bytes.unshift(Number(val & 255n)); 3964 val = val >> 8n; 3965 } 3966 return Buffer.from([0x80 | bytes.length, ...bytes]); 3967 } 3968 exports.encodeLength = encodeLength; 3969 3970 3971 /***/ }), 3972 3973 /***/ 2988: 3974 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 3975 3976 "use strict"; 3977 3978 Object.defineProperty(exports, "__esModule", ({ value: true })); 3979 exports.ASN1Obj = void 0; 3980 /* 3981 Copyright 2023 The Sigstore Authors. 3982 3983 Licensed under the Apache License, Version 2.0 (the "License"); 3984 you may not use this file except in compliance with the License. 3985 You may obtain a copy of the License at 3986 3987 http://www.apache.org/licenses/LICENSE-2.0 3988 3989 Unless required by applicable law or agreed to in writing, software 3990 distributed under the License is distributed on an "AS IS" BASIS, 3991 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3992 See the License for the specific language governing permissions and 3993 limitations under the License. 3994 */ 3995 const stream_1 = __nccwpck_require__(2283); 3996 const error_1 = __nccwpck_require__(6136); 3997 const length_1 = __nccwpck_require__(5088); 3998 const parse_1 = __nccwpck_require__(3947); 3999 const tag_1 = __nccwpck_require__(3725); 4000 class ASN1Obj { 4001 constructor(tag, value, subs) { 4002 this.tag = tag; 4003 this.value = value; 4004 this.subs = subs; 4005 } 4006 // Constructs an ASN.1 object from a Buffer of DER-encoded bytes. 4007 static parseBuffer(buf) { 4008 return parseStream(new stream_1.ByteStream(buf)); 4009 } 4010 toDER() { 4011 const valueStream = new stream_1.ByteStream(); 4012 if (this.subs.length > 0) { 4013 for (const sub of this.subs) { 4014 valueStream.appendView(sub.toDER()); 4015 } 4016 } 4017 else { 4018 valueStream.appendView(this.value); 4019 } 4020 const value = valueStream.buffer; 4021 // Concat tag/length/value 4022 const obj = new stream_1.ByteStream(); 4023 obj.appendChar(this.tag.toDER()); 4024 obj.appendView((0, length_1.encodeLength)(value.length)); 4025 obj.appendView(value); 4026 return obj.buffer; 4027 } 4028 ///////////////////////////////////////////////////////////////////////////// 4029 // Convenience methods for parsing ASN.1 primitives into JS types 4030 // Returns the ASN.1 object's value as a boolean. Throws an error if the 4031 // object is not a boolean. 4032 toBoolean() { 4033 if (!this.tag.isBoolean()) { 4034 throw new error_1.ASN1TypeError('not a boolean'); 4035 } 4036 return (0, parse_1.parseBoolean)(this.value); 4037 } 4038 // Returns the ASN.1 object's value as a BigInt. Throws an error if the 4039 // object is not an integer. 4040 toInteger() { 4041 if (!this.tag.isInteger()) { 4042 throw new error_1.ASN1TypeError('not an integer'); 4043 } 4044 return (0, parse_1.parseInteger)(this.value); 4045 } 4046 // Returns the ASN.1 object's value as an OID string. Throws an error if the 4047 // object is not an OID. 4048 toOID() { 4049 if (!this.tag.isOID()) { 4050 throw new error_1.ASN1TypeError('not an OID'); 4051 } 4052 return (0, parse_1.parseOID)(this.value); 4053 } 4054 // Returns the ASN.1 object's value as a Date. Throws an error if the object 4055 // is not either a UTCTime or a GeneralizedTime. 4056 toDate() { 4057 switch (true) { 4058 case this.tag.isUTCTime(): 4059 return (0, parse_1.parseTime)(this.value, true); 4060 case this.tag.isGeneralizedTime(): 4061 return (0, parse_1.parseTime)(this.value, false); 4062 default: 4063 throw new error_1.ASN1TypeError('not a date'); 4064 } 4065 } 4066 // Returns the ASN.1 object's value as a number[] where each number is the 4067 // value of a bit in the bit string. Throws an error if the object is not a 4068 // bit string. 4069 toBitString() { 4070 if (!this.tag.isBitString()) { 4071 throw new error_1.ASN1TypeError('not a bit string'); 4072 } 4073 return (0, parse_1.parseBitString)(this.value); 4074 } 4075 } 4076 exports.ASN1Obj = ASN1Obj; 4077 ///////////////////////////////////////////////////////////////////////////// 4078 // Internal stream parsing functions 4079 function parseStream(stream) { 4080 // Parse tag, length, and value from stream 4081 const tag = new tag_1.ASN1Tag(stream.getUint8()); 4082 const len = (0, length_1.decodeLength)(stream); 4083 const value = stream.slice(stream.position, len); 4084 const start = stream.position; 4085 let subs = []; 4086 // If the object is constructed, parse its children. Sometimes, children 4087 // are embedded in OCTESTRING objects, so we need to check those 4088 // for children as well. 4089 if (tag.constructed) { 4090 subs = collectSubs(stream, len); 4091 } 4092 else if (tag.isOctetString()) { 4093 // Attempt to parse children of OCTETSTRING objects. If anything fails, 4094 // assume the object is not constructed and treat as primitive. 4095 try { 4096 subs = collectSubs(stream, len); 4097 } 4098 catch (e) { 4099 // Fail silently and treat as primitive 4100 } 4101 } 4102 // If there are no children, move stream cursor to the end of the object 4103 if (subs.length === 0) { 4104 stream.seek(start + len); 4105 } 4106 return new ASN1Obj(tag, value, subs); 4107 } 4108 function collectSubs(stream, len) { 4109 // Calculate end of object content 4110 const end = stream.position + len; 4111 // Make sure there are enough bytes left in the stream. This should never 4112 // happen, cause it'll get caught when the stream is sliced in parseStream. 4113 // Leaving as an extra check just in case. 4114 /* istanbul ignore if */ 4115 if (end > stream.length) { 4116 throw new error_1.ASN1ParseError('invalid length'); 4117 } 4118 // Parse all children 4119 const subs = []; 4120 while (stream.position < end) { 4121 subs.push(parseStream(stream)); 4122 } 4123 // When we're done parsing children, we should be at the end of the object 4124 if (stream.position !== end) { 4125 throw new error_1.ASN1ParseError('invalid length'); 4126 } 4127 return subs; 4128 } 4129 4130 4131 /***/ }), 4132 4133 /***/ 3947: 4134 /***/ ((__unused_webpack_module, exports) => { 4135 4136 "use strict"; 4137 4138 Object.defineProperty(exports, "__esModule", ({ value: true })); 4139 exports.parseBitString = exports.parseBoolean = exports.parseOID = exports.parseTime = exports.parseStringASCII = exports.parseInteger = void 0; 4140 /* 4141 Copyright 2023 The Sigstore Authors. 4142 4143 Licensed under the Apache License, Version 2.0 (the "License"); 4144 you may not use this file except in compliance with the License. 4145 You may obtain a copy of the License at 4146 4147 http://www.apache.org/licenses/LICENSE-2.0 4148 4149 Unless required by applicable law or agreed to in writing, software 4150 distributed under the License is distributed on an "AS IS" BASIS, 4151 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4152 See the License for the specific language governing permissions and 4153 limitations under the License. 4154 */ 4155 const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; 4156 const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; 4157 // Parse a BigInt from the DER-encoded buffer 4158 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer 4159 function parseInteger(buf) { 4160 let pos = 0; 4161 const end = buf.length; 4162 let val = buf[pos]; 4163 const neg = val > 0x7f; 4164 // Consume any padding bytes 4165 const pad = neg ? 0xff : 0x00; 4166 while (val == pad && ++pos < end) { 4167 val = buf[pos]; 4168 } 4169 // Calculate remaining bytes to read 4170 const len = end - pos; 4171 if (len === 0) 4172 return BigInt(neg ? -1 : 0); 4173 // Handle two's complement for negative numbers 4174 val = neg ? val - 256 : val; 4175 // Parse remaining bytes 4176 let n = BigInt(val); 4177 for (let i = pos + 1; i < end; ++i) { 4178 n = n * BigInt(256) + BigInt(buf[i]); 4179 } 4180 return n; 4181 } 4182 exports.parseInteger = parseInteger; 4183 // Parse an ASCII string from the DER-encoded buffer 4184 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean 4185 function parseStringASCII(buf) { 4186 return buf.toString('ascii'); 4187 } 4188 exports.parseStringASCII = parseStringASCII; 4189 // Parse a Date from the DER-encoded buffer 4190 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1 4191 function parseTime(buf, shortYear) { 4192 const timeStr = parseStringASCII(buf); 4193 // Parse the time string into matches - captured groups start at index 1 4194 const m = shortYear 4195 ? RE_TIME_SHORT_YEAR.exec(timeStr) 4196 : RE_TIME_LONG_YEAR.exec(timeStr); 4197 if (!m) { 4198 throw new Error('invalid time'); 4199 } 4200 // Translate dates with a 2-digit year to 4 digits per the spec 4201 if (shortYear) { 4202 let year = Number(m[1]); 4203 year += year >= 50 ? 1900 : 2000; 4204 m[1] = year.toString(); 4205 } 4206 // Translate to ISO8601 format and parse 4207 return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`); 4208 } 4209 exports.parseTime = parseTime; 4210 // Parse an OID from the DER-encoded buffer 4211 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier 4212 function parseOID(buf) { 4213 let pos = 0; 4214 const end = buf.length; 4215 // Consume first byte which encodes the first two OID components 4216 let n = buf[pos++]; 4217 const first = Math.floor(n / 40); 4218 const second = n % 40; 4219 let oid = `${first}.${second}`; 4220 // Consume remaining bytes 4221 let val = 0; 4222 for (; pos < end; ++pos) { 4223 n = buf[pos]; 4224 val = (val << 7) + (n & 0x7f); 4225 // If the left-most bit is NOT set, then this is the last byte in the 4226 // sequence and we can add the value to the OID and reset the accumulator 4227 if ((n & 0x80) === 0) { 4228 oid += `.${val}`; 4229 val = 0; 4230 } 4231 } 4232 return oid; 4233 } 4234 exports.parseOID = parseOID; 4235 // Parse a boolean from the DER-encoded buffer 4236 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean 4237 function parseBoolean(buf) { 4238 return buf[0] !== 0; 4239 } 4240 exports.parseBoolean = parseBoolean; 4241 // Parse a bit string from the DER-encoded buffer 4242 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string 4243 function parseBitString(buf) { 4244 // First byte tell us how many unused bits are in the last byte 4245 const unused = buf[0]; 4246 const start = 1; 4247 const end = buf.length; 4248 const bits = []; 4249 for (let i = start; i < end; ++i) { 4250 const byte = buf[i]; 4251 // The skip value is only used for the last byte 4252 const skip = i === end - 1 ? unused : 0; 4253 // Iterate over each bit in the byte (most significant first) 4254 for (let j = 7; j >= skip; --j) { 4255 // Read the bit and add it to the bit string 4256 bits.push((byte >> j) & 0x01); 4257 } 4258 } 4259 return bits; 4260 } 4261 exports.parseBitString = parseBitString; 4262 4263 4264 /***/ }), 4265 4266 /***/ 3725: 4267 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 4268 4269 "use strict"; 4270 4271 Object.defineProperty(exports, "__esModule", ({ value: true })); 4272 exports.ASN1Tag = void 0; 4273 /* 4274 Copyright 2023 The Sigstore Authors. 4275 4276 Licensed under the Apache License, Version 2.0 (the "License"); 4277 you may not use this file except in compliance with the License. 4278 You may obtain a copy of the License at 4279 4280 http://www.apache.org/licenses/LICENSE-2.0 4281 4282 Unless required by applicable law or agreed to in writing, software 4283 distributed under the License is distributed on an "AS IS" BASIS, 4284 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4285 See the License for the specific language governing permissions and 4286 limitations under the License. 4287 */ 4288 const error_1 = __nccwpck_require__(6136); 4289 const UNIVERSAL_TAG = { 4290 BOOLEAN: 0x01, 4291 INTEGER: 0x02, 4292 BIT_STRING: 0x03, 4293 OCTET_STRING: 0x04, 4294 OBJECT_IDENTIFIER: 0x06, 4295 SEQUENCE: 0x10, 4296 SET: 0x11, 4297 PRINTABLE_STRING: 0x13, 4298 UTC_TIME: 0x17, 4299 GENERALIZED_TIME: 0x18, 4300 }; 4301 const TAG_CLASS = { 4302 UNIVERSAL: 0x00, 4303 APPLICATION: 0x01, 4304 CONTEXT_SPECIFIC: 0x02, 4305 PRIVATE: 0x03, 4306 }; 4307 // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes 4308 class ASN1Tag { 4309 constructor(enc) { 4310 // Bits 0 through 4 are the tag number 4311 this.number = enc & 0x1f; 4312 // Bit 5 is the constructed bit 4313 this.constructed = (enc & 0x20) === 0x20; 4314 // Bit 6 & 7 are the class 4315 this.class = enc >> 6; 4316 if (this.number === 0x1f) { 4317 throw new error_1.ASN1ParseError('long form tags not supported'); 4318 } 4319 if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) { 4320 throw new error_1.ASN1ParseError('unsupported tag 0x00'); 4321 } 4322 } 4323 isUniversal() { 4324 return this.class === TAG_CLASS.UNIVERSAL; 4325 } 4326 isContextSpecific(num) { 4327 const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC; 4328 return num !== undefined ? res && this.number === num : res; 4329 } 4330 isBoolean() { 4331 return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN; 4332 } 4333 isInteger() { 4334 return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER; 4335 } 4336 isBitString() { 4337 return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING; 4338 } 4339 isOctetString() { 4340 return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING; 4341 } 4342 isOID() { 4343 return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER); 4344 } 4345 isUTCTime() { 4346 return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME; 4347 } 4348 isGeneralizedTime() { 4349 return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME; 4350 } 4351 toDER() { 4352 return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6); 4353 } 4354 } 4355 exports.ASN1Tag = ASN1Tag; 4356 4357 4358 /***/ }), 4359 4360 /***/ 3914: 4361 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 4362 4363 "use strict"; 4364 4365 var __importDefault = (this && this.__importDefault) || function (mod) { 4366 return (mod && mod.__esModule) ? mod : { "default": mod }; 4367 }; 4368 Object.defineProperty(exports, "__esModule", ({ value: true })); 4369 exports.bufferEqual = exports.verify = exports.hash = exports.digest = exports.createPublicKey = void 0; 4370 /* 4371 Copyright 2023 The Sigstore Authors. 4372 4373 Licensed under the Apache License, Version 2.0 (the "License"); 4374 you may not use this file except in compliance with the License. 4375 You may obtain a copy of the License at 4376 4377 http://www.apache.org/licenses/LICENSE-2.0 4378 4379 Unless required by applicable law or agreed to in writing, software 4380 distributed under the License is distributed on an "AS IS" BASIS, 4381 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4382 See the License for the specific language governing permissions and 4383 limitations under the License. 4384 */ 4385 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 4386 const SHA256_ALGORITHM = 'sha256'; 4387 function createPublicKey(key, type = 'spki') { 4388 if (typeof key === 'string') { 4389 return crypto_1.default.createPublicKey(key); 4390 } 4391 else { 4392 return crypto_1.default.createPublicKey({ key, format: 'der', type: type }); 4393 } 4394 } 4395 exports.createPublicKey = createPublicKey; 4396 function digest(algorithm, ...data) { 4397 const hash = crypto_1.default.createHash(algorithm); 4398 for (const d of data) { 4399 hash.update(d); 4400 } 4401 return hash.digest(); 4402 } 4403 exports.digest = digest; 4404 // TODO: deprecate this in favor of digest() 4405 function hash(...data) { 4406 const hash = crypto_1.default.createHash(SHA256_ALGORITHM); 4407 for (const d of data) { 4408 hash.update(d); 4409 } 4410 return hash.digest(); 4411 } 4412 exports.hash = hash; 4413 function verify(data, key, signature, algorithm) { 4414 // The try/catch is to work around an issue in Node 14.x where verify throws 4415 // an error in some scenarios if the signature is invalid. 4416 try { 4417 return crypto_1.default.verify(algorithm, data, key, signature); 4418 } 4419 catch (e) { 4420 /* istanbul ignore next */ 4421 return false; 4422 } 4423 } 4424 exports.verify = verify; 4425 function bufferEqual(a, b) { 4426 try { 4427 return crypto_1.default.timingSafeEqual(a, b); 4428 } 4429 catch { 4430 /* istanbul ignore next */ 4431 return false; 4432 } 4433 } 4434 exports.bufferEqual = bufferEqual; 4435 4436 4437 /***/ }), 4438 4439 /***/ 9892: 4440 /***/ ((__unused_webpack_module, exports) => { 4441 4442 "use strict"; 4443 4444 Object.defineProperty(exports, "__esModule", ({ value: true })); 4445 exports.preAuthEncoding = void 0; 4446 /* 4447 Copyright 2023 The Sigstore Authors. 4448 4449 Licensed under the Apache License, Version 2.0 (the "License"); 4450 you may not use this file except in compliance with the License. 4451 You may obtain a copy of the License at 4452 4453 http://www.apache.org/licenses/LICENSE-2.0 4454 4455 Unless required by applicable law or agreed to in writing, software 4456 distributed under the License is distributed on an "AS IS" BASIS, 4457 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4458 See the License for the specific language governing permissions and 4459 limitations under the License. 4460 */ 4461 const PAE_PREFIX = 'DSSEv1'; 4462 // DSSE Pre-Authentication Encoding 4463 function preAuthEncoding(payloadType, payload) { 4464 const prefix = [ 4465 PAE_PREFIX, 4466 payloadType.length, 4467 payloadType, 4468 payload.length, 4469 '', 4470 ].join(' '); 4471 return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]); 4472 } 4473 exports.preAuthEncoding = preAuthEncoding; 4474 4475 4476 /***/ }), 4477 4478 /***/ 7496: 4479 /***/ ((__unused_webpack_module, exports) => { 4480 4481 "use strict"; 4482 4483 Object.defineProperty(exports, "__esModule", ({ value: true })); 4484 exports.base64Decode = exports.base64Encode = void 0; 4485 /* 4486 Copyright 2023 The Sigstore Authors. 4487 4488 Licensed under the Apache License, Version 2.0 (the "License"); 4489 you may not use this file except in compliance with the License. 4490 You may obtain a copy of the License at 4491 4492 http://www.apache.org/licenses/LICENSE-2.0 4493 4494 Unless required by applicable law or agreed to in writing, software 4495 distributed under the License is distributed on an "AS IS" BASIS, 4496 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4497 See the License for the specific language governing permissions and 4498 limitations under the License. 4499 */ 4500 const BASE64_ENCODING = 'base64'; 4501 const UTF8_ENCODING = 'utf-8'; 4502 function base64Encode(str) { 4503 return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); 4504 } 4505 exports.base64Encode = base64Encode; 4506 function base64Decode(str) { 4507 return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); 4508 } 4509 exports.base64Decode = base64Decode; 4510 4511 4512 /***/ }), 4513 4514 /***/ 3352: 4515 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 4516 4517 "use strict"; 4518 4519 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 4520 if (k2 === undefined) k2 = k; 4521 var desc = Object.getOwnPropertyDescriptor(m, k); 4522 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 4523 desc = { enumerable: true, get: function() { return m[k]; } }; 4524 } 4525 Object.defineProperty(o, k2, desc); 4526 }) : (function(o, m, k, k2) { 4527 if (k2 === undefined) k2 = k; 4528 o[k2] = m[k]; 4529 })); 4530 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 4531 Object.defineProperty(o, "default", { enumerable: true, value: v }); 4532 }) : function(o, v) { 4533 o["default"] = v; 4534 }); 4535 var __importStar = (this && this.__importStar) || function (mod) { 4536 if (mod && mod.__esModule) return mod; 4537 var result = {}; 4538 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 4539 __setModuleDefault(result, mod); 4540 return result; 4541 }; 4542 Object.defineProperty(exports, "__esModule", ({ value: true })); 4543 exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0; 4544 /* 4545 Copyright 2023 The Sigstore Authors. 4546 4547 Licensed under the Apache License, Version 2.0 (the "License"); 4548 you may not use this file except in compliance with the License. 4549 You may obtain a copy of the License at 4550 4551 http://www.apache.org/licenses/LICENSE-2.0 4552 4553 Unless required by applicable law or agreed to in writing, software 4554 distributed under the License is distributed on an "AS IS" BASIS, 4555 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4556 See the License for the specific language governing permissions and 4557 limitations under the License. 4558 */ 4559 var asn1_1 = __nccwpck_require__(4095); 4560 Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return asn1_1.ASN1Obj; } })); 4561 exports.crypto = __importStar(__nccwpck_require__(3914)); 4562 exports.dsse = __importStar(__nccwpck_require__(9892)); 4563 exports.encoding = __importStar(__nccwpck_require__(7496)); 4564 exports.json = __importStar(__nccwpck_require__(9022)); 4565 exports.pem = __importStar(__nccwpck_require__(5225)); 4566 var rfc3161_1 = __nccwpck_require__(7411); 4567 Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } })); 4568 var stream_1 = __nccwpck_require__(2283); 4569 Object.defineProperty(exports, "ByteStream", ({ enumerable: true, get: function () { return stream_1.ByteStream; } })); 4570 var x509_1 = __nccwpck_require__(5500); 4571 Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } })); 4572 Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return x509_1.X509Certificate; } })); 4573 Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return x509_1.X509SCTExtension; } })); 4574 4575 4576 /***/ }), 4577 4578 /***/ 9022: 4579 /***/ ((__unused_webpack_module, exports) => { 4580 4581 "use strict"; 4582 4583 /* 4584 Copyright 2023 The Sigstore Authors. 4585 4586 Licensed under the Apache License, Version 2.0 (the "License"); 4587 you may not use this file except in compliance with the License. 4588 You may obtain a copy of the License at 4589 4590 http://www.apache.org/licenses/LICENSE-2.0 4591 4592 Unless required by applicable law or agreed to in writing, software 4593 distributed under the License is distributed on an "AS IS" BASIS, 4594 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4595 See the License for the specific language governing permissions and 4596 limitations under the License. 4597 */ 4598 Object.defineProperty(exports, "__esModule", ({ value: true })); 4599 exports.canonicalize = void 0; 4600 // JSON canonicalization per https://github.com/cyberphone/json-canonicalization 4601 // eslint-disable-next-line @typescript-eslint/no-explicit-any 4602 function canonicalize(object) { 4603 let buffer = ''; 4604 if (object === null || typeof object !== 'object' || object.toJSON != null) { 4605 // Primitives or toJSONable objects 4606 buffer += JSON.stringify(object); 4607 } 4608 else if (Array.isArray(object)) { 4609 // Array - maintain element order 4610 buffer += '['; 4611 let first = true; 4612 object.forEach((element) => { 4613 if (!first) { 4614 buffer += ','; 4615 } 4616 first = false; 4617 // recursive call 4618 buffer += canonicalize(element); 4619 }); 4620 buffer += ']'; 4621 } 4622 else { 4623 // Object - Sort properties before serializing 4624 buffer += '{'; 4625 let first = true; 4626 Object.keys(object) 4627 .sort() 4628 .forEach((property) => { 4629 if (!first) { 4630 buffer += ','; 4631 } 4632 first = false; 4633 buffer += JSON.stringify(property); 4634 buffer += ':'; 4635 // recursive call 4636 buffer += canonicalize(object[property]); 4637 }); 4638 buffer += '}'; 4639 } 4640 return buffer; 4641 } 4642 exports.canonicalize = canonicalize; 4643 4644 4645 /***/ }), 4646 4647 /***/ 5960: 4648 /***/ ((__unused_webpack_module, exports) => { 4649 4650 "use strict"; 4651 4652 Object.defineProperty(exports, "__esModule", ({ value: true })); 4653 exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0; 4654 exports.ECDSA_SIGNATURE_ALGOS = { 4655 '1.2.840.10045.4.3.1': 'sha224', 4656 '1.2.840.10045.4.3.2': 'sha256', 4657 '1.2.840.10045.4.3.3': 'sha384', 4658 '1.2.840.10045.4.3.4': 'sha512', 4659 }; 4660 exports.SHA2_HASH_ALGOS = { 4661 '2.16.840.1.101.3.4.2.1': 'sha256', 4662 '2.16.840.1.101.3.4.2.2': 'sha384', 4663 '2.16.840.1.101.3.4.2.3': 'sha512', 4664 }; 4665 4666 4667 /***/ }), 4668 4669 /***/ 5225: 4670 /***/ ((__unused_webpack_module, exports) => { 4671 4672 "use strict"; 4673 4674 Object.defineProperty(exports, "__esModule", ({ value: true })); 4675 exports.fromDER = exports.toDER = void 0; 4676 /* 4677 Copyright 2023 The Sigstore Authors. 4678 4679 Licensed under the Apache License, Version 2.0 (the "License"); 4680 you may not use this file except in compliance with the License. 4681 You may obtain a copy of the License at 4682 4683 http://www.apache.org/licenses/LICENSE-2.0 4684 4685 Unless required by applicable law or agreed to in writing, software 4686 distributed under the License is distributed on an "AS IS" BASIS, 4687 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4688 See the License for the specific language governing permissions and 4689 limitations under the License. 4690 */ 4691 const PEM_HEADER = /-----BEGIN (.*)-----/; 4692 const PEM_FOOTER = /-----END (.*)-----/; 4693 function toDER(certificate) { 4694 let der = ''; 4695 certificate.split('\n').forEach((line) => { 4696 if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) { 4697 return; 4698 } 4699 der += line; 4700 }); 4701 return Buffer.from(der, 'base64'); 4702 } 4703 exports.toDER = toDER; 4704 // Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM 4705 // encoding dictates that each certificate should have a trailing newline after 4706 // the footer. 4707 function fromDER(certificate, type = 'CERTIFICATE') { 4708 // Base64-encode the certificate. 4709 const der = certificate.toString('base64'); 4710 // Split the certificate into lines of 64 characters. 4711 const lines = der.match(/.{1,64}/g) || ''; 4712 return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`] 4713 .join('\n') 4714 .concat('\n'); 4715 } 4716 exports.fromDER = fromDER; 4717 4718 4719 /***/ }), 4720 4721 /***/ 4526: 4722 /***/ ((__unused_webpack_module, exports) => { 4723 4724 "use strict"; 4725 4726 Object.defineProperty(exports, "__esModule", ({ value: true })); 4727 exports.RFC3161TimestampVerificationError = void 0; 4728 /* 4729 Copyright 2023 The Sigstore Authors. 4730 4731 Licensed under the Apache License, Version 2.0 (the "License"); 4732 you may not use this file except in compliance with the License. 4733 You may obtain a copy of the License at 4734 4735 http://www.apache.org/licenses/LICENSE-2.0 4736 4737 Unless required by applicable law or agreed to in writing, software 4738 distributed under the License is distributed on an "AS IS" BASIS, 4739 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4740 See the License for the specific language governing permissions and 4741 limitations under the License. 4742 */ 4743 class RFC3161TimestampVerificationError extends Error { 4744 } 4745 exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError; 4746 4747 4748 /***/ }), 4749 4750 /***/ 7411: 4751 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 4752 4753 "use strict"; 4754 4755 /* 4756 Copyright 2023 The Sigstore Authors. 4757 4758 Licensed under the Apache License, Version 2.0 (the "License"); 4759 you may not use this file except in compliance with the License. 4760 You may obtain a copy of the License at 4761 4762 http://www.apache.org/licenses/LICENSE-2.0 4763 4764 Unless required by applicable law or agreed to in writing, software 4765 distributed under the License is distributed on an "AS IS" BASIS, 4766 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4767 See the License for the specific language governing permissions and 4768 limitations under the License. 4769 */ 4770 Object.defineProperty(exports, "__esModule", ({ value: true })); 4771 exports.RFC3161Timestamp = void 0; 4772 var timestamp_1 = __nccwpck_require__(9180); 4773 Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } })); 4774 4775 4776 /***/ }), 4777 4778 /***/ 9180: 4779 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 4780 4781 "use strict"; 4782 4783 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 4784 if (k2 === undefined) k2 = k; 4785 var desc = Object.getOwnPropertyDescriptor(m, k); 4786 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 4787 desc = { enumerable: true, get: function() { return m[k]; } }; 4788 } 4789 Object.defineProperty(o, k2, desc); 4790 }) : (function(o, m, k, k2) { 4791 if (k2 === undefined) k2 = k; 4792 o[k2] = m[k]; 4793 })); 4794 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 4795 Object.defineProperty(o, "default", { enumerable: true, value: v }); 4796 }) : function(o, v) { 4797 o["default"] = v; 4798 }); 4799 var __importStar = (this && this.__importStar) || function (mod) { 4800 if (mod && mod.__esModule) return mod; 4801 var result = {}; 4802 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 4803 __setModuleDefault(result, mod); 4804 return result; 4805 }; 4806 Object.defineProperty(exports, "__esModule", ({ value: true })); 4807 exports.RFC3161Timestamp = void 0; 4808 /* 4809 Copyright 2023 The Sigstore Authors. 4810 4811 Licensed under the Apache License, Version 2.0 (the "License"); 4812 you may not use this file except in compliance with the License. 4813 You may obtain a copy of the License at 4814 4815 http://www.apache.org/licenses/LICENSE-2.0 4816 4817 Unless required by applicable law or agreed to in writing, software 4818 distributed under the License is distributed on an "AS IS" BASIS, 4819 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4820 See the License for the specific language governing permissions and 4821 limitations under the License. 4822 */ 4823 const asn1_1 = __nccwpck_require__(4095); 4824 const crypto = __importStar(__nccwpck_require__(3914)); 4825 const oid_1 = __nccwpck_require__(5960); 4826 const error_1 = __nccwpck_require__(4526); 4827 const tstinfo_1 = __nccwpck_require__(6368); 4828 const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2'; 4829 const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4'; 4830 const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4'; 4831 class RFC3161Timestamp { 4832 constructor(asn1) { 4833 this.root = asn1; 4834 } 4835 static parse(der) { 4836 const asn1 = asn1_1.ASN1Obj.parseBuffer(der); 4837 return new RFC3161Timestamp(asn1); 4838 } 4839 get status() { 4840 return this.pkiStatusInfoObj.subs[0].toInteger(); 4841 } 4842 get contentType() { 4843 return this.contentTypeObj.toOID(); 4844 } 4845 get eContentType() { 4846 return this.eContentTypeObj.toOID(); 4847 } 4848 get signingTime() { 4849 return this.tstInfo.genTime; 4850 } 4851 get signerIssuer() { 4852 return this.signerSidObj.subs[0].value; 4853 } 4854 get signerSerialNumber() { 4855 return this.signerSidObj.subs[1].value; 4856 } 4857 get signerDigestAlgorithm() { 4858 const oid = this.signerDigestAlgorithmObj.subs[0].toOID(); 4859 return oid_1.SHA2_HASH_ALGOS[oid]; 4860 } 4861 get signatureAlgorithm() { 4862 const oid = this.signatureAlgorithmObj.subs[0].toOID(); 4863 return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; 4864 } 4865 get signatureValue() { 4866 return this.signatureValueObj.value; 4867 } 4868 get tstInfo() { 4869 // Need to unpack tstInfo from an OCTET STRING 4870 return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]); 4871 } 4872 verify(data, publicKey) { 4873 if (!this.timeStampTokenObj) { 4874 throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing'); 4875 } 4876 // Check for expected ContentInfo content type 4877 if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) { 4878 throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`); 4879 } 4880 // Check for expected encapsulated content type 4881 if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) { 4882 throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`); 4883 } 4884 // Check that the tstInfo references the correct artifact 4885 this.tstInfo.verify(data); 4886 // Check that the signed message digest matches the tstInfo 4887 this.verifyMessageDigest(); 4888 // Check that the signature is valid for the signed attributes 4889 this.verifySignature(publicKey); 4890 } 4891 verifyMessageDigest() { 4892 // Check that the tstInfo matches the signed data 4893 const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw); 4894 const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value; 4895 if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) { 4896 throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo'); 4897 } 4898 } 4899 verifySignature(key) { 4900 // Encode the signed attributes for verification 4901 const signedAttrs = this.signedAttrsObj.toDER(); 4902 signedAttrs[0] = 0x31; // Change context-specific tag to SET 4903 // Check that the signature is valid for the signed attributes 4904 const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm); 4905 if (!verified) { 4906 throw new error_1.RFC3161TimestampVerificationError('signature verification failed'); 4907 } 4908 } 4909 // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 4910 get pkiStatusInfoObj() { 4911 // pkiStatusInfo is the first element of the timestamp response sequence 4912 return this.root.subs[0]; 4913 } 4914 // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 4915 get timeStampTokenObj() { 4916 // timeStampToken is the first element of the timestamp response sequence 4917 return this.root.subs[1]; 4918 } 4919 // https://datatracker.ietf.org/doc/html/rfc5652#section-3 4920 get contentTypeObj() { 4921 return this.timeStampTokenObj.subs[0]; 4922 } 4923 // https://www.rfc-editor.org/rfc/rfc5652#section-3 4924 get signedDataObj() { 4925 const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); 4926 return obj.subs[0]; 4927 } 4928 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 4929 get encapContentInfoObj() { 4930 return this.signedDataObj.subs[2]; 4931 } 4932 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 4933 get signerInfosObj() { 4934 // SignerInfos is the last element of the signed data sequence 4935 const sd = this.signedDataObj; 4936 return sd.subs[sd.subs.length - 1]; 4937 } 4938 // https://www.rfc-editor.org/rfc/rfc5652#section-5.1 4939 get signerInfoObj() { 4940 // Only supporting one signer 4941 return this.signerInfosObj.subs[0]; 4942 } 4943 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 4944 get eContentTypeObj() { 4945 return this.encapContentInfoObj.subs[0]; 4946 } 4947 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 4948 get eContentObj() { 4949 return this.encapContentInfoObj.subs[1]; 4950 } 4951 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4952 get signedAttrsObj() { 4953 const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); 4954 return signedAttrs; 4955 } 4956 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4957 get messageDigestAttributeObj() { 4958 const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() && 4959 sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY); 4960 return messageDigest; 4961 } 4962 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4963 get signerSidObj() { 4964 return this.signerInfoObj.subs[1]; 4965 } 4966 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4967 get signerDigestAlgorithmObj() { 4968 // Signature is the 2nd element of the signerInfoObj object 4969 return this.signerInfoObj.subs[2]; 4970 } 4971 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4972 get signatureAlgorithmObj() { 4973 // Signature is the 4th element of the signerInfoObj object 4974 return this.signerInfoObj.subs[4]; 4975 } 4976 // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 4977 get signatureValueObj() { 4978 // Signature is the 6th element of the signerInfoObj object 4979 return this.signerInfoObj.subs[5]; 4980 } 4981 } 4982 exports.RFC3161Timestamp = RFC3161Timestamp; 4983 4984 4985 /***/ }), 4986 4987 /***/ 6368: 4988 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 4989 4990 "use strict"; 4991 4992 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 4993 if (k2 === undefined) k2 = k; 4994 var desc = Object.getOwnPropertyDescriptor(m, k); 4995 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 4996 desc = { enumerable: true, get: function() { return m[k]; } }; 4997 } 4998 Object.defineProperty(o, k2, desc); 4999 }) : (function(o, m, k, k2) { 5000 if (k2 === undefined) k2 = k; 5001 o[k2] = m[k]; 5002 })); 5003 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 5004 Object.defineProperty(o, "default", { enumerable: true, value: v }); 5005 }) : function(o, v) { 5006 o["default"] = v; 5007 }); 5008 var __importStar = (this && this.__importStar) || function (mod) { 5009 if (mod && mod.__esModule) return mod; 5010 var result = {}; 5011 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 5012 __setModuleDefault(result, mod); 5013 return result; 5014 }; 5015 Object.defineProperty(exports, "__esModule", ({ value: true })); 5016 exports.TSTInfo = void 0; 5017 const crypto = __importStar(__nccwpck_require__(3914)); 5018 const oid_1 = __nccwpck_require__(5960); 5019 const error_1 = __nccwpck_require__(4526); 5020 class TSTInfo { 5021 constructor(asn1) { 5022 this.root = asn1; 5023 } 5024 get version() { 5025 return this.root.subs[0].toInteger(); 5026 } 5027 get genTime() { 5028 return this.root.subs[4].toDate(); 5029 } 5030 get messageImprintHashAlgorithm() { 5031 const oid = this.messageImprintObj.subs[0].subs[0].toOID(); 5032 return oid_1.SHA2_HASH_ALGOS[oid]; 5033 } 5034 get messageImprintHashedMessage() { 5035 return this.messageImprintObj.subs[1].value; 5036 } 5037 get raw() { 5038 return this.root.toDER(); 5039 } 5040 verify(data) { 5041 const digest = crypto.digest(this.messageImprintHashAlgorithm, data); 5042 if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) { 5043 throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact'); 5044 } 5045 } 5046 // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 5047 get messageImprintObj() { 5048 return this.root.subs[2]; 5049 } 5050 } 5051 exports.TSTInfo = TSTInfo; 5052 5053 5054 /***/ }), 5055 5056 /***/ 2283: 5057 /***/ ((__unused_webpack_module, exports) => { 5058 5059 "use strict"; 5060 5061 Object.defineProperty(exports, "__esModule", ({ value: true })); 5062 exports.ByteStream = void 0; 5063 /* 5064 Copyright 2023 The Sigstore Authors. 5065 5066 Licensed under the Apache License, Version 2.0 (the "License"); 5067 you may not use this file except in compliance with the License. 5068 You may obtain a copy of the License at 5069 5070 http://www.apache.org/licenses/LICENSE-2.0 5071 5072 Unless required by applicable law or agreed to in writing, software 5073 distributed under the License is distributed on an "AS IS" BASIS, 5074 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5075 See the License for the specific language governing permissions and 5076 limitations under the License. 5077 */ 5078 class StreamError extends Error { 5079 } 5080 class ByteStream { 5081 constructor(buffer) { 5082 this.start = 0; 5083 if (buffer) { 5084 this.buf = buffer; 5085 this.view = Buffer.from(buffer); 5086 } 5087 else { 5088 this.buf = new ArrayBuffer(0); 5089 this.view = Buffer.from(this.buf); 5090 } 5091 } 5092 get buffer() { 5093 return this.view.subarray(0, this.start); 5094 } 5095 get length() { 5096 return this.view.byteLength; 5097 } 5098 get position() { 5099 return this.start; 5100 } 5101 seek(position) { 5102 this.start = position; 5103 } 5104 // Returns a Buffer containing the specified number of bytes starting at the 5105 // given start position. 5106 slice(start, len) { 5107 const end = start + len; 5108 if (end > this.length) { 5109 throw new StreamError('request past end of buffer'); 5110 } 5111 return this.view.subarray(start, end); 5112 } 5113 appendChar(char) { 5114 this.ensureCapacity(1); 5115 this.view[this.start] = char; 5116 this.start += 1; 5117 } 5118 appendUint16(num) { 5119 this.ensureCapacity(2); 5120 const value = new Uint16Array([num]); 5121 const view = new Uint8Array(value.buffer); 5122 this.view[this.start] = view[1]; 5123 this.view[this.start + 1] = view[0]; 5124 this.start += 2; 5125 } 5126 appendUint24(num) { 5127 this.ensureCapacity(3); 5128 const value = new Uint32Array([num]); 5129 const view = new Uint8Array(value.buffer); 5130 this.view[this.start] = view[2]; 5131 this.view[this.start + 1] = view[1]; 5132 this.view[this.start + 2] = view[0]; 5133 this.start += 3; 5134 } 5135 appendView(view) { 5136 this.ensureCapacity(view.length); 5137 this.view.set(view, this.start); 5138 this.start += view.length; 5139 } 5140 getBlock(size) { 5141 if (size <= 0) { 5142 return Buffer.alloc(0); 5143 } 5144 if (this.start + size > this.view.length) { 5145 throw new Error('request past end of buffer'); 5146 } 5147 const result = this.view.subarray(this.start, this.start + size); 5148 this.start += size; 5149 return result; 5150 } 5151 getUint8() { 5152 return this.getBlock(1)[0]; 5153 } 5154 getUint16() { 5155 const block = this.getBlock(2); 5156 return (block[0] << 8) | block[1]; 5157 } 5158 ensureCapacity(size) { 5159 if (this.start + size > this.view.byteLength) { 5160 const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0); 5161 this.realloc(this.view.byteLength + blockSize); 5162 } 5163 } 5164 realloc(size) { 5165 const newArray = new ArrayBuffer(size); 5166 const newView = Buffer.from(newArray); 5167 // Copy the old buffer into the new one 5168 newView.set(this.view); 5169 this.buf = newArray; 5170 this.view = newView; 5171 } 5172 } 5173 exports.ByteStream = ByteStream; 5174 ByteStream.BLOCK_SIZE = 1024; 5175 5176 5177 /***/ }), 5178 5179 /***/ 6381: 5180 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 5181 5182 "use strict"; 5183 5184 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 5185 if (k2 === undefined) k2 = k; 5186 var desc = Object.getOwnPropertyDescriptor(m, k); 5187 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 5188 desc = { enumerable: true, get: function() { return m[k]; } }; 5189 } 5190 Object.defineProperty(o, k2, desc); 5191 }) : (function(o, m, k, k2) { 5192 if (k2 === undefined) k2 = k; 5193 o[k2] = m[k]; 5194 })); 5195 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 5196 Object.defineProperty(o, "default", { enumerable: true, value: v }); 5197 }) : function(o, v) { 5198 o["default"] = v; 5199 }); 5200 var __importStar = (this && this.__importStar) || function (mod) { 5201 if (mod && mod.__esModule) return mod; 5202 var result = {}; 5203 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 5204 __setModuleDefault(result, mod); 5205 return result; 5206 }; 5207 Object.defineProperty(exports, "__esModule", ({ value: true })); 5208 exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; 5209 /* 5210 Copyright 2023 The Sigstore Authors. 5211 5212 Licensed under the Apache License, Version 2.0 (the "License"); 5213 you may not use this file except in compliance with the License. 5214 You may obtain a copy of the License at 5215 5216 http://www.apache.org/licenses/LICENSE-2.0 5217 5218 Unless required by applicable law or agreed to in writing, software 5219 distributed under the License is distributed on an "AS IS" BASIS, 5220 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5221 See the License for the specific language governing permissions and 5222 limitations under the License. 5223 */ 5224 const asn1_1 = __nccwpck_require__(4095); 5225 const crypto = __importStar(__nccwpck_require__(3914)); 5226 const oid_1 = __nccwpck_require__(5960); 5227 const pem = __importStar(__nccwpck_require__(5225)); 5228 const ext_1 = __nccwpck_require__(1292); 5229 const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14'; 5230 const EXTENSION_OID_KEY_USAGE = '2.5.29.15'; 5231 const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17'; 5232 const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19'; 5233 const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35'; 5234 exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2'; 5235 class X509Certificate { 5236 constructor(asn1) { 5237 this.root = asn1; 5238 } 5239 static parse(cert) { 5240 const der = typeof cert === 'string' ? pem.toDER(cert) : cert; 5241 const asn1 = asn1_1.ASN1Obj.parseBuffer(der); 5242 return new X509Certificate(asn1); 5243 } 5244 get tbsCertificate() { 5245 return this.tbsCertificateObj; 5246 } 5247 get version() { 5248 // version number is the first element of the version context specific tag 5249 const ver = this.versionObj.subs[0].toInteger(); 5250 return `v${(ver + BigInt(1)).toString()}`; 5251 } 5252 get serialNumber() { 5253 return this.serialNumberObj.value; 5254 } 5255 get notBefore() { 5256 // notBefore is the first element of the validity sequence 5257 return this.validityObj.subs[0].toDate(); 5258 } 5259 get notAfter() { 5260 // notAfter is the second element of the validity sequence 5261 return this.validityObj.subs[1].toDate(); 5262 } 5263 get issuer() { 5264 return this.issuerObj.value; 5265 } 5266 get subject() { 5267 return this.subjectObj.value; 5268 } 5269 get publicKey() { 5270 return this.subjectPublicKeyInfoObj.toDER(); 5271 } 5272 get signatureAlgorithm() { 5273 const oid = this.signatureAlgorithmObj.subs[0].toOID(); 5274 return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; 5275 } 5276 get signatureValue() { 5277 // Signature value is a bit string, so we need to skip the first byte 5278 return this.signatureValueObj.value.subarray(1); 5279 } 5280 get subjectAltName() { 5281 const ext = this.extSubjectAltName; 5282 return ext?.uri || ext?.rfc822Name; 5283 } 5284 get extensions() { 5285 // The extension list is the first (and only) element of the extensions 5286 // context specific tag 5287 const extSeq = this.extensionsObj?.subs[0]; 5288 return extSeq?.subs || /* istanbul ignore next */ []; 5289 } 5290 get extKeyUsage() { 5291 const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); 5292 return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined; 5293 } 5294 get extBasicConstraints() { 5295 const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS); 5296 return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined; 5297 } 5298 get extSubjectAltName() { 5299 const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME); 5300 return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined; 5301 } 5302 get extAuthorityKeyID() { 5303 const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID); 5304 return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined; 5305 } 5306 get extSubjectKeyID() { 5307 const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID); 5308 return ext 5309 ? new ext_1.X509SubjectKeyIDExtension(ext) 5310 : /* istanbul ignore next */ undefined; 5311 } 5312 get extSCT() { 5313 const ext = this.findExtension(exports.EXTENSION_OID_SCT); 5314 return ext ? new ext_1.X509SCTExtension(ext) : undefined; 5315 } 5316 get isCA() { 5317 const ca = this.extBasicConstraints?.isCA || false; 5318 // If the KeyUsage extension is present, keyCertSign must be set 5319 if (this.extKeyUsage) { 5320 ca && this.extKeyUsage.keyCertSign; 5321 } 5322 return ca; 5323 } 5324 extension(oid) { 5325 const ext = this.findExtension(oid); 5326 return ext ? new ext_1.X509Extension(ext) : undefined; 5327 } 5328 verify(issuerCertificate) { 5329 // Use the issuer's public key if provided, otherwise use the subject's 5330 const publicKey = issuerCertificate?.publicKey || this.publicKey; 5331 const key = crypto.createPublicKey(publicKey); 5332 return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm); 5333 } 5334 validForDate(date) { 5335 return this.notBefore <= date && date <= this.notAfter; 5336 } 5337 equals(other) { 5338 return this.root.toDER().equals(other.root.toDER()); 5339 } 5340 // Creates a copy of the certificate with a new buffer 5341 clone() { 5342 const der = this.root.toDER(); 5343 const clone = Buffer.alloc(der.length); 5344 der.copy(clone); 5345 return X509Certificate.parse(clone); 5346 } 5347 findExtension(oid) { 5348 // Find the extension with the given OID. The OID will always be the first 5349 // element of the extension sequence 5350 return this.extensions.find((ext) => ext.subs[0].toOID() === oid); 5351 } 5352 ///////////////////////////////////////////////////////////////////////////// 5353 // The following properties use the documented x509 structure to locate the 5354 // desired ASN.1 object 5355 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 5356 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1 5357 get tbsCertificateObj() { 5358 // tbsCertificate is the first element of the certificate sequence 5359 return this.root.subs[0]; 5360 } 5361 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 5362 get signatureAlgorithmObj() { 5363 // signatureAlgorithm is the second element of the certificate sequence 5364 return this.root.subs[1]; 5365 } 5366 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3 5367 get signatureValueObj() { 5368 // signatureValue is the third element of the certificate sequence 5369 return this.root.subs[2]; 5370 } 5371 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1 5372 get versionObj() { 5373 // version is the first element of the tbsCertificate sequence 5374 return this.tbsCertificateObj.subs[0]; 5375 } 5376 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2 5377 get serialNumberObj() { 5378 // serialNumber is the second element of the tbsCertificate sequence 5379 return this.tbsCertificateObj.subs[1]; 5380 } 5381 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4 5382 get issuerObj() { 5383 // issuer is the fourth element of the tbsCertificate sequence 5384 return this.tbsCertificateObj.subs[3]; 5385 } 5386 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5 5387 get validityObj() { 5388 // version is the fifth element of the tbsCertificate sequence 5389 return this.tbsCertificateObj.subs[4]; 5390 } 5391 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6 5392 get subjectObj() { 5393 // subject is the sixth element of the tbsCertificate sequence 5394 return this.tbsCertificateObj.subs[5]; 5395 } 5396 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7 5397 get subjectPublicKeyInfoObj() { 5398 // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence 5399 return this.tbsCertificateObj.subs[6]; 5400 } 5401 // Extensions can't be located by index because their position varies. Instead, 5402 // we need to find the extensions context specific tag 5403 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9 5404 get extensionsObj() { 5405 return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03)); 5406 } 5407 } 5408 exports.X509Certificate = X509Certificate; 5409 5410 5411 /***/ }), 5412 5413 /***/ 1292: 5414 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 5415 5416 "use strict"; 5417 5418 Object.defineProperty(exports, "__esModule", ({ value: true })); 5419 exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0; 5420 const stream_1 = __nccwpck_require__(2283); 5421 const sct_1 = __nccwpck_require__(454); 5422 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 5423 class X509Extension { 5424 constructor(asn1) { 5425 this.root = asn1; 5426 } 5427 get oid() { 5428 return this.root.subs[0].toOID(); 5429 } 5430 get critical() { 5431 // The critical field is optional and will be the second element of the 5432 // extension sequence if present. Default to false if not present. 5433 return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false; 5434 } 5435 get value() { 5436 return this.extnValueObj.value; 5437 } 5438 get valueObj() { 5439 return this.extnValueObj; 5440 } 5441 get extnValueObj() { 5442 // The extnValue field will be the last element of the extension sequence 5443 return this.root.subs[this.root.subs.length - 1]; 5444 } 5445 } 5446 exports.X509Extension = X509Extension; 5447 // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9 5448 class X509BasicConstraintsExtension extends X509Extension { 5449 get isCA() { 5450 return this.sequence.subs[0]?.toBoolean() ?? false; 5451 } 5452 get pathLenConstraint() { 5453 return this.sequence.subs.length > 1 5454 ? this.sequence.subs[1].toInteger() 5455 : undefined; 5456 } 5457 // The extnValue field contains a single sequence wrapping the isCA and 5458 // pathLenConstraint. 5459 get sequence() { 5460 return this.extnValueObj.subs[0]; 5461 } 5462 } 5463 exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension; 5464 // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3 5465 class X509KeyUsageExtension extends X509Extension { 5466 get digitalSignature() { 5467 return this.bitString[0] === 1; 5468 } 5469 get keyCertSign() { 5470 return this.bitString[5] === 1; 5471 } 5472 get crlSign() { 5473 return this.bitString[6] === 1; 5474 } 5475 // The extnValue field contains a single bit string which is a bit mask 5476 // indicating which key usages are enabled. 5477 get bitString() { 5478 return this.extnValueObj.subs[0].toBitString(); 5479 } 5480 } 5481 exports.X509KeyUsageExtension = X509KeyUsageExtension; 5482 // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6 5483 class X509SubjectAlternativeNameExtension extends X509Extension { 5484 get rfc822Name() { 5485 return this.findGeneralName(0x01)?.value.toString('ascii'); 5486 } 5487 get uri() { 5488 return this.findGeneralName(0x06)?.value.toString('ascii'); 5489 } 5490 // Retrieve the value of an otherName with the given OID. 5491 otherName(oid) { 5492 const otherName = this.findGeneralName(0x00); 5493 if (otherName === undefined) { 5494 return undefined; 5495 } 5496 // The otherName is a sequence containing an OID and a value. 5497 // Need to check that the OID matches the one we're looking for. 5498 const otherNameOID = otherName.subs[0].toOID(); 5499 if (otherNameOID !== oid) { 5500 return undefined; 5501 } 5502 // The otherNameValue is a sequence containing the actual value. 5503 const otherNameValue = otherName.subs[1]; 5504 return otherNameValue.subs[0].value.toString('ascii'); 5505 } 5506 findGeneralName(tag) { 5507 return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag)); 5508 } 5509 // The extnValue field contains a sequence of GeneralNames. 5510 get generalNames() { 5511 return this.extnValueObj.subs[0].subs; 5512 } 5513 } 5514 exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension; 5515 // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1 5516 class X509AuthorityKeyIDExtension extends X509Extension { 5517 get keyIdentifier() { 5518 return this.findSequenceMember(0x00)?.value; 5519 } 5520 findSequenceMember(tag) { 5521 return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag)); 5522 } 5523 // The extnValue field contains a single sequence wrapping the keyIdentifier 5524 get sequence() { 5525 return this.extnValueObj.subs[0]; 5526 } 5527 } 5528 exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension; 5529 // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2 5530 class X509SubjectKeyIDExtension extends X509Extension { 5531 get keyIdentifier() { 5532 return this.extnValueObj.subs[0].value; 5533 } 5534 } 5535 exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension; 5536 // https://www.rfc-editor.org/rfc/rfc6962#section-3.3 5537 class X509SCTExtension extends X509Extension { 5538 constructor(asn1) { 5539 super(asn1); 5540 } 5541 get signedCertificateTimestamps() { 5542 const buf = this.extnValueObj.subs[0].value; 5543 const stream = new stream_1.ByteStream(buf); 5544 // The overall list length is encoded in the first two bytes -- note this 5545 // is the length of the list in bytes, NOT the number of SCTs in the list 5546 const end = stream.getUint16() + 2; 5547 const sctList = []; 5548 while (stream.position < end) { 5549 // Read the length of the next SCT 5550 const sctLength = stream.getUint16(); 5551 // Slice out the bytes for the next SCT and parse it 5552 const sct = stream.getBlock(sctLength); 5553 sctList.push(sct_1.SignedCertificateTimestamp.parse(sct)); 5554 } 5555 if (stream.position !== end) { 5556 throw new Error('SCT list length does not match actual length'); 5557 } 5558 return sctList; 5559 } 5560 } 5561 exports.X509SCTExtension = X509SCTExtension; 5562 5563 5564 /***/ }), 5565 5566 /***/ 5500: 5567 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 5568 5569 "use strict"; 5570 5571 /* 5572 Copyright 2023 The Sigstore Authors. 5573 5574 Licensed under the Apache License, Version 2.0 (the "License"); 5575 you may not use this file except in compliance with the License. 5576 You may obtain a copy of the License at 5577 5578 http://www.apache.org/licenses/LICENSE-2.0 5579 5580 Unless required by applicable law or agreed to in writing, software 5581 distributed under the License is distributed on an "AS IS" BASIS, 5582 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5583 See the License for the specific language governing permissions and 5584 limitations under the License. 5585 */ 5586 Object.defineProperty(exports, "__esModule", ({ value: true })); 5587 exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; 5588 var cert_1 = __nccwpck_require__(6381); 5589 Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } })); 5590 Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return cert_1.X509Certificate; } })); 5591 var ext_1 = __nccwpck_require__(1292); 5592 Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return ext_1.X509SCTExtension; } })); 5593 5594 5595 /***/ }), 5596 5597 /***/ 454: 5598 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 5599 5600 "use strict"; 5601 5602 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 5603 if (k2 === undefined) k2 = k; 5604 var desc = Object.getOwnPropertyDescriptor(m, k); 5605 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 5606 desc = { enumerable: true, get: function() { return m[k]; } }; 5607 } 5608 Object.defineProperty(o, k2, desc); 5609 }) : (function(o, m, k, k2) { 5610 if (k2 === undefined) k2 = k; 5611 o[k2] = m[k]; 5612 })); 5613 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 5614 Object.defineProperty(o, "default", { enumerable: true, value: v }); 5615 }) : function(o, v) { 5616 o["default"] = v; 5617 }); 5618 var __importStar = (this && this.__importStar) || function (mod) { 5619 if (mod && mod.__esModule) return mod; 5620 var result = {}; 5621 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 5622 __setModuleDefault(result, mod); 5623 return result; 5624 }; 5625 Object.defineProperty(exports, "__esModule", ({ value: true })); 5626 exports.SignedCertificateTimestamp = void 0; 5627 /* 5628 Copyright 2023 The Sigstore Authors. 5629 5630 Licensed under the Apache License, Version 2.0 (the "License"); 5631 you may not use this file except in compliance with the License. 5632 You may obtain a copy of the License at 5633 5634 http://www.apache.org/licenses/LICENSE-2.0 5635 5636 Unless required by applicable law or agreed to in writing, software 5637 distributed under the License is distributed on an "AS IS" BASIS, 5638 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5639 See the License for the specific language governing permissions and 5640 limitations under the License. 5641 */ 5642 const crypto = __importStar(__nccwpck_require__(3914)); 5643 const stream_1 = __nccwpck_require__(2283); 5644 class SignedCertificateTimestamp { 5645 constructor(options) { 5646 this.version = options.version; 5647 this.logID = options.logID; 5648 this.timestamp = options.timestamp; 5649 this.extensions = options.extensions; 5650 this.hashAlgorithm = options.hashAlgorithm; 5651 this.signatureAlgorithm = options.signatureAlgorithm; 5652 this.signature = options.signature; 5653 } 5654 get datetime() { 5655 return new Date(Number(this.timestamp.readBigInt64BE())); 5656 } 5657 // Returns the hash algorithm used to generate the SCT's signature. 5658 // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 5659 get algorithm() { 5660 switch (this.hashAlgorithm) { 5661 /* istanbul ignore next */ 5662 case 0: 5663 return 'none'; 5664 /* istanbul ignore next */ 5665 case 1: 5666 return 'md5'; 5667 /* istanbul ignore next */ 5668 case 2: 5669 return 'sha1'; 5670 /* istanbul ignore next */ 5671 case 3: 5672 return 'sha224'; 5673 case 4: 5674 return 'sha256'; 5675 /* istanbul ignore next */ 5676 case 5: 5677 return 'sha384'; 5678 /* istanbul ignore next */ 5679 case 6: 5680 return 'sha512'; 5681 /* istanbul ignore next */ 5682 default: 5683 return 'unknown'; 5684 } 5685 } 5686 verify(preCert, key) { 5687 // Assemble the digitally-signed struct (the data over which the signature 5688 // was generated). 5689 // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 5690 const stream = new stream_1.ByteStream(); 5691 stream.appendChar(this.version); 5692 stream.appendChar(0x00); // SignatureType = certificate_timestamp(0) 5693 stream.appendView(this.timestamp); 5694 stream.appendUint16(0x01); // LogEntryType = precert_entry(1) 5695 stream.appendView(preCert); 5696 stream.appendUint16(this.extensions.byteLength); 5697 /* istanbul ignore next - extensions are very uncommon */ 5698 if (this.extensions.byteLength > 0) { 5699 stream.appendView(this.extensions); 5700 } 5701 return crypto.verify(stream.buffer, key, this.signature, this.algorithm); 5702 } 5703 // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using 5704 // TLS encoding which means the fields and lengths of most fields are 5705 // specified as part of the SCT and TLS specs. 5706 // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 5707 // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 5708 static parse(buf) { 5709 const stream = new stream_1.ByteStream(buf); 5710 // Version - enum { v1(0), (255) } 5711 const version = stream.getUint8(); 5712 // Log ID - struct { opaque key_id[32]; } 5713 const logID = stream.getBlock(32); 5714 // Timestamp - uint64 5715 const timestamp = stream.getBlock(8); 5716 // Extensions - opaque extensions<0..2^16-1>; 5717 const extenstionLength = stream.getUint16(); 5718 const extensions = stream.getBlock(extenstionLength); 5719 // Hash algo - enum { sha256(4), . . . (255) } 5720 const hashAlgorithm = stream.getUint8(); 5721 // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } 5722 const signatureAlgorithm = stream.getUint8(); 5723 // Signature - opaque signature<0..2^16-1>; 5724 const sigLength = stream.getUint16(); 5725 const signature = stream.getBlock(sigLength); 5726 // Check that we read the entire buffer 5727 if (stream.position !== buf.length) { 5728 throw new Error('SCT buffer length mismatch'); 5729 } 5730 return new SignedCertificateTimestamp({ 5731 version, 5732 logID, 5733 timestamp, 5734 extensions, 5735 hashAlgorithm, 5736 signatureAlgorithm, 5737 signature, 5738 }); 5739 } 5740 } 5741 exports.SignedCertificateTimestamp = SignedCertificateTimestamp; 5742 5743 5744 /***/ }), 5745 5746 /***/ 714: 5747 /***/ ((__unused_webpack_module, exports) => { 5748 5749 "use strict"; 5750 5751 /* eslint-disable */ 5752 Object.defineProperty(exports, "__esModule", ({ value: true })); 5753 exports.Signature = exports.Envelope = void 0; 5754 function createBaseEnvelope() { 5755 return { payload: Buffer.alloc(0), payloadType: "", signatures: [] }; 5756 } 5757 exports.Envelope = { 5758 fromJSON(object) { 5759 return { 5760 payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0), 5761 payloadType: isSet(object.payloadType) ? String(object.payloadType) : "", 5762 signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [], 5763 }; 5764 }, 5765 toJSON(message) { 5766 const obj = {}; 5767 message.payload !== undefined && 5768 (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0))); 5769 message.payloadType !== undefined && (obj.payloadType = message.payloadType); 5770 if (message.signatures) { 5771 obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined); 5772 } 5773 else { 5774 obj.signatures = []; 5775 } 5776 return obj; 5777 }, 5778 }; 5779 function createBaseSignature() { 5780 return { sig: Buffer.alloc(0), keyid: "" }; 5781 } 5782 exports.Signature = { 5783 fromJSON(object) { 5784 return { 5785 sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0), 5786 keyid: isSet(object.keyid) ? String(object.keyid) : "", 5787 }; 5788 }, 5789 toJSON(message) { 5790 const obj = {}; 5791 message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0))); 5792 message.keyid !== undefined && (obj.keyid = message.keyid); 5793 return obj; 5794 }, 5795 }; 5796 var tsProtoGlobalThis = (() => { 5797 if (typeof globalThis !== "undefined") { 5798 return globalThis; 5799 } 5800 if (typeof self !== "undefined") { 5801 return self; 5802 } 5803 if (typeof window !== "undefined") { 5804 return window; 5805 } 5806 if (typeof global !== "undefined") { 5807 return global; 5808 } 5809 throw "Unable to locate global object"; 5810 })(); 5811 function bytesFromBase64(b64) { 5812 if (tsProtoGlobalThis.Buffer) { 5813 return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); 5814 } 5815 else { 5816 const bin = tsProtoGlobalThis.atob(b64); 5817 const arr = new Uint8Array(bin.length); 5818 for (let i = 0; i < bin.length; ++i) { 5819 arr[i] = bin.charCodeAt(i); 5820 } 5821 return arr; 5822 } 5823 } 5824 function base64FromBytes(arr) { 5825 if (tsProtoGlobalThis.Buffer) { 5826 return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); 5827 } 5828 else { 5829 const bin = []; 5830 arr.forEach((byte) => { 5831 bin.push(String.fromCharCode(byte)); 5832 }); 5833 return tsProtoGlobalThis.btoa(bin.join("")); 5834 } 5835 } 5836 function isSet(value) { 5837 return value !== null && value !== undefined; 5838 } 5839 5840 5841 /***/ }), 5842 5843 /***/ 3027: 5844 /***/ ((__unused_webpack_module, exports) => { 5845 5846 "use strict"; 5847 5848 /* eslint-disable */ 5849 Object.defineProperty(exports, "__esModule", ({ value: true })); 5850 exports.Timestamp = void 0; 5851 function createBaseTimestamp() { 5852 return { seconds: "0", nanos: 0 }; 5853 } 5854 exports.Timestamp = { 5855 fromJSON(object) { 5856 return { 5857 seconds: isSet(object.seconds) ? String(object.seconds) : "0", 5858 nanos: isSet(object.nanos) ? Number(object.nanos) : 0, 5859 }; 5860 }, 5861 toJSON(message) { 5862 const obj = {}; 5863 message.seconds !== undefined && (obj.seconds = message.seconds); 5864 message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); 5865 return obj; 5866 }, 5867 }; 5868 function isSet(value) { 5869 return value !== null && value !== undefined; 5870 } 5871 5872 5873 /***/ }), 5874 5875 /***/ 8293: 5876 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 5877 5878 "use strict"; 5879 5880 Object.defineProperty(exports, "__esModule", ({ value: true })); 5881 exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0; 5882 /* eslint-disable */ 5883 const envelope_1 = __nccwpck_require__(714); 5884 const sigstore_common_1 = __nccwpck_require__(2193); 5885 const sigstore_rekor_1 = __nccwpck_require__(4951); 5886 function createBaseTimestampVerificationData() { 5887 return { rfc3161Timestamps: [] }; 5888 } 5889 exports.TimestampVerificationData = { 5890 fromJSON(object) { 5891 return { 5892 rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps) 5893 ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e)) 5894 : [], 5895 }; 5896 }, 5897 toJSON(message) { 5898 const obj = {}; 5899 if (message.rfc3161Timestamps) { 5900 obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined); 5901 } 5902 else { 5903 obj.rfc3161Timestamps = []; 5904 } 5905 return obj; 5906 }, 5907 }; 5908 function createBaseVerificationMaterial() { 5909 return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; 5910 } 5911 exports.VerificationMaterial = { 5912 fromJSON(object) { 5913 return { 5914 content: isSet(object.publicKey) 5915 ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) } 5916 : isSet(object.x509CertificateChain) 5917 ? { 5918 $case: "x509CertificateChain", 5919 x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain), 5920 } 5921 : isSet(object.certificate) 5922 ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) } 5923 : undefined, 5924 tlogEntries: Array.isArray(object?.tlogEntries) 5925 ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) 5926 : [], 5927 timestampVerificationData: isSet(object.timestampVerificationData) 5928 ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData) 5929 : undefined, 5930 }; 5931 }, 5932 toJSON(message) { 5933 const obj = {}; 5934 message.content?.$case === "publicKey" && 5935 (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined); 5936 message.content?.$case === "x509CertificateChain" && 5937 (obj.x509CertificateChain = message.content?.x509CertificateChain 5938 ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain) 5939 : undefined); 5940 message.content?.$case === "certificate" && 5941 (obj.certificate = message.content?.certificate 5942 ? sigstore_common_1.X509Certificate.toJSON(message.content?.certificate) 5943 : undefined); 5944 if (message.tlogEntries) { 5945 obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined); 5946 } 5947 else { 5948 obj.tlogEntries = []; 5949 } 5950 message.timestampVerificationData !== undefined && 5951 (obj.timestampVerificationData = message.timestampVerificationData 5952 ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData) 5953 : undefined); 5954 return obj; 5955 }, 5956 }; 5957 function createBaseBundle() { 5958 return { mediaType: "", verificationMaterial: undefined, content: undefined }; 5959 } 5960 exports.Bundle = { 5961 fromJSON(object) { 5962 return { 5963 mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", 5964 verificationMaterial: isSet(object.verificationMaterial) 5965 ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) 5966 : undefined, 5967 content: isSet(object.messageSignature) 5968 ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) } 5969 : isSet(object.dsseEnvelope) 5970 ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) } 5971 : undefined, 5972 }; 5973 }, 5974 toJSON(message) { 5975 const obj = {}; 5976 message.mediaType !== undefined && (obj.mediaType = message.mediaType); 5977 message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial 5978 ? exports.VerificationMaterial.toJSON(message.verificationMaterial) 5979 : undefined); 5980 message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature 5981 ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature) 5982 : undefined); 5983 message.content?.$case === "dsseEnvelope" && 5984 (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined); 5985 return obj; 5986 }, 5987 }; 5988 function isSet(value) { 5989 return value !== null && value !== undefined; 5990 } 5991 5992 5993 /***/ }), 5994 5995 /***/ 2193: 5996 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 5997 5998 "use strict"; 5999 6000 Object.defineProperty(exports, "__esModule", ({ value: true })); 6001 exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0; 6002 /* eslint-disable */ 6003 const timestamp_1 = __nccwpck_require__(3027); 6004 /** 6005 * Only a subset of the secure hash standard algorithms are supported. 6006 * See <https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf> for more 6007 * details. 6008 * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force 6009 * any proto JSON serialization to emit the used hash algorithm, as default 6010 * option is to *omit* the default value of an enum (which is the first 6011 * value, represented by '0'. 6012 */ 6013 var HashAlgorithm; 6014 (function (HashAlgorithm) { 6015 HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED"; 6016 HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; 6017 HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384"; 6018 HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512"; 6019 HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256"; 6020 HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384"; 6021 })(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); 6022 function hashAlgorithmFromJSON(object) { 6023 switch (object) { 6024 case 0: 6025 case "HASH_ALGORITHM_UNSPECIFIED": 6026 return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED; 6027 case 1: 6028 case "SHA2_256": 6029 return HashAlgorithm.SHA2_256; 6030 case 2: 6031 case "SHA2_384": 6032 return HashAlgorithm.SHA2_384; 6033 case 3: 6034 case "SHA2_512": 6035 return HashAlgorithm.SHA2_512; 6036 case 4: 6037 case "SHA3_256": 6038 return HashAlgorithm.SHA3_256; 6039 case 5: 6040 case "SHA3_384": 6041 return HashAlgorithm.SHA3_384; 6042 default: 6043 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); 6044 } 6045 } 6046 exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; 6047 function hashAlgorithmToJSON(object) { 6048 switch (object) { 6049 case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: 6050 return "HASH_ALGORITHM_UNSPECIFIED"; 6051 case HashAlgorithm.SHA2_256: 6052 return "SHA2_256"; 6053 case HashAlgorithm.SHA2_384: 6054 return "SHA2_384"; 6055 case HashAlgorithm.SHA2_512: 6056 return "SHA2_512"; 6057 case HashAlgorithm.SHA3_256: 6058 return "SHA3_256"; 6059 case HashAlgorithm.SHA3_384: 6060 return "SHA3_384"; 6061 default: 6062 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); 6063 } 6064 } 6065 exports.hashAlgorithmToJSON = hashAlgorithmToJSON; 6066 /** 6067 * Details of a specific public key, capturing the the key encoding method, 6068 * and signature algorithm. 6069 * 6070 * PublicKeyDetails captures the public key/hash algorithm combinations 6071 * recommended in the Sigstore ecosystem. 6072 * 6073 * This is modelled as a linear set as we want to provide a small number of 6074 * opinionated options instead of allowing every possible permutation. 6075 * 6076 * Any changes to this enum MUST be reflected in the algorithm registry. 6077 * See: docs/algorithm-registry.md 6078 * 6079 * To avoid the possibility of contradicting formats such as PKCS1 with 6080 * ED25519 the valid permutations are listed as a linear set instead of a 6081 * cartesian set (i.e one combined variable instead of two, one for encoding 6082 * and one for the signature algorithm). 6083 */ 6084 var PublicKeyDetails; 6085 (function (PublicKeyDetails) { 6086 PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED"; 6087 /** 6088 * PKCS1_RSA_PKCS1V5 - RSA 6089 * 6090 * @deprecated 6091 */ 6092 PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5"; 6093 /** 6094 * PKCS1_RSA_PSS - See RFC8017 6095 * 6096 * @deprecated 6097 */ 6098 PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS"; 6099 /** @deprecated */ 6100 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5"; 6101 /** @deprecated */ 6102 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS"; 6103 /** PKIX_RSA_PKCS1V15_2048_SHA256 - RSA public key in PKIX format, PKCS#1v1.5 signature */ 6104 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_2048_SHA256"] = 9] = "PKIX_RSA_PKCS1V15_2048_SHA256"; 6105 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_3072_SHA256"] = 10] = "PKIX_RSA_PKCS1V15_3072_SHA256"; 6106 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_4096_SHA256"] = 11] = "PKIX_RSA_PKCS1V15_4096_SHA256"; 6107 /** PKIX_RSA_PSS_2048_SHA256 - RSA public key in PKIX format, RSASSA-PSS signature */ 6108 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_2048_SHA256"] = 16] = "PKIX_RSA_PSS_2048_SHA256"; 6109 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_3072_SHA256"] = 17] = "PKIX_RSA_PSS_3072_SHA256"; 6110 PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_4096_SHA256"] = 18] = "PKIX_RSA_PSS_4096_SHA256"; 6111 /** 6112 * PKIX_ECDSA_P256_HMAC_SHA_256 - ECDSA 6113 * 6114 * @deprecated 6115 */ 6116 PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256"; 6117 /** PKIX_ECDSA_P256_SHA_256 - See NIST FIPS 186-4 */ 6118 PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256"; 6119 PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_384"] = 12] = "PKIX_ECDSA_P384_SHA_384"; 6120 PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_512"] = 13] = "PKIX_ECDSA_P521_SHA_512"; 6121 /** PKIX_ED25519 - Ed 25519 */ 6122 PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; 6123 PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH"; 6124 /** 6125 * LMS_SHA256 - LMS and LM-OTS 6126 * 6127 * These keys and signatures may be used by private Sigstore 6128 * deployments, but are not currently supported by the public 6129 * good instance. 6130 * 6131 * USER WARNING: LMS and LM-OTS are both stateful signature schemes. 6132 * Using them correctly requires discretion and careful consideration 6133 * to ensure that individual secret keys are not used more than once. 6134 * In addition, LM-OTS is a single-use scheme, meaning that it 6135 * MUST NOT be used for more than one signature per LM-OTS key. 6136 * If you cannot maintain these invariants, you MUST NOT use these 6137 * schemes. 6138 */ 6139 PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256"; 6140 PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256"; 6141 })(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {})); 6142 function publicKeyDetailsFromJSON(object) { 6143 switch (object) { 6144 case 0: 6145 case "PUBLIC_KEY_DETAILS_UNSPECIFIED": 6146 return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED; 6147 case 1: 6148 case "PKCS1_RSA_PKCS1V5": 6149 return PublicKeyDetails.PKCS1_RSA_PKCS1V5; 6150 case 2: 6151 case "PKCS1_RSA_PSS": 6152 return PublicKeyDetails.PKCS1_RSA_PSS; 6153 case 3: 6154 case "PKIX_RSA_PKCS1V5": 6155 return PublicKeyDetails.PKIX_RSA_PKCS1V5; 6156 case 4: 6157 case "PKIX_RSA_PSS": 6158 return PublicKeyDetails.PKIX_RSA_PSS; 6159 case 9: 6160 case "PKIX_RSA_PKCS1V15_2048_SHA256": 6161 return PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256; 6162 case 10: 6163 case "PKIX_RSA_PKCS1V15_3072_SHA256": 6164 return PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256; 6165 case 11: 6166 case "PKIX_RSA_PKCS1V15_4096_SHA256": 6167 return PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256; 6168 case 16: 6169 case "PKIX_RSA_PSS_2048_SHA256": 6170 return PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256; 6171 case 17: 6172 case "PKIX_RSA_PSS_3072_SHA256": 6173 return PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256; 6174 case 18: 6175 case "PKIX_RSA_PSS_4096_SHA256": 6176 return PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256; 6177 case 6: 6178 case "PKIX_ECDSA_P256_HMAC_SHA_256": 6179 return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256; 6180 case 5: 6181 case "PKIX_ECDSA_P256_SHA_256": 6182 return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256; 6183 case 12: 6184 case "PKIX_ECDSA_P384_SHA_384": 6185 return PublicKeyDetails.PKIX_ECDSA_P384_SHA_384; 6186 case 13: 6187 case "PKIX_ECDSA_P521_SHA_512": 6188 return PublicKeyDetails.PKIX_ECDSA_P521_SHA_512; 6189 case 7: 6190 case "PKIX_ED25519": 6191 return PublicKeyDetails.PKIX_ED25519; 6192 case 8: 6193 case "PKIX_ED25519_PH": 6194 return PublicKeyDetails.PKIX_ED25519_PH; 6195 case 14: 6196 case "LMS_SHA256": 6197 return PublicKeyDetails.LMS_SHA256; 6198 case 15: 6199 case "LMOTS_SHA256": 6200 return PublicKeyDetails.LMOTS_SHA256; 6201 default: 6202 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); 6203 } 6204 } 6205 exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; 6206 function publicKeyDetailsToJSON(object) { 6207 switch (object) { 6208 case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: 6209 return "PUBLIC_KEY_DETAILS_UNSPECIFIED"; 6210 case PublicKeyDetails.PKCS1_RSA_PKCS1V5: 6211 return "PKCS1_RSA_PKCS1V5"; 6212 case PublicKeyDetails.PKCS1_RSA_PSS: 6213 return "PKCS1_RSA_PSS"; 6214 case PublicKeyDetails.PKIX_RSA_PKCS1V5: 6215 return "PKIX_RSA_PKCS1V5"; 6216 case PublicKeyDetails.PKIX_RSA_PSS: 6217 return "PKIX_RSA_PSS"; 6218 case PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256: 6219 return "PKIX_RSA_PKCS1V15_2048_SHA256"; 6220 case PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256: 6221 return "PKIX_RSA_PKCS1V15_3072_SHA256"; 6222 case PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256: 6223 return "PKIX_RSA_PKCS1V15_4096_SHA256"; 6224 case PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256: 6225 return "PKIX_RSA_PSS_2048_SHA256"; 6226 case PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256: 6227 return "PKIX_RSA_PSS_3072_SHA256"; 6228 case PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256: 6229 return "PKIX_RSA_PSS_4096_SHA256"; 6230 case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256: 6231 return "PKIX_ECDSA_P256_HMAC_SHA_256"; 6232 case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256: 6233 return "PKIX_ECDSA_P256_SHA_256"; 6234 case PublicKeyDetails.PKIX_ECDSA_P384_SHA_384: 6235 return "PKIX_ECDSA_P384_SHA_384"; 6236 case PublicKeyDetails.PKIX_ECDSA_P521_SHA_512: 6237 return "PKIX_ECDSA_P521_SHA_512"; 6238 case PublicKeyDetails.PKIX_ED25519: 6239 return "PKIX_ED25519"; 6240 case PublicKeyDetails.PKIX_ED25519_PH: 6241 return "PKIX_ED25519_PH"; 6242 case PublicKeyDetails.LMS_SHA256: 6243 return "LMS_SHA256"; 6244 case PublicKeyDetails.LMOTS_SHA256: 6245 return "LMOTS_SHA256"; 6246 default: 6247 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); 6248 } 6249 } 6250 exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; 6251 var SubjectAlternativeNameType; 6252 (function (SubjectAlternativeNameType) { 6253 SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; 6254 SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL"; 6255 SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI"; 6256 /** 6257 * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 6258 * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san 6259 * for more details. 6260 */ 6261 SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; 6262 })(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {})); 6263 function subjectAlternativeNameTypeFromJSON(object) { 6264 switch (object) { 6265 case 0: 6266 case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED": 6267 return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED; 6268 case 1: 6269 case "EMAIL": 6270 return SubjectAlternativeNameType.EMAIL; 6271 case 2: 6272 case "URI": 6273 return SubjectAlternativeNameType.URI; 6274 case 3: 6275 case "OTHER_NAME": 6276 return SubjectAlternativeNameType.OTHER_NAME; 6277 default: 6278 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); 6279 } 6280 } 6281 exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; 6282 function subjectAlternativeNameTypeToJSON(object) { 6283 switch (object) { 6284 case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: 6285 return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; 6286 case SubjectAlternativeNameType.EMAIL: 6287 return "EMAIL"; 6288 case SubjectAlternativeNameType.URI: 6289 return "URI"; 6290 case SubjectAlternativeNameType.OTHER_NAME: 6291 return "OTHER_NAME"; 6292 default: 6293 throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); 6294 } 6295 } 6296 exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; 6297 function createBaseHashOutput() { 6298 return { algorithm: 0, digest: Buffer.alloc(0) }; 6299 } 6300 exports.HashOutput = { 6301 fromJSON(object) { 6302 return { 6303 algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0, 6304 digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), 6305 }; 6306 }, 6307 toJSON(message) { 6308 const obj = {}; 6309 message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm)); 6310 message.digest !== undefined && 6311 (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0))); 6312 return obj; 6313 }, 6314 }; 6315 function createBaseMessageSignature() { 6316 return { messageDigest: undefined, signature: Buffer.alloc(0) }; 6317 } 6318 exports.MessageSignature = { 6319 fromJSON(object) { 6320 return { 6321 messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined, 6322 signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0), 6323 }; 6324 }, 6325 toJSON(message) { 6326 const obj = {}; 6327 message.messageDigest !== undefined && 6328 (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined); 6329 message.signature !== undefined && 6330 (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0))); 6331 return obj; 6332 }, 6333 }; 6334 function createBaseLogId() { 6335 return { keyId: Buffer.alloc(0) }; 6336 } 6337 exports.LogId = { 6338 fromJSON(object) { 6339 return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) }; 6340 }, 6341 toJSON(message) { 6342 const obj = {}; 6343 message.keyId !== undefined && 6344 (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0))); 6345 return obj; 6346 }, 6347 }; 6348 function createBaseRFC3161SignedTimestamp() { 6349 return { signedTimestamp: Buffer.alloc(0) }; 6350 } 6351 exports.RFC3161SignedTimestamp = { 6352 fromJSON(object) { 6353 return { 6354 signedTimestamp: isSet(object.signedTimestamp) 6355 ? Buffer.from(bytesFromBase64(object.signedTimestamp)) 6356 : Buffer.alloc(0), 6357 }; 6358 }, 6359 toJSON(message) { 6360 const obj = {}; 6361 message.signedTimestamp !== undefined && 6362 (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); 6363 return obj; 6364 }, 6365 }; 6366 function createBasePublicKey() { 6367 return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; 6368 } 6369 exports.PublicKey = { 6370 fromJSON(object) { 6371 return { 6372 rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined, 6373 keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0, 6374 validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined, 6375 }; 6376 }, 6377 toJSON(message) { 6378 const obj = {}; 6379 message.rawBytes !== undefined && 6380 (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined); 6381 message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails)); 6382 message.validFor !== undefined && 6383 (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined); 6384 return obj; 6385 }, 6386 }; 6387 function createBasePublicKeyIdentifier() { 6388 return { hint: "" }; 6389 } 6390 exports.PublicKeyIdentifier = { 6391 fromJSON(object) { 6392 return { hint: isSet(object.hint) ? String(object.hint) : "" }; 6393 }, 6394 toJSON(message) { 6395 const obj = {}; 6396 message.hint !== undefined && (obj.hint = message.hint); 6397 return obj; 6398 }, 6399 }; 6400 function createBaseObjectIdentifier() { 6401 return { id: [] }; 6402 } 6403 exports.ObjectIdentifier = { 6404 fromJSON(object) { 6405 return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] }; 6406 }, 6407 toJSON(message) { 6408 const obj = {}; 6409 if (message.id) { 6410 obj.id = message.id.map((e) => Math.round(e)); 6411 } 6412 else { 6413 obj.id = []; 6414 } 6415 return obj; 6416 }, 6417 }; 6418 function createBaseObjectIdentifierValuePair() { 6419 return { oid: undefined, value: Buffer.alloc(0) }; 6420 } 6421 exports.ObjectIdentifierValuePair = { 6422 fromJSON(object) { 6423 return { 6424 oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined, 6425 value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), 6426 }; 6427 }, 6428 toJSON(message) { 6429 const obj = {}; 6430 message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined); 6431 message.value !== undefined && 6432 (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); 6433 return obj; 6434 }, 6435 }; 6436 function createBaseDistinguishedName() { 6437 return { organization: "", commonName: "" }; 6438 } 6439 exports.DistinguishedName = { 6440 fromJSON(object) { 6441 return { 6442 organization: isSet(object.organization) ? String(object.organization) : "", 6443 commonName: isSet(object.commonName) ? String(object.commonName) : "", 6444 }; 6445 }, 6446 toJSON(message) { 6447 const obj = {}; 6448 message.organization !== undefined && (obj.organization = message.organization); 6449 message.commonName !== undefined && (obj.commonName = message.commonName); 6450 return obj; 6451 }, 6452 }; 6453 function createBaseX509Certificate() { 6454 return { rawBytes: Buffer.alloc(0) }; 6455 } 6456 exports.X509Certificate = { 6457 fromJSON(object) { 6458 return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; 6459 }, 6460 toJSON(message) { 6461 const obj = {}; 6462 message.rawBytes !== undefined && 6463 (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0))); 6464 return obj; 6465 }, 6466 }; 6467 function createBaseSubjectAlternativeName() { 6468 return { type: 0, identity: undefined }; 6469 } 6470 exports.SubjectAlternativeName = { 6471 fromJSON(object) { 6472 return { 6473 type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0, 6474 identity: isSet(object.regexp) 6475 ? { $case: "regexp", regexp: String(object.regexp) } 6476 : isSet(object.value) 6477 ? { $case: "value", value: String(object.value) } 6478 : undefined, 6479 }; 6480 }, 6481 toJSON(message) { 6482 const obj = {}; 6483 message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type)); 6484 message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp); 6485 message.identity?.$case === "value" && (obj.value = message.identity?.value); 6486 return obj; 6487 }, 6488 }; 6489 function createBaseX509CertificateChain() { 6490 return { certificates: [] }; 6491 } 6492 exports.X509CertificateChain = { 6493 fromJSON(object) { 6494 return { 6495 certificates: Array.isArray(object?.certificates) 6496 ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e)) 6497 : [], 6498 }; 6499 }, 6500 toJSON(message) { 6501 const obj = {}; 6502 if (message.certificates) { 6503 obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined); 6504 } 6505 else { 6506 obj.certificates = []; 6507 } 6508 return obj; 6509 }, 6510 }; 6511 function createBaseTimeRange() { 6512 return { start: undefined, end: undefined }; 6513 } 6514 exports.TimeRange = { 6515 fromJSON(object) { 6516 return { 6517 start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined, 6518 end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined, 6519 }; 6520 }, 6521 toJSON(message) { 6522 const obj = {}; 6523 message.start !== undefined && (obj.start = message.start.toISOString()); 6524 message.end !== undefined && (obj.end = message.end.toISOString()); 6525 return obj; 6526 }, 6527 }; 6528 var tsProtoGlobalThis = (() => { 6529 if (typeof globalThis !== "undefined") { 6530 return globalThis; 6531 } 6532 if (typeof self !== "undefined") { 6533 return self; 6534 } 6535 if (typeof window !== "undefined") { 6536 return window; 6537 } 6538 if (typeof global !== "undefined") { 6539 return global; 6540 } 6541 throw "Unable to locate global object"; 6542 })(); 6543 function bytesFromBase64(b64) { 6544 if (tsProtoGlobalThis.Buffer) { 6545 return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); 6546 } 6547 else { 6548 const bin = tsProtoGlobalThis.atob(b64); 6549 const arr = new Uint8Array(bin.length); 6550 for (let i = 0; i < bin.length; ++i) { 6551 arr[i] = bin.charCodeAt(i); 6552 } 6553 return arr; 6554 } 6555 } 6556 function base64FromBytes(arr) { 6557 if (tsProtoGlobalThis.Buffer) { 6558 return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); 6559 } 6560 else { 6561 const bin = []; 6562 arr.forEach((byte) => { 6563 bin.push(String.fromCharCode(byte)); 6564 }); 6565 return tsProtoGlobalThis.btoa(bin.join("")); 6566 } 6567 } 6568 function fromTimestamp(t) { 6569 let millis = Number(t.seconds) * 1000; 6570 millis += t.nanos / 1000000; 6571 return new Date(millis); 6572 } 6573 function fromJsonTimestamp(o) { 6574 if (o instanceof Date) { 6575 return o; 6576 } 6577 else if (typeof o === "string") { 6578 return new Date(o); 6579 } 6580 else { 6581 return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); 6582 } 6583 } 6584 function isSet(value) { 6585 return value !== null && value !== undefined; 6586 } 6587 6588 6589 /***/ }), 6590 6591 /***/ 4951: 6592 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 6593 6594 "use strict"; 6595 6596 Object.defineProperty(exports, "__esModule", ({ value: true })); 6597 exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0; 6598 /* eslint-disable */ 6599 const sigstore_common_1 = __nccwpck_require__(2193); 6600 function createBaseKindVersion() { 6601 return { kind: "", version: "" }; 6602 } 6603 exports.KindVersion = { 6604 fromJSON(object) { 6605 return { 6606 kind: isSet(object.kind) ? String(object.kind) : "", 6607 version: isSet(object.version) ? String(object.version) : "", 6608 }; 6609 }, 6610 toJSON(message) { 6611 const obj = {}; 6612 message.kind !== undefined && (obj.kind = message.kind); 6613 message.version !== undefined && (obj.version = message.version); 6614 return obj; 6615 }, 6616 }; 6617 function createBaseCheckpoint() { 6618 return { envelope: "" }; 6619 } 6620 exports.Checkpoint = { 6621 fromJSON(object) { 6622 return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; 6623 }, 6624 toJSON(message) { 6625 const obj = {}; 6626 message.envelope !== undefined && (obj.envelope = message.envelope); 6627 return obj; 6628 }, 6629 }; 6630 function createBaseInclusionProof() { 6631 return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined }; 6632 } 6633 exports.InclusionProof = { 6634 fromJSON(object) { 6635 return { 6636 logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", 6637 rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0), 6638 treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0", 6639 hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [], 6640 checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined, 6641 }; 6642 }, 6643 toJSON(message) { 6644 const obj = {}; 6645 message.logIndex !== undefined && (obj.logIndex = message.logIndex); 6646 message.rootHash !== undefined && 6647 (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0))); 6648 message.treeSize !== undefined && (obj.treeSize = message.treeSize); 6649 if (message.hashes) { 6650 obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0))); 6651 } 6652 else { 6653 obj.hashes = []; 6654 } 6655 message.checkpoint !== undefined && 6656 (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined); 6657 return obj; 6658 }, 6659 }; 6660 function createBaseInclusionPromise() { 6661 return { signedEntryTimestamp: Buffer.alloc(0) }; 6662 } 6663 exports.InclusionPromise = { 6664 fromJSON(object) { 6665 return { 6666 signedEntryTimestamp: isSet(object.signedEntryTimestamp) 6667 ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp)) 6668 : Buffer.alloc(0), 6669 }; 6670 }, 6671 toJSON(message) { 6672 const obj = {}; 6673 message.signedEntryTimestamp !== undefined && 6674 (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); 6675 return obj; 6676 }, 6677 }; 6678 function createBaseTransparencyLogEntry() { 6679 return { 6680 logIndex: "0", 6681 logId: undefined, 6682 kindVersion: undefined, 6683 integratedTime: "0", 6684 inclusionPromise: undefined, 6685 inclusionProof: undefined, 6686 canonicalizedBody: Buffer.alloc(0), 6687 }; 6688 } 6689 exports.TransparencyLogEntry = { 6690 fromJSON(object) { 6691 return { 6692 logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", 6693 logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, 6694 kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined, 6695 integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0", 6696 inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined, 6697 inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined, 6698 canonicalizedBody: isSet(object.canonicalizedBody) 6699 ? Buffer.from(bytesFromBase64(object.canonicalizedBody)) 6700 : Buffer.alloc(0), 6701 }; 6702 }, 6703 toJSON(message) { 6704 const obj = {}; 6705 message.logIndex !== undefined && (obj.logIndex = message.logIndex); 6706 message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); 6707 message.kindVersion !== undefined && 6708 (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined); 6709 message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime); 6710 message.inclusionPromise !== undefined && 6711 (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined); 6712 message.inclusionProof !== undefined && 6713 (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined); 6714 message.canonicalizedBody !== undefined && 6715 (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0))); 6716 return obj; 6717 }, 6718 }; 6719 var tsProtoGlobalThis = (() => { 6720 if (typeof globalThis !== "undefined") { 6721 return globalThis; 6722 } 6723 if (typeof self !== "undefined") { 6724 return self; 6725 } 6726 if (typeof window !== "undefined") { 6727 return window; 6728 } 6729 if (typeof global !== "undefined") { 6730 return global; 6731 } 6732 throw "Unable to locate global object"; 6733 })(); 6734 function bytesFromBase64(b64) { 6735 if (tsProtoGlobalThis.Buffer) { 6736 return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); 6737 } 6738 else { 6739 const bin = tsProtoGlobalThis.atob(b64); 6740 const arr = new Uint8Array(bin.length); 6741 for (let i = 0; i < bin.length; ++i) { 6742 arr[i] = bin.charCodeAt(i); 6743 } 6744 return arr; 6745 } 6746 } 6747 function base64FromBytes(arr) { 6748 if (tsProtoGlobalThis.Buffer) { 6749 return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); 6750 } 6751 else { 6752 const bin = []; 6753 arr.forEach((byte) => { 6754 bin.push(String.fromCharCode(byte)); 6755 }); 6756 return tsProtoGlobalThis.btoa(bin.join("")); 6757 } 6758 } 6759 function isSet(value) { 6760 return value !== null && value !== undefined; 6761 } 6762 6763 6764 /***/ }), 6765 6766 /***/ 4012: 6767 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 6768 6769 "use strict"; 6770 6771 Object.defineProperty(exports, "__esModule", ({ value: true })); 6772 exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; 6773 /* eslint-disable */ 6774 const sigstore_common_1 = __nccwpck_require__(2193); 6775 function createBaseTransparencyLogInstance() { 6776 return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined }; 6777 } 6778 exports.TransparencyLogInstance = { 6779 fromJSON(object) { 6780 return { 6781 baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", 6782 hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0, 6783 publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined, 6784 logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, 6785 checkpointKeyId: isSet(object.checkpointKeyId) ? sigstore_common_1.LogId.fromJSON(object.checkpointKeyId) : undefined, 6786 }; 6787 }, 6788 toJSON(message) { 6789 const obj = {}; 6790 message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl); 6791 message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm)); 6792 message.publicKey !== undefined && 6793 (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined); 6794 message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); 6795 message.checkpointKeyId !== undefined && 6796 (obj.checkpointKeyId = message.checkpointKeyId ? sigstore_common_1.LogId.toJSON(message.checkpointKeyId) : undefined); 6797 return obj; 6798 }, 6799 }; 6800 function createBaseCertificateAuthority() { 6801 return { subject: undefined, uri: "", certChain: undefined, validFor: undefined }; 6802 } 6803 exports.CertificateAuthority = { 6804 fromJSON(object) { 6805 return { 6806 subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined, 6807 uri: isSet(object.uri) ? String(object.uri) : "", 6808 certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined, 6809 validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, 6810 }; 6811 }, 6812 toJSON(message) { 6813 const obj = {}; 6814 message.subject !== undefined && 6815 (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined); 6816 message.uri !== undefined && (obj.uri = message.uri); 6817 message.certChain !== undefined && 6818 (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined); 6819 message.validFor !== undefined && 6820 (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined); 6821 return obj; 6822 }, 6823 }; 6824 function createBaseTrustedRoot() { 6825 return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] }; 6826 } 6827 exports.TrustedRoot = { 6828 fromJSON(object) { 6829 return { 6830 mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", 6831 tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], 6832 certificateAuthorities: Array.isArray(object?.certificateAuthorities) 6833 ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) 6834 : [], 6835 ctlogs: Array.isArray(object?.ctlogs) 6836 ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) 6837 : [], 6838 timestampAuthorities: Array.isArray(object?.timestampAuthorities) 6839 ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) 6840 : [], 6841 }; 6842 }, 6843 toJSON(message) { 6844 const obj = {}; 6845 message.mediaType !== undefined && (obj.mediaType = message.mediaType); 6846 if (message.tlogs) { 6847 obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); 6848 } 6849 else { 6850 obj.tlogs = []; 6851 } 6852 if (message.certificateAuthorities) { 6853 obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); 6854 } 6855 else { 6856 obj.certificateAuthorities = []; 6857 } 6858 if (message.ctlogs) { 6859 obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); 6860 } 6861 else { 6862 obj.ctlogs = []; 6863 } 6864 if (message.timestampAuthorities) { 6865 obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); 6866 } 6867 else { 6868 obj.timestampAuthorities = []; 6869 } 6870 return obj; 6871 }, 6872 }; 6873 function createBaseSigningConfig() { 6874 return { caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] }; 6875 } 6876 exports.SigningConfig = { 6877 fromJSON(object) { 6878 return { 6879 caUrl: isSet(object.caUrl) ? String(object.caUrl) : "", 6880 oidcUrl: isSet(object.oidcUrl) ? String(object.oidcUrl) : "", 6881 tlogUrls: Array.isArray(object?.tlogUrls) ? object.tlogUrls.map((e) => String(e)) : [], 6882 tsaUrls: Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => String(e)) : [], 6883 }; 6884 }, 6885 toJSON(message) { 6886 const obj = {}; 6887 message.caUrl !== undefined && (obj.caUrl = message.caUrl); 6888 message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl); 6889 if (message.tlogUrls) { 6890 obj.tlogUrls = message.tlogUrls.map((e) => e); 6891 } 6892 else { 6893 obj.tlogUrls = []; 6894 } 6895 if (message.tsaUrls) { 6896 obj.tsaUrls = message.tsaUrls.map((e) => e); 6897 } 6898 else { 6899 obj.tsaUrls = []; 6900 } 6901 return obj; 6902 }, 6903 }; 6904 function createBaseClientTrustConfig() { 6905 return { mediaType: "", trustedRoot: undefined, signingConfig: undefined }; 6906 } 6907 exports.ClientTrustConfig = { 6908 fromJSON(object) { 6909 return { 6910 mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", 6911 trustedRoot: isSet(object.trustedRoot) ? exports.TrustedRoot.fromJSON(object.trustedRoot) : undefined, 6912 signingConfig: isSet(object.signingConfig) ? exports.SigningConfig.fromJSON(object.signingConfig) : undefined, 6913 }; 6914 }, 6915 toJSON(message) { 6916 const obj = {}; 6917 message.mediaType !== undefined && (obj.mediaType = message.mediaType); 6918 message.trustedRoot !== undefined && 6919 (obj.trustedRoot = message.trustedRoot ? exports.TrustedRoot.toJSON(message.trustedRoot) : undefined); 6920 message.signingConfig !== undefined && 6921 (obj.signingConfig = message.signingConfig ? exports.SigningConfig.toJSON(message.signingConfig) : undefined); 6922 return obj; 6923 }, 6924 }; 6925 function isSet(value) { 6926 return value !== null && value !== undefined; 6927 } 6928 6929 6930 /***/ }), 6931 6932 /***/ 9980: 6933 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 6934 6935 "use strict"; 6936 6937 Object.defineProperty(exports, "__esModule", ({ value: true })); 6938 exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0; 6939 /* eslint-disable */ 6940 const sigstore_bundle_1 = __nccwpck_require__(8293); 6941 const sigstore_common_1 = __nccwpck_require__(2193); 6942 const sigstore_trustroot_1 = __nccwpck_require__(4012); 6943 function createBaseCertificateIdentity() { 6944 return { issuer: "", san: undefined, oids: [] }; 6945 } 6946 exports.CertificateIdentity = { 6947 fromJSON(object) { 6948 return { 6949 issuer: isSet(object.issuer) ? String(object.issuer) : "", 6950 san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined, 6951 oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [], 6952 }; 6953 }, 6954 toJSON(message) { 6955 const obj = {}; 6956 message.issuer !== undefined && (obj.issuer = message.issuer); 6957 message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined); 6958 if (message.oids) { 6959 obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined); 6960 } 6961 else { 6962 obj.oids = []; 6963 } 6964 return obj; 6965 }, 6966 }; 6967 function createBaseCertificateIdentities() { 6968 return { identities: [] }; 6969 } 6970 exports.CertificateIdentities = { 6971 fromJSON(object) { 6972 return { 6973 identities: Array.isArray(object?.identities) 6974 ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e)) 6975 : [], 6976 }; 6977 }, 6978 toJSON(message) { 6979 const obj = {}; 6980 if (message.identities) { 6981 obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined); 6982 } 6983 else { 6984 obj.identities = []; 6985 } 6986 return obj; 6987 }, 6988 }; 6989 function createBasePublicKeyIdentities() { 6990 return { publicKeys: [] }; 6991 } 6992 exports.PublicKeyIdentities = { 6993 fromJSON(object) { 6994 return { 6995 publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [], 6996 }; 6997 }, 6998 toJSON(message) { 6999 const obj = {}; 7000 if (message.publicKeys) { 7001 obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined); 7002 } 7003 else { 7004 obj.publicKeys = []; 7005 } 7006 return obj; 7007 }, 7008 }; 7009 function createBaseArtifactVerificationOptions() { 7010 return { 7011 signers: undefined, 7012 tlogOptions: undefined, 7013 ctlogOptions: undefined, 7014 tsaOptions: undefined, 7015 integratedTsOptions: undefined, 7016 observerOptions: undefined, 7017 }; 7018 } 7019 exports.ArtifactVerificationOptions = { 7020 fromJSON(object) { 7021 return { 7022 signers: isSet(object.certificateIdentities) 7023 ? { 7024 $case: "certificateIdentities", 7025 certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities), 7026 } 7027 : isSet(object.publicKeys) 7028 ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) } 7029 : undefined, 7030 tlogOptions: isSet(object.tlogOptions) 7031 ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions) 7032 : undefined, 7033 ctlogOptions: isSet(object.ctlogOptions) 7034 ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions) 7035 : undefined, 7036 tsaOptions: isSet(object.tsaOptions) 7037 ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions) 7038 : undefined, 7039 integratedTsOptions: isSet(object.integratedTsOptions) 7040 ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.fromJSON(object.integratedTsOptions) 7041 : undefined, 7042 observerOptions: isSet(object.observerOptions) 7043 ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.fromJSON(object.observerOptions) 7044 : undefined, 7045 }; 7046 }, 7047 toJSON(message) { 7048 const obj = {}; 7049 message.signers?.$case === "certificateIdentities" && 7050 (obj.certificateIdentities = message.signers?.certificateIdentities 7051 ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities) 7052 : undefined); 7053 message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys 7054 ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys) 7055 : undefined); 7056 message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions 7057 ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions) 7058 : undefined); 7059 message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions 7060 ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions) 7061 : undefined); 7062 message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions 7063 ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions) 7064 : undefined); 7065 message.integratedTsOptions !== undefined && (obj.integratedTsOptions = message.integratedTsOptions 7066 ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions) 7067 : undefined); 7068 message.observerOptions !== undefined && (obj.observerOptions = message.observerOptions 7069 ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions) 7070 : undefined); 7071 return obj; 7072 }, 7073 }; 7074 function createBaseArtifactVerificationOptions_TlogOptions() { 7075 return { threshold: 0, performOnlineVerification: false, disable: false }; 7076 } 7077 exports.ArtifactVerificationOptions_TlogOptions = { 7078 fromJSON(object) { 7079 return { 7080 threshold: isSet(object.threshold) ? Number(object.threshold) : 0, 7081 performOnlineVerification: isSet(object.performOnlineVerification) 7082 ? Boolean(object.performOnlineVerification) 7083 : false, 7084 disable: isSet(object.disable) ? Boolean(object.disable) : false, 7085 }; 7086 }, 7087 toJSON(message) { 7088 const obj = {}; 7089 message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); 7090 message.performOnlineVerification !== undefined && 7091 (obj.performOnlineVerification = message.performOnlineVerification); 7092 message.disable !== undefined && (obj.disable = message.disable); 7093 return obj; 7094 }, 7095 }; 7096 function createBaseArtifactVerificationOptions_CtlogOptions() { 7097 return { threshold: 0, disable: false }; 7098 } 7099 exports.ArtifactVerificationOptions_CtlogOptions = { 7100 fromJSON(object) { 7101 return { 7102 threshold: isSet(object.threshold) ? Number(object.threshold) : 0, 7103 disable: isSet(object.disable) ? Boolean(object.disable) : false, 7104 }; 7105 }, 7106 toJSON(message) { 7107 const obj = {}; 7108 message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); 7109 message.disable !== undefined && (obj.disable = message.disable); 7110 return obj; 7111 }, 7112 }; 7113 function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() { 7114 return { threshold: 0, disable: false }; 7115 } 7116 exports.ArtifactVerificationOptions_TimestampAuthorityOptions = { 7117 fromJSON(object) { 7118 return { 7119 threshold: isSet(object.threshold) ? Number(object.threshold) : 0, 7120 disable: isSet(object.disable) ? Boolean(object.disable) : false, 7121 }; 7122 }, 7123 toJSON(message) { 7124 const obj = {}; 7125 message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); 7126 message.disable !== undefined && (obj.disable = message.disable); 7127 return obj; 7128 }, 7129 }; 7130 function createBaseArtifactVerificationOptions_TlogIntegratedTimestampOptions() { 7131 return { threshold: 0, disable: false }; 7132 } 7133 exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = { 7134 fromJSON(object) { 7135 return { 7136 threshold: isSet(object.threshold) ? Number(object.threshold) : 0, 7137 disable: isSet(object.disable) ? Boolean(object.disable) : false, 7138 }; 7139 }, 7140 toJSON(message) { 7141 const obj = {}; 7142 message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); 7143 message.disable !== undefined && (obj.disable = message.disable); 7144 return obj; 7145 }, 7146 }; 7147 function createBaseArtifactVerificationOptions_ObserverTimestampOptions() { 7148 return { threshold: 0, disable: false }; 7149 } 7150 exports.ArtifactVerificationOptions_ObserverTimestampOptions = { 7151 fromJSON(object) { 7152 return { 7153 threshold: isSet(object.threshold) ? Number(object.threshold) : 0, 7154 disable: isSet(object.disable) ? Boolean(object.disable) : false, 7155 }; 7156 }, 7157 toJSON(message) { 7158 const obj = {}; 7159 message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); 7160 message.disable !== undefined && (obj.disable = message.disable); 7161 return obj; 7162 }, 7163 }; 7164 function createBaseArtifact() { 7165 return { data: undefined }; 7166 } 7167 exports.Artifact = { 7168 fromJSON(object) { 7169 return { 7170 data: isSet(object.artifactUri) 7171 ? { $case: "artifactUri", artifactUri: String(object.artifactUri) } 7172 : isSet(object.artifact) 7173 ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } 7174 : undefined, 7175 }; 7176 }, 7177 toJSON(message) { 7178 const obj = {}; 7179 message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri); 7180 message.data?.$case === "artifact" && 7181 (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined); 7182 return obj; 7183 }, 7184 }; 7185 function createBaseInput() { 7186 return { 7187 artifactTrustRoot: undefined, 7188 artifactVerificationOptions: undefined, 7189 bundle: undefined, 7190 artifact: undefined, 7191 }; 7192 } 7193 exports.Input = { 7194 fromJSON(object) { 7195 return { 7196 artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined, 7197 artifactVerificationOptions: isSet(object.artifactVerificationOptions) 7198 ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions) 7199 : undefined, 7200 bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined, 7201 artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined, 7202 }; 7203 }, 7204 toJSON(message) { 7205 const obj = {}; 7206 message.artifactTrustRoot !== undefined && 7207 (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined); 7208 message.artifactVerificationOptions !== undefined && 7209 (obj.artifactVerificationOptions = message.artifactVerificationOptions 7210 ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions) 7211 : undefined); 7212 message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined); 7213 message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined); 7214 return obj; 7215 }, 7216 }; 7217 var tsProtoGlobalThis = (() => { 7218 if (typeof globalThis !== "undefined") { 7219 return globalThis; 7220 } 7221 if (typeof self !== "undefined") { 7222 return self; 7223 } 7224 if (typeof window !== "undefined") { 7225 return window; 7226 } 7227 if (typeof global !== "undefined") { 7228 return global; 7229 } 7230 throw "Unable to locate global object"; 7231 })(); 7232 function bytesFromBase64(b64) { 7233 if (tsProtoGlobalThis.Buffer) { 7234 return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); 7235 } 7236 else { 7237 const bin = tsProtoGlobalThis.atob(b64); 7238 const arr = new Uint8Array(bin.length); 7239 for (let i = 0; i < bin.length; ++i) { 7240 arr[i] = bin.charCodeAt(i); 7241 } 7242 return arr; 7243 } 7244 } 7245 function base64FromBytes(arr) { 7246 if (tsProtoGlobalThis.Buffer) { 7247 return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); 7248 } 7249 else { 7250 const bin = []; 7251 arr.forEach((byte) => { 7252 bin.push(String.fromCharCode(byte)); 7253 }); 7254 return tsProtoGlobalThis.btoa(bin.join("")); 7255 } 7256 } 7257 function isSet(value) { 7258 return value !== null && value !== undefined; 7259 } 7260 7261 7262 /***/ }), 7263 7264 /***/ 530: 7265 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 7266 7267 "use strict"; 7268 7269 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 7270 if (k2 === undefined) k2 = k; 7271 var desc = Object.getOwnPropertyDescriptor(m, k); 7272 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 7273 desc = { enumerable: true, get: function() { return m[k]; } }; 7274 } 7275 Object.defineProperty(o, k2, desc); 7276 }) : (function(o, m, k, k2) { 7277 if (k2 === undefined) k2 = k; 7278 o[k2] = m[k]; 7279 })); 7280 var __exportStar = (this && this.__exportStar) || function(m, exports) { 7281 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); 7282 }; 7283 Object.defineProperty(exports, "__esModule", ({ value: true })); 7284 /* 7285 Copyright 2023 The Sigstore Authors. 7286 7287 Licensed under the Apache License, Version 2.0 (the "License"); 7288 you may not use this file except in compliance with the License. 7289 You may obtain a copy of the License at 7290 7291 http://www.apache.org/licenses/LICENSE-2.0 7292 7293 Unless required by applicable law or agreed to in writing, software 7294 distributed under the License is distributed on an "AS IS" BASIS, 7295 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7296 See the License for the specific language governing permissions and 7297 limitations under the License. 7298 */ 7299 __exportStar(__nccwpck_require__(714), exports); 7300 __exportStar(__nccwpck_require__(8293), exports); 7301 __exportStar(__nccwpck_require__(2193), exports); 7302 __exportStar(__nccwpck_require__(4951), exports); 7303 __exportStar(__nccwpck_require__(4012), exports); 7304 __exportStar(__nccwpck_require__(9980), exports); 7305 7306 7307 /***/ }), 7308 7309 /***/ 5: 7310 /***/ ((__unused_webpack_module, exports) => { 7311 7312 "use strict"; 7313 7314 Object.defineProperty(exports, "__esModule", ({ value: true })); 7315 exports.BaseBundleBuilder = void 0; 7316 // BaseBundleBuilder is a base class for BundleBuilder implementations. It 7317 // provides a the basic wokflow for signing and witnessing an artifact. 7318 // Subclasses must implement the `package` method to assemble a valid bundle 7319 // with the generated signature and verification material. 7320 class BaseBundleBuilder { 7321 constructor(options) { 7322 this.signer = options.signer; 7323 this.witnesses = options.witnesses; 7324 } 7325 // Executes the signing/witnessing process for the given artifact. 7326 async create(artifact) { 7327 const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob)); 7328 const bundle = await this.package(artifact, signature); 7329 // Invoke all of the witnesses in parallel 7330 const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key)))); 7331 // Collect the verification material from all of the witnesses 7332 const tlogEntryList = []; 7333 const timestampList = []; 7334 verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => { 7335 tlogEntryList.push(...(tlogEntries ?? [])); 7336 timestampList.push(...(rfc3161Timestamps ?? [])); 7337 }); 7338 // Merge the collected verification material into the bundle 7339 bundle.verificationMaterial.tlogEntries = tlogEntryList; 7340 bundle.verificationMaterial.timestampVerificationData = { 7341 rfc3161Timestamps: timestampList, 7342 }; 7343 return bundle; 7344 } 7345 // Override this function to apply any pre-signing transformations to the 7346 // artifact. The returned buffer will be signed by the signer. The default 7347 // implementation simply returns the artifact data. 7348 async prepare(artifact) { 7349 return artifact.data; 7350 } 7351 } 7352 exports.BaseBundleBuilder = BaseBundleBuilder; 7353 // Extracts the public key from a KeyMaterial. Returns either the public key 7354 // or the certificate, depending on the type of key material. 7355 function publicKey(key) { 7356 switch (key.$case) { 7357 case 'publicKey': 7358 return key.publicKey; 7359 case 'x509Certificate': 7360 return key.certificate; 7361 } 7362 } 7363 7364 7365 /***/ }), 7366 7367 /***/ 6947: 7368 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 7369 7370 "use strict"; 7371 7372 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 7373 if (k2 === undefined) k2 = k; 7374 var desc = Object.getOwnPropertyDescriptor(m, k); 7375 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 7376 desc = { enumerable: true, get: function() { return m[k]; } }; 7377 } 7378 Object.defineProperty(o, k2, desc); 7379 }) : (function(o, m, k, k2) { 7380 if (k2 === undefined) k2 = k; 7381 o[k2] = m[k]; 7382 })); 7383 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 7384 Object.defineProperty(o, "default", { enumerable: true, value: v }); 7385 }) : function(o, v) { 7386 o["default"] = v; 7387 }); 7388 var __importStar = (this && this.__importStar) || function (mod) { 7389 if (mod && mod.__esModule) return mod; 7390 var result = {}; 7391 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 7392 __setModuleDefault(result, mod); 7393 return result; 7394 }; 7395 Object.defineProperty(exports, "__esModule", ({ value: true })); 7396 exports.toDSSEBundle = exports.toMessageSignatureBundle = void 0; 7397 /* 7398 Copyright 2023 The Sigstore Authors. 7399 7400 Licensed under the Apache License, Version 2.0 (the "License"); 7401 you may not use this file except in compliance with the License. 7402 You may obtain a copy of the License at 7403 7404 http://www.apache.org/licenses/LICENSE-2.0 7405 7406 Unless required by applicable law or agreed to in writing, software 7407 distributed under the License is distributed on an "AS IS" BASIS, 7408 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7409 See the License for the specific language governing permissions and 7410 limitations under the License. 7411 */ 7412 const sigstore = __importStar(__nccwpck_require__(9715)); 7413 const util_1 = __nccwpck_require__(724); 7414 // Helper functions for assembling the parts of a Sigstore bundle 7415 // Message signature bundle - $case: 'messageSignature' 7416 function toMessageSignatureBundle(artifact, signature) { 7417 const digest = util_1.crypto.hash(artifact.data); 7418 return sigstore.toMessageSignatureBundle({ 7419 digest, 7420 signature: signature.signature, 7421 certificate: signature.key.$case === 'x509Certificate' 7422 ? util_1.pem.toDER(signature.key.certificate) 7423 : undefined, 7424 keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, 7425 }); 7426 } 7427 exports.toMessageSignatureBundle = toMessageSignatureBundle; 7428 // DSSE envelope bundle - $case: 'dsseEnvelope' 7429 function toDSSEBundle(artifact, signature, singleCertificate) { 7430 return sigstore.toDSSEBundle({ 7431 artifact: artifact.data, 7432 artifactType: artifact.type, 7433 signature: signature.signature, 7434 certificate: signature.key.$case === 'x509Certificate' 7435 ? util_1.pem.toDER(signature.key.certificate) 7436 : undefined, 7437 keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, 7438 singleCertificate, 7439 }); 7440 } 7441 exports.toDSSEBundle = toDSSEBundle; 7442 7443 7444 /***/ }), 7445 7446 /***/ 8791: 7447 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7448 7449 "use strict"; 7450 7451 Object.defineProperty(exports, "__esModule", ({ value: true })); 7452 exports.DSSEBundleBuilder = void 0; 7453 /* 7454 Copyright 2023 The Sigstore Authors. 7455 7456 Licensed under the Apache License, Version 2.0 (the "License"); 7457 you may not use this file except in compliance with the License. 7458 You may obtain a copy of the License at 7459 7460 http://www.apache.org/licenses/LICENSE-2.0 7461 7462 Unless required by applicable law or agreed to in writing, software 7463 distributed under the License is distributed on an "AS IS" BASIS, 7464 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7465 See the License for the specific language governing permissions and 7466 limitations under the License. 7467 */ 7468 const util_1 = __nccwpck_require__(724); 7469 const base_1 = __nccwpck_require__(5); 7470 const bundle_1 = __nccwpck_require__(6947); 7471 // BundleBuilder implementation for DSSE wrapped attestations 7472 class DSSEBundleBuilder extends base_1.BaseBundleBuilder { 7473 constructor(options) { 7474 super(options); 7475 this.singleCertificate = options.singleCertificate ?? false; 7476 } 7477 // DSSE requires the artifact to be pre-encoded with the payload type 7478 // before the signature is generated. 7479 async prepare(artifact) { 7480 const a = artifactDefaults(artifact); 7481 return util_1.dsse.preAuthEncoding(a.type, a.data); 7482 } 7483 // Packages the artifact and signature into a DSSE bundle 7484 async package(artifact, signature) { 7485 return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.singleCertificate); 7486 } 7487 } 7488 exports.DSSEBundleBuilder = DSSEBundleBuilder; 7489 // Defaults the artifact type to an empty string if not provided 7490 function artifactDefaults(artifact) { 7491 return { 7492 ...artifact, 7493 type: artifact.type ?? '', 7494 }; 7495 } 7496 7497 7498 /***/ }), 7499 7500 /***/ 4929: 7501 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7502 7503 "use strict"; 7504 7505 Object.defineProperty(exports, "__esModule", ({ value: true })); 7506 exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; 7507 var dsse_1 = __nccwpck_require__(8791); 7508 Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } })); 7509 var message_1 = __nccwpck_require__(6258); 7510 Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } })); 7511 7512 7513 /***/ }), 7514 7515 /***/ 6258: 7516 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7517 7518 "use strict"; 7519 7520 Object.defineProperty(exports, "__esModule", ({ value: true })); 7521 exports.MessageSignatureBundleBuilder = void 0; 7522 /* 7523 Copyright 2023 The Sigstore Authors. 7524 7525 Licensed under the Apache License, Version 2.0 (the "License"); 7526 you may not use this file except in compliance with the License. 7527 You may obtain a copy of the License at 7528 7529 http://www.apache.org/licenses/LICENSE-2.0 7530 7531 Unless required by applicable law or agreed to in writing, software 7532 distributed under the License is distributed on an "AS IS" BASIS, 7533 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7534 See the License for the specific language governing permissions and 7535 limitations under the License. 7536 */ 7537 const base_1 = __nccwpck_require__(5); 7538 const bundle_1 = __nccwpck_require__(6947); 7539 // BundleBuilder implementation for raw message signatures 7540 class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder { 7541 constructor(options) { 7542 super(options); 7543 } 7544 async package(artifact, signature) { 7545 return (0, bundle_1.toMessageSignatureBundle)(artifact, signature); 7546 } 7547 } 7548 exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder; 7549 7550 7551 /***/ }), 7552 7553 /***/ 532: 7554 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7555 7556 "use strict"; 7557 7558 /* 7559 Copyright 2023 The Sigstore Authors. 7560 7561 Licensed under the Apache License, Version 2.0 (the "License"); 7562 you may not use this file except in compliance with the License. 7563 You may obtain a copy of the License at 7564 7565 http://www.apache.org/licenses/LICENSE-2.0 7566 7567 Unless required by applicable law or agreed to in writing, software 7568 distributed under the License is distributed on an "AS IS" BASIS, 7569 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7570 See the License for the specific language governing permissions and 7571 limitations under the License. 7572 */ 7573 Object.defineProperty(exports, "__esModule", ({ value: true })); 7574 exports.internalError = exports.InternalError = void 0; 7575 const error_1 = __nccwpck_require__(1294); 7576 class InternalError extends Error { 7577 constructor({ code, message, cause, }) { 7578 super(message); 7579 this.name = this.constructor.name; 7580 this.cause = cause; 7581 this.code = code; 7582 } 7583 } 7584 exports.InternalError = InternalError; 7585 function internalError(err, code, message) { 7586 if (err instanceof error_1.HTTPError) { 7587 message += ` - ${err.message}`; 7588 } 7589 throw new InternalError({ 7590 code: code, 7591 message: message, 7592 cause: err, 7593 }); 7594 } 7595 exports.internalError = internalError; 7596 7597 7598 /***/ }), 7599 7600 /***/ 1294: 7601 /***/ ((__unused_webpack_module, exports) => { 7602 7603 "use strict"; 7604 7605 /* 7606 Copyright 2023 The Sigstore Authors. 7607 7608 Licensed under the Apache License, Version 2.0 (the "License"); 7609 you may not use this file except in compliance with the License. 7610 You may obtain a copy of the License at 7611 7612 http://www.apache.org/licenses/LICENSE-2.0 7613 7614 Unless required by applicable law or agreed to in writing, software 7615 distributed under the License is distributed on an "AS IS" BASIS, 7616 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7617 See the License for the specific language governing permissions and 7618 limitations under the License. 7619 */ 7620 Object.defineProperty(exports, "__esModule", ({ value: true })); 7621 exports.HTTPError = void 0; 7622 class HTTPError extends Error { 7623 constructor({ status, message, location, }) { 7624 super(`(${status}) ${message}`); 7625 this.statusCode = status; 7626 this.location = location; 7627 } 7628 } 7629 exports.HTTPError = HTTPError; 7630 7631 7632 /***/ }), 7633 7634 /***/ 8509: 7635 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 7636 7637 "use strict"; 7638 7639 var __importDefault = (this && this.__importDefault) || function (mod) { 7640 return (mod && mod.__esModule) ? mod : { "default": mod }; 7641 }; 7642 Object.defineProperty(exports, "__esModule", ({ value: true })); 7643 exports.fetchWithRetry = void 0; 7644 /* 7645 Copyright 2023 The Sigstore Authors. 7646 7647 Licensed under the Apache License, Version 2.0 (the "License"); 7648 you may not use this file except in compliance with the License. 7649 You may obtain a copy of the License at 7650 7651 http://www.apache.org/licenses/LICENSE-2.0 7652 7653 Unless required by applicable law or agreed to in writing, software 7654 distributed under the License is distributed on an "AS IS" BASIS, 7655 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7656 See the License for the specific language governing permissions and 7657 limitations under the License. 7658 */ 7659 const http2_1 = __nccwpck_require__(5158); 7660 const make_fetch_happen_1 = __importDefault(__nccwpck_require__(9525)); 7661 const proc_log_1 = __nccwpck_require__(6528); 7662 const promise_retry_1 = __importDefault(__nccwpck_require__(4742)); 7663 const util_1 = __nccwpck_require__(724); 7664 const error_1 = __nccwpck_require__(1294); 7665 const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; 7666 async function fetchWithRetry(url, options) { 7667 return (0, promise_retry_1.default)(async (retry, attemptNum) => { 7668 const method = options.method || 'POST'; 7669 const headers = { 7670 [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(), 7671 ...options.headers, 7672 }; 7673 const response = await (0, make_fetch_happen_1.default)(url, { 7674 method, 7675 headers, 7676 body: options.body, 7677 timeout: options.timeout, 7678 retry: false, // We're handling retries ourselves 7679 }).catch((reason) => { 7680 proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`); 7681 return retry(reason); 7682 }); 7683 if (response.ok) { 7684 return response; 7685 } 7686 else { 7687 const error = await errorFromResponse(response); 7688 proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`); 7689 if (retryable(response.status)) { 7690 return retry(error); 7691 } 7692 else { 7693 throw error; 7694 } 7695 } 7696 }, retryOpts(options.retry)); 7697 } 7698 exports.fetchWithRetry = fetchWithRetry; 7699 // Translate a Response into an HTTPError instance. This will attempt to parse 7700 // the response body for a message, but will default to the statusText if none 7701 // is found. 7702 const errorFromResponse = async (response) => { 7703 let message = response.statusText; 7704 const location = response.headers?.get(HTTP2_HEADER_LOCATION) || undefined; 7705 const contentType = response.headers?.get(HTTP2_HEADER_CONTENT_TYPE); 7706 // If response type is JSON, try to parse the body for a message 7707 if (contentType?.includes('application/json')) { 7708 try { 7709 const body = await response.json(); 7710 message = body.message || message; 7711 } 7712 catch (e) { 7713 // ignore 7714 } 7715 } 7716 return new error_1.HTTPError({ 7717 status: response.status, 7718 message: message, 7719 location: location, 7720 }); 7721 }; 7722 // Determine if a status code is retryable. This includes 5xx errors, 408, and 7723 // 429. 7724 const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; 7725 // Normalize the retry options to the format expected by promise-retry 7726 const retryOpts = (retry) => { 7727 if (typeof retry === 'boolean') { 7728 return { retries: retry ? 1 : 0 }; 7729 } 7730 else if (typeof retry === 'number') { 7731 return { retries: retry }; 7732 } 7733 else { 7734 return { retries: 0, ...retry }; 7735 } 7736 }; 7737 7738 7739 /***/ }), 7740 7741 /***/ 269: 7742 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7743 7744 "use strict"; 7745 7746 Object.defineProperty(exports, "__esModule", ({ value: true })); 7747 exports.Fulcio = void 0; 7748 /* 7749 Copyright 2023 The Sigstore Authors. 7750 7751 Licensed under the Apache License, Version 2.0 (the "License"); 7752 you may not use this file except in compliance with the License. 7753 You may obtain a copy of the License at 7754 7755 http://www.apache.org/licenses/LICENSE-2.0 7756 7757 Unless required by applicable law or agreed to in writing, software 7758 distributed under the License is distributed on an "AS IS" BASIS, 7759 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7760 See the License for the specific language governing permissions and 7761 limitations under the License. 7762 */ 7763 const fetch_1 = __nccwpck_require__(8509); 7764 /** 7765 * Fulcio API client. 7766 */ 7767 class Fulcio { 7768 constructor(options) { 7769 this.options = options; 7770 } 7771 async createSigningCertificate(request) { 7772 const { baseURL, retry, timeout } = this.options; 7773 const url = `${baseURL}/api/v2/signingCert`; 7774 const response = await (0, fetch_1.fetchWithRetry)(url, { 7775 headers: { 7776 'Content-Type': 'application/json', 7777 }, 7778 body: JSON.stringify(request), 7779 timeout, 7780 retry, 7781 }); 7782 return response.json(); 7783 } 7784 } 7785 exports.Fulcio = Fulcio; 7786 7787 7788 /***/ }), 7789 7790 /***/ 6205: 7791 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7792 7793 "use strict"; 7794 7795 Object.defineProperty(exports, "__esModule", ({ value: true })); 7796 exports.Rekor = void 0; 7797 /* 7798 Copyright 2023 The Sigstore Authors. 7799 7800 Licensed under the Apache License, Version 2.0 (the "License"); 7801 you may not use this file except in compliance with the License. 7802 You may obtain a copy of the License at 7803 7804 http://www.apache.org/licenses/LICENSE-2.0 7805 7806 Unless required by applicable law or agreed to in writing, software 7807 distributed under the License is distributed on an "AS IS" BASIS, 7808 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7809 See the License for the specific language governing permissions and 7810 limitations under the License. 7811 */ 7812 const fetch_1 = __nccwpck_require__(8509); 7813 /** 7814 * Rekor API client. 7815 */ 7816 class Rekor { 7817 constructor(options) { 7818 this.options = options; 7819 } 7820 /** 7821 * Create a new entry in the Rekor log. 7822 * @param propsedEntry {ProposedEntry} Data to create a new entry 7823 * @returns {Promise<Entry>} The created entry 7824 */ 7825 async createEntry(propsedEntry) { 7826 const { baseURL, timeout, retry } = this.options; 7827 const url = `${baseURL}/api/v1/log/entries`; 7828 const response = await (0, fetch_1.fetchWithRetry)(url, { 7829 headers: { 7830 'Content-Type': 'application/json', 7831 Accept: 'application/json', 7832 }, 7833 body: JSON.stringify(propsedEntry), 7834 timeout, 7835 retry, 7836 }); 7837 const data = await response.json(); 7838 return entryFromResponse(data); 7839 } 7840 /** 7841 * Get an entry from the Rekor log. 7842 * @param uuid {string} The UUID of the entry to retrieve 7843 * @returns {Promise<Entry>} The retrieved entry 7844 */ 7845 async getEntry(uuid) { 7846 const { baseURL, timeout, retry } = this.options; 7847 const url = `${baseURL}/api/v1/log/entries/${uuid}`; 7848 const response = await (0, fetch_1.fetchWithRetry)(url, { 7849 method: 'GET', 7850 headers: { 7851 Accept: 'application/json', 7852 }, 7853 timeout, 7854 retry, 7855 }); 7856 const data = await response.json(); 7857 return entryFromResponse(data); 7858 } 7859 } 7860 exports.Rekor = Rekor; 7861 // Unpack the response from the Rekor API into a more convenient format. 7862 function entryFromResponse(data) { 7863 const entries = Object.entries(data); 7864 if (entries.length != 1) { 7865 throw new Error('Received multiple entries in Rekor response'); 7866 } 7867 // Grab UUID and entry data from the response 7868 const [uuid, entry] = entries[0]; 7869 return { 7870 ...entry, 7871 uuid, 7872 }; 7873 } 7874 7875 7876 /***/ }), 7877 7878 /***/ 2759: 7879 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 7880 7881 "use strict"; 7882 7883 Object.defineProperty(exports, "__esModule", ({ value: true })); 7884 exports.TimestampAuthority = void 0; 7885 /* 7886 Copyright 2023 The Sigstore Authors. 7887 7888 Licensed under the Apache License, Version 2.0 (the "License"); 7889 you may not use this file except in compliance with the License. 7890 You may obtain a copy of the License at 7891 7892 http://www.apache.org/licenses/LICENSE-2.0 7893 7894 Unless required by applicable law or agreed to in writing, software 7895 distributed under the License is distributed on an "AS IS" BASIS, 7896 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7897 See the License for the specific language governing permissions and 7898 limitations under the License. 7899 */ 7900 const fetch_1 = __nccwpck_require__(8509); 7901 class TimestampAuthority { 7902 constructor(options) { 7903 this.options = options; 7904 } 7905 async createTimestamp(request) { 7906 const { baseURL, timeout, retry } = this.options; 7907 const url = `${baseURL}/api/v1/timestamp`; 7908 const response = await (0, fetch_1.fetchWithRetry)(url, { 7909 headers: { 7910 'Content-Type': 'application/json', 7911 }, 7912 body: JSON.stringify(request), 7913 timeout, 7914 retry, 7915 }); 7916 return response.buffer(); 7917 } 7918 } 7919 exports.TimestampAuthority = TimestampAuthority; 7920 7921 7922 /***/ }), 7923 7924 /***/ 3110: 7925 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 7926 7927 "use strict"; 7928 7929 var __importDefault = (this && this.__importDefault) || function (mod) { 7930 return (mod && mod.__esModule) ? mod : { "default": mod }; 7931 }; 7932 Object.defineProperty(exports, "__esModule", ({ value: true })); 7933 exports.CIContextProvider = void 0; 7934 /* 7935 Copyright 2023 The Sigstore Authors. 7936 7937 Licensed under the Apache License, Version 2.0 (the "License"); 7938 you may not use this file except in compliance with the License. 7939 You may obtain a copy of the License at 7940 7941 http://www.apache.org/licenses/LICENSE-2.0 7942 7943 Unless required by applicable law or agreed to in writing, software 7944 distributed under the License is distributed on an "AS IS" BASIS, 7945 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 7946 See the License for the specific language governing permissions and 7947 limitations under the License. 7948 */ 7949 const make_fetch_happen_1 = __importDefault(__nccwpck_require__(9525)); 7950 // Collection of all the CI-specific providers we have implemented 7951 const providers = [getGHAToken, getEnv]; 7952 /** 7953 * CIContextProvider is a composite identity provider which will iterate 7954 * over all of the CI-specific providers and return the token from the first 7955 * one that resolves. 7956 */ 7957 class CIContextProvider { 7958 /* istanbul ignore next */ 7959 constructor(audience = 'sigstore') { 7960 this.audience = audience; 7961 } 7962 // Invoke all registered ProviderFuncs and return the value of whichever one 7963 // resolves first. 7964 async getToken() { 7965 return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available')); 7966 } 7967 } 7968 exports.CIContextProvider = CIContextProvider; 7969 /** 7970 * getGHAToken can retrieve an OIDC token when running in a GitHub Actions 7971 * workflow 7972 */ 7973 async function getGHAToken(audience) { 7974 // Check to see if we're running in GitHub Actions 7975 if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || 7976 !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { 7977 return Promise.reject('no token available'); 7978 } 7979 // Construct URL to request token w/ appropriate audience 7980 const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL); 7981 url.searchParams.append('audience', audience); 7982 const response = await (0, make_fetch_happen_1.default)(url.href, { 7983 retry: 2, 7984 headers: { 7985 Accept: 'application/json', 7986 Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, 7987 }, 7988 }); 7989 return response.json().then((data) => data.value); 7990 } 7991 /** 7992 * getEnv can retrieve an OIDC token from an environment variable. 7993 * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar 7994 */ 7995 async function getEnv() { 7996 if (!process.env.SIGSTORE_ID_TOKEN) { 7997 return Promise.reject('no token available'); 7998 } 7999 return process.env.SIGSTORE_ID_TOKEN; 8000 } 8001 8002 8003 /***/ }), 8004 8005 /***/ 4463: 8006 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8007 8008 "use strict"; 8009 8010 Object.defineProperty(exports, "__esModule", ({ value: true })); 8011 exports.CIContextProvider = void 0; 8012 /* 8013 Copyright 2023 The Sigstore Authors. 8014 8015 Licensed under the Apache License, Version 2.0 (the "License"); 8016 you may not use this file except in compliance with the License. 8017 You may obtain a copy of the License at 8018 8019 http://www.apache.org/licenses/LICENSE-2.0 8020 8021 Unless required by applicable law or agreed to in writing, software 8022 distributed under the License is distributed on an "AS IS" BASIS, 8023 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8024 See the License for the specific language governing permissions and 8025 limitations under the License. 8026 */ 8027 var ci_1 = __nccwpck_require__(3110); 8028 Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return ci_1.CIContextProvider; } })); 8029 8030 8031 /***/ }), 8032 8033 /***/ 2071: 8034 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8035 8036 "use strict"; 8037 8038 Object.defineProperty(exports, "__esModule", ({ value: true })); 8039 exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; 8040 var bundler_1 = __nccwpck_require__(4929); 8041 Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } })); 8042 Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } })); 8043 var error_1 = __nccwpck_require__(532); 8044 Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return error_1.InternalError; } })); 8045 var identity_1 = __nccwpck_require__(4463); 8046 Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return identity_1.CIContextProvider; } })); 8047 var signer_1 = __nccwpck_require__(7551); 8048 Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } })); 8049 Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return signer_1.FulcioSigner; } })); 8050 var witness_1 = __nccwpck_require__(2170); 8051 Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } })); 8052 Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return witness_1.RekorWitness; } })); 8053 Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return witness_1.TSAWitness; } })); 8054 8055 8056 /***/ }), 8057 8058 /***/ 334: 8059 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8060 8061 "use strict"; 8062 8063 Object.defineProperty(exports, "__esModule", ({ value: true })); 8064 exports.CAClient = void 0; 8065 /* 8066 Copyright 2023 The Sigstore Authors. 8067 8068 Licensed under the Apache License, Version 2.0 (the "License"); 8069 you may not use this file except in compliance with the License. 8070 You may obtain a copy of the License at 8071 8072 http://www.apache.org/licenses/LICENSE-2.0 8073 8074 Unless required by applicable law or agreed to in writing, software 8075 distributed under the License is distributed on an "AS IS" BASIS, 8076 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8077 See the License for the specific language governing permissions and 8078 limitations under the License. 8079 */ 8080 const error_1 = __nccwpck_require__(532); 8081 const fulcio_1 = __nccwpck_require__(269); 8082 class CAClient { 8083 constructor(options) { 8084 this.fulcio = new fulcio_1.Fulcio({ 8085 baseURL: options.fulcioBaseURL, 8086 retry: options.retry, 8087 timeout: options.timeout, 8088 }); 8089 } 8090 async createSigningCertificate(identityToken, publicKey, challenge) { 8091 const request = toCertificateRequest(identityToken, publicKey, challenge); 8092 try { 8093 const resp = await this.fulcio.createSigningCertificate(request); 8094 // Account for the fact that the response may contain either a 8095 // signedCertificateEmbeddedSct or a signedCertificateDetachedSct. 8096 const cert = resp.signedCertificateEmbeddedSct 8097 ? resp.signedCertificateEmbeddedSct 8098 : resp.signedCertificateDetachedSct; 8099 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 8100 return cert.chain.certificates; 8101 } 8102 catch (err) { 8103 (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate'); 8104 } 8105 } 8106 } 8107 exports.CAClient = CAClient; 8108 function toCertificateRequest(identityToken, publicKey, challenge) { 8109 return { 8110 credentials: { 8111 oidcIdentityToken: identityToken, 8112 }, 8113 publicKeyRequest: { 8114 publicKey: { 8115 algorithm: 'ECDSA', 8116 content: publicKey, 8117 }, 8118 proofOfPossession: challenge.toString('base64'), 8119 }, 8120 }; 8121 } 8122 8123 8124 /***/ }), 8125 8126 /***/ 8489: 8127 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 8128 8129 "use strict"; 8130 8131 var __importDefault = (this && this.__importDefault) || function (mod) { 8132 return (mod && mod.__esModule) ? mod : { "default": mod }; 8133 }; 8134 Object.defineProperty(exports, "__esModule", ({ value: true })); 8135 exports.EphemeralSigner = void 0; 8136 /* 8137 Copyright 2023 The Sigstore Authors. 8138 8139 Licensed under the Apache License, Version 2.0 (the "License"); 8140 you may not use this file except in compliance with the License. 8141 You may obtain a copy of the License at 8142 8143 http://www.apache.org/licenses/LICENSE-2.0 8144 8145 Unless required by applicable law or agreed to in writing, software 8146 distributed under the License is distributed on an "AS IS" BASIS, 8147 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8148 See the License for the specific language governing permissions and 8149 limitations under the License. 8150 */ 8151 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 8152 const EC_KEYPAIR_TYPE = 'ec'; 8153 const P256_CURVE = 'P-256'; 8154 // Signer implementation which uses an ephemeral keypair to sign artifacts. 8155 // The private key lives only in memory and is tied to the lifetime of the 8156 // EphemeralSigner instance. 8157 class EphemeralSigner { 8158 constructor() { 8159 this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { 8160 namedCurve: P256_CURVE, 8161 }); 8162 } 8163 async sign(data) { 8164 const signature = crypto_1.default.sign(null, data, this.keypair.privateKey); 8165 const publicKey = this.keypair.publicKey 8166 .export({ format: 'pem', type: 'spki' }) 8167 .toString('ascii'); 8168 return { 8169 signature: signature, 8170 key: { $case: 'publicKey', publicKey }, 8171 }; 8172 } 8173 } 8174 exports.EphemeralSigner = EphemeralSigner; 8175 8176 8177 /***/ }), 8178 8179 /***/ 7328: 8180 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8181 8182 "use strict"; 8183 8184 Object.defineProperty(exports, "__esModule", ({ value: true })); 8185 exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; 8186 /* 8187 Copyright 2023 The Sigstore Authors. 8188 8189 Licensed under the Apache License, Version 2.0 (the "License"); 8190 you may not use this file except in compliance with the License. 8191 You may obtain a copy of the License at 8192 8193 http://www.apache.org/licenses/LICENSE-2.0 8194 8195 Unless required by applicable law or agreed to in writing, software 8196 distributed under the License is distributed on an "AS IS" BASIS, 8197 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8198 See the License for the specific language governing permissions and 8199 limitations under the License. 8200 */ 8201 const error_1 = __nccwpck_require__(532); 8202 const util_1 = __nccwpck_require__(724); 8203 const ca_1 = __nccwpck_require__(334); 8204 const ephemeral_1 = __nccwpck_require__(8489); 8205 exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev'; 8206 // Signer implementation which can be used to decorate another signer 8207 // with a Fulcio-issued signing certificate for the signer's public key. 8208 // Must be instantiated with an identity provider which can provide a JWT 8209 // which represents the identity to be bound to the signing certificate. 8210 class FulcioSigner { 8211 constructor(options) { 8212 this.ca = new ca_1.CAClient({ 8213 ...options, 8214 fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL, 8215 }); 8216 this.identityProvider = options.identityProvider; 8217 this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner(); 8218 } 8219 async sign(data) { 8220 // Retrieve identity token from the supplied identity provider 8221 const identityToken = await this.getIdentityToken(); 8222 // Extract challenge claim from OIDC token 8223 let subject; 8224 try { 8225 subject = util_1.oidc.extractJWTSubject(identityToken); 8226 } 8227 catch (err) { 8228 throw new error_1.InternalError({ 8229 code: 'IDENTITY_TOKEN_PARSE_ERROR', 8230 message: `invalid identity token: ${identityToken}`, 8231 cause: err, 8232 }); 8233 } 8234 // Construct challenge value by signing the subject claim 8235 const challenge = await this.keyHolder.sign(Buffer.from(subject)); 8236 if (challenge.key.$case !== 'publicKey') { 8237 throw new error_1.InternalError({ 8238 code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 8239 message: 'unexpected format for signing key', 8240 }); 8241 } 8242 // Create signing certificate 8243 const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature); 8244 // Generate artifact signature 8245 const signature = await this.keyHolder.sign(data); 8246 // Specifically returning only the first certificate in the chain 8247 // as the key. 8248 return { 8249 signature: signature.signature, 8250 key: { 8251 $case: 'x509Certificate', 8252 certificate: certificates[0], 8253 }, 8254 }; 8255 } 8256 async getIdentityToken() { 8257 try { 8258 return await this.identityProvider.getToken(); 8259 } 8260 catch (err) { 8261 throw new error_1.InternalError({ 8262 code: 'IDENTITY_TOKEN_READ_ERROR', 8263 message: 'error retrieving identity token', 8264 cause: err, 8265 }); 8266 } 8267 } 8268 } 8269 exports.FulcioSigner = FulcioSigner; 8270 8271 8272 /***/ }), 8273 8274 /***/ 7551: 8275 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8276 8277 "use strict"; 8278 8279 /* istanbul ignore file */ 8280 Object.defineProperty(exports, "__esModule", ({ value: true })); 8281 exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; 8282 /* 8283 Copyright 2023 The Sigstore Authors. 8284 8285 Licensed under the Apache License, Version 2.0 (the "License"); 8286 you may not use this file except in compliance with the License. 8287 You may obtain a copy of the License at 8288 8289 http://www.apache.org/licenses/LICENSE-2.0 8290 8291 Unless required by applicable law or agreed to in writing, software 8292 distributed under the License is distributed on an "AS IS" BASIS, 8293 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8294 See the License for the specific language governing permissions and 8295 limitations under the License. 8296 */ 8297 var fulcio_1 = __nccwpck_require__(7328); 8298 Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } })); 8299 Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return fulcio_1.FulcioSigner; } })); 8300 8301 8302 /***/ }), 8303 8304 /***/ 724: 8305 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 8306 8307 "use strict"; 8308 8309 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 8310 if (k2 === undefined) k2 = k; 8311 var desc = Object.getOwnPropertyDescriptor(m, k); 8312 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 8313 desc = { enumerable: true, get: function() { return m[k]; } }; 8314 } 8315 Object.defineProperty(o, k2, desc); 8316 }) : (function(o, m, k, k2) { 8317 if (k2 === undefined) k2 = k; 8318 o[k2] = m[k]; 8319 })); 8320 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 8321 Object.defineProperty(o, "default", { enumerable: true, value: v }); 8322 }) : function(o, v) { 8323 o["default"] = v; 8324 }); 8325 var __importStar = (this && this.__importStar) || function (mod) { 8326 if (mod && mod.__esModule) return mod; 8327 var result = {}; 8328 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 8329 __setModuleDefault(result, mod); 8330 return result; 8331 }; 8332 Object.defineProperty(exports, "__esModule", ({ value: true })); 8333 exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0; 8334 /* 8335 Copyright 2023 The Sigstore Authors. 8336 8337 Licensed under the Apache License, Version 2.0 (the "License"); 8338 you may not use this file except in compliance with the License. 8339 You may obtain a copy of the License at 8340 8341 http://www.apache.org/licenses/LICENSE-2.0 8342 8343 Unless required by applicable law or agreed to in writing, software 8344 distributed under the License is distributed on an "AS IS" BASIS, 8345 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8346 See the License for the specific language governing permissions and 8347 limitations under the License. 8348 */ 8349 var core_1 = __nccwpck_require__(3352); 8350 Object.defineProperty(exports, "crypto", ({ enumerable: true, get: function () { return core_1.crypto; } })); 8351 Object.defineProperty(exports, "dsse", ({ enumerable: true, get: function () { return core_1.dsse; } })); 8352 Object.defineProperty(exports, "encoding", ({ enumerable: true, get: function () { return core_1.encoding; } })); 8353 Object.defineProperty(exports, "json", ({ enumerable: true, get: function () { return core_1.json; } })); 8354 Object.defineProperty(exports, "pem", ({ enumerable: true, get: function () { return core_1.pem; } })); 8355 exports.oidc = __importStar(__nccwpck_require__(3397)); 8356 exports.ua = __importStar(__nccwpck_require__(6253)); 8357 8358 8359 /***/ }), 8360 8361 /***/ 3397: 8362 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8363 8364 "use strict"; 8365 8366 Object.defineProperty(exports, "__esModule", ({ value: true })); 8367 exports.extractJWTSubject = void 0; 8368 /* 8369 Copyright 2023 The Sigstore Authors. 8370 8371 Licensed under the Apache License, Version 2.0 (the "License"); 8372 you may not use this file except in compliance with the License. 8373 You may obtain a copy of the License at 8374 8375 http://www.apache.org/licenses/LICENSE-2.0 8376 8377 Unless required by applicable law or agreed to in writing, software 8378 distributed under the License is distributed on an "AS IS" BASIS, 8379 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8380 See the License for the specific language governing permissions and 8381 limitations under the License. 8382 */ 8383 const core_1 = __nccwpck_require__(3352); 8384 function extractJWTSubject(jwt) { 8385 const parts = jwt.split('.', 3); 8386 const payload = JSON.parse(core_1.encoding.base64Decode(parts[1])); 8387 switch (payload.iss) { 8388 case 'https://accounts.google.com': 8389 case 'https://oauth2.sigstore.dev/auth': 8390 return payload.email; 8391 default: 8392 return payload.sub; 8393 } 8394 } 8395 exports.extractJWTSubject = extractJWTSubject; 8396 8397 8398 /***/ }), 8399 8400 /***/ 6253: 8401 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 8402 8403 "use strict"; 8404 8405 var __importDefault = (this && this.__importDefault) || function (mod) { 8406 return (mod && mod.__esModule) ? mod : { "default": mod }; 8407 }; 8408 Object.defineProperty(exports, "__esModule", ({ value: true })); 8409 exports.getUserAgent = void 0; 8410 /* 8411 Copyright 2023 The Sigstore Authors. 8412 8413 Licensed under the Apache License, Version 2.0 (the "License"); 8414 you may not use this file except in compliance with the License. 8415 You may obtain a copy of the License at 8416 8417 http://www.apache.org/licenses/LICENSE-2.0 8418 8419 Unless required by applicable law or agreed to in writing, software 8420 distributed under the License is distributed on an "AS IS" BASIS, 8421 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8422 See the License for the specific language governing permissions and 8423 limitations under the License. 8424 */ 8425 const os_1 = __importDefault(__nccwpck_require__(2037)); 8426 // Format User-Agent: <product> / <product-version> (<platform>) 8427 // source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent 8428 const getUserAgent = () => { 8429 // eslint-disable-next-line @typescript-eslint/no-var-requires 8430 const packageVersion = (__nccwpck_require__(8992)/* .version */ .i8); 8431 const nodeVersion = process.version; 8432 const platformName = os_1.default.platform(); 8433 const archName = os_1.default.arch(); 8434 return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`; 8435 }; 8436 exports.getUserAgent = getUserAgent; 8437 8438 8439 /***/ }), 8440 8441 /***/ 2170: 8442 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8443 8444 "use strict"; 8445 8446 /* istanbul ignore file */ 8447 Object.defineProperty(exports, "__esModule", ({ value: true })); 8448 exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; 8449 /* 8450 Copyright 2023 The Sigstore Authors. 8451 8452 Licensed under the Apache License, Version 2.0 (the "License"); 8453 you may not use this file except in compliance with the License. 8454 You may obtain a copy of the License at 8455 8456 http://www.apache.org/licenses/LICENSE-2.0 8457 8458 Unless required by applicable law or agreed to in writing, software 8459 distributed under the License is distributed on an "AS IS" BASIS, 8460 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8461 See the License for the specific language governing permissions and 8462 limitations under the License. 8463 */ 8464 var tlog_1 = __nccwpck_require__(7843); 8465 Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } })); 8466 Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return tlog_1.RekorWitness; } })); 8467 var tsa_1 = __nccwpck_require__(49); 8468 Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return tsa_1.TSAWitness; } })); 8469 8470 8471 /***/ }), 8472 8473 /***/ 6737: 8474 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8475 8476 "use strict"; 8477 8478 Object.defineProperty(exports, "__esModule", ({ value: true })); 8479 exports.TLogClient = void 0; 8480 /* 8481 Copyright 2023 The Sigstore Authors. 8482 8483 Licensed under the Apache License, Version 2.0 (the "License"); 8484 you may not use this file except in compliance with the License. 8485 You may obtain a copy of the License at 8486 8487 http://www.apache.org/licenses/LICENSE-2.0 8488 8489 Unless required by applicable law or agreed to in writing, software 8490 distributed under the License is distributed on an "AS IS" BASIS, 8491 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8492 See the License for the specific language governing permissions and 8493 limitations under the License. 8494 */ 8495 const error_1 = __nccwpck_require__(532); 8496 const error_2 = __nccwpck_require__(1294); 8497 const rekor_1 = __nccwpck_require__(6205); 8498 class TLogClient { 8499 constructor(options) { 8500 this.fetchOnConflict = options.fetchOnConflict ?? false; 8501 this.rekor = new rekor_1.Rekor({ 8502 baseURL: options.rekorBaseURL, 8503 retry: options.retry, 8504 timeout: options.timeout, 8505 }); 8506 } 8507 async createEntry(proposedEntry) { 8508 let entry; 8509 try { 8510 entry = await this.rekor.createEntry(proposedEntry); 8511 } 8512 catch (err) { 8513 // If the entry already exists, fetch it (if enabled) 8514 if (entryExistsError(err) && this.fetchOnConflict) { 8515 // Grab the UUID of the existing entry from the location header 8516 /* istanbul ignore next */ 8517 const uuid = err.location.split('/').pop() || ''; 8518 try { 8519 entry = await this.rekor.getEntry(uuid); 8520 } 8521 catch (err) { 8522 (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry'); 8523 } 8524 } 8525 else { 8526 (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); 8527 } 8528 } 8529 return entry; 8530 } 8531 } 8532 exports.TLogClient = TLogClient; 8533 function entryExistsError(value) { 8534 return (value instanceof error_2.HTTPError && 8535 value.statusCode === 409 && 8536 value.location !== undefined); 8537 } 8538 8539 8540 /***/ }), 8541 8542 /***/ 3776: 8543 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8544 8545 "use strict"; 8546 8547 Object.defineProperty(exports, "__esModule", ({ value: true })); 8548 exports.toProposedEntry = void 0; 8549 /* 8550 Copyright 2023 The Sigstore Authors. 8551 8552 Licensed under the Apache License, Version 2.0 (the "License"); 8553 you may not use this file except in compliance with the License. 8554 You may obtain a copy of the License at 8555 8556 http://www.apache.org/licenses/LICENSE-2.0 8557 8558 Unless required by applicable law or agreed to in writing, software 8559 distributed under the License is distributed on an "AS IS" BASIS, 8560 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8561 See the License for the specific language governing permissions and 8562 limitations under the License. 8563 */ 8564 const bundle_1 = __nccwpck_require__(9715); 8565 const util_1 = __nccwpck_require__(724); 8566 function toProposedEntry(content, publicKey, 8567 // TODO: Remove this parameter once have completely switched to 'dsse' entries 8568 entryType = 'intoto') { 8569 switch (content.$case) { 8570 case 'dsseEnvelope': 8571 // TODO: Remove this conditional once have completely switched to 'dsse' entries 8572 if (entryType === 'dsse') { 8573 return toProposedDSSEEntry(content.dsseEnvelope, publicKey); 8574 } 8575 return toProposedIntotoEntry(content.dsseEnvelope, publicKey); 8576 case 'messageSignature': 8577 return toProposedHashedRekordEntry(content.messageSignature, publicKey); 8578 } 8579 } 8580 exports.toProposedEntry = toProposedEntry; 8581 // Returns a properly formatted Rekor "hashedrekord" entry for the given digest 8582 // and signature 8583 function toProposedHashedRekordEntry(messageSignature, publicKey) { 8584 const hexDigest = messageSignature.messageDigest.digest.toString('hex'); 8585 const b64Signature = messageSignature.signature.toString('base64'); 8586 const b64Key = util_1.encoding.base64Encode(publicKey); 8587 return { 8588 apiVersion: '0.0.1', 8589 kind: 'hashedrekord', 8590 spec: { 8591 data: { 8592 hash: { 8593 algorithm: 'sha256', 8594 value: hexDigest, 8595 }, 8596 }, 8597 signature: { 8598 content: b64Signature, 8599 publicKey: { 8600 content: b64Key, 8601 }, 8602 }, 8603 }, 8604 }; 8605 } 8606 // Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope 8607 // and signature 8608 function toProposedDSSEEntry(envelope, publicKey) { 8609 const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope)); 8610 const encodedKey = util_1.encoding.base64Encode(publicKey); 8611 return { 8612 apiVersion: '0.0.1', 8613 kind: 'dsse', 8614 spec: { 8615 proposedContent: { 8616 envelope: envelopeJSON, 8617 verifiers: [encodedKey], 8618 }, 8619 }, 8620 }; 8621 } 8622 // Returns a properly formatted Rekor "intoto" entry for the given DSSE 8623 // envelope and signature 8624 function toProposedIntotoEntry(envelope, publicKey) { 8625 // Calculate the value for the payloadHash field in the Rekor entry 8626 const payloadHash = util_1.crypto.hash(envelope.payload).toString('hex'); 8627 // Calculate the value for the hash field in the Rekor entry 8628 const envelopeHash = calculateDSSEHash(envelope, publicKey); 8629 // Collect values for re-creating the DSSE envelope. 8630 // Double-encode payload and signature cause that's what Rekor expects 8631 const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64')); 8632 const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64')); 8633 const keyid = envelope.signatures[0].keyid; 8634 const encodedKey = util_1.encoding.base64Encode(publicKey); 8635 // Create the envelope portion of the entry. Note the inclusion of the 8636 // publicKey in the signature struct is not a standard part of a DSSE 8637 // envelope, but is required by Rekor. 8638 const dsse = { 8639 payloadType: envelope.payloadType, 8640 payload: payload, 8641 signatures: [{ sig, publicKey: encodedKey }], 8642 }; 8643 // If the keyid is an empty string, Rekor seems to remove it altogether. We 8644 // need to do the same here so that we can properly recreate the entry for 8645 // verification. 8646 if (keyid.length > 0) { 8647 dsse.signatures[0].keyid = keyid; 8648 } 8649 return { 8650 apiVersion: '0.0.2', 8651 kind: 'intoto', 8652 spec: { 8653 content: { 8654 envelope: dsse, 8655 hash: { algorithm: 'sha256', value: envelopeHash }, 8656 payloadHash: { algorithm: 'sha256', value: payloadHash }, 8657 }, 8658 }, 8659 }; 8660 } 8661 // Calculates the hash of a DSSE envelope for inclusion in a Rekor entry. 8662 // There is no standard way to do this, so the scheme we're using as as 8663 // follows: 8664 // * payload is base64 encoded 8665 // * signature is base64 encoded (only the first signature is used) 8666 // * keyid is included ONLY if it is NOT an empty string 8667 // * The resulting JSON is canonicalized and hashed to a hex string 8668 function calculateDSSEHash(envelope, publicKey) { 8669 const dsse = { 8670 payloadType: envelope.payloadType, 8671 payload: envelope.payload.toString('base64'), 8672 signatures: [ 8673 { sig: envelope.signatures[0].sig.toString('base64'), publicKey }, 8674 ], 8675 }; 8676 // If the keyid is an empty string, Rekor seems to remove it altogether. 8677 if (envelope.signatures[0].keyid.length > 0) { 8678 dsse.signatures[0].keyid = envelope.signatures[0].keyid; 8679 } 8680 return util_1.crypto.hash(util_1.json.canonicalize(dsse)).toString('hex'); 8681 } 8682 8683 8684 /***/ }), 8685 8686 /***/ 7843: 8687 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8688 8689 "use strict"; 8690 8691 Object.defineProperty(exports, "__esModule", ({ value: true })); 8692 exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; 8693 /* 8694 Copyright 2023 The Sigstore Authors. 8695 8696 Licensed under the Apache License, Version 2.0 (the "License"); 8697 you may not use this file except in compliance with the License. 8698 You may obtain a copy of the License at 8699 8700 http://www.apache.org/licenses/LICENSE-2.0 8701 8702 Unless required by applicable law or agreed to in writing, software 8703 distributed under the License is distributed on an "AS IS" BASIS, 8704 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8705 See the License for the specific language governing permissions and 8706 limitations under the License. 8707 */ 8708 const util_1 = __nccwpck_require__(724); 8709 const client_1 = __nccwpck_require__(6737); 8710 const entry_1 = __nccwpck_require__(3776); 8711 exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev'; 8712 class RekorWitness { 8713 constructor(options) { 8714 this.entryType = options.entryType; 8715 this.tlog = new client_1.TLogClient({ 8716 ...options, 8717 rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, 8718 }); 8719 } 8720 async testify(content, publicKey) { 8721 const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType); 8722 const entry = await this.tlog.createEntry(proposedEntry); 8723 return toTransparencyLogEntry(entry); 8724 } 8725 } 8726 exports.RekorWitness = RekorWitness; 8727 function toTransparencyLogEntry(entry) { 8728 const logID = Buffer.from(entry.logID, 'hex'); 8729 // Parse entry body so we can extract the kind and version. 8730 const bodyJSON = util_1.encoding.base64Decode(entry.body); 8731 const entryBody = JSON.parse(bodyJSON); 8732 const promise = entry?.verification?.signedEntryTimestamp 8733 ? inclusionPromise(entry.verification.signedEntryTimestamp) 8734 : undefined; 8735 const proof = entry?.verification?.inclusionProof 8736 ? inclusionProof(entry.verification.inclusionProof) 8737 : undefined; 8738 const tlogEntry = { 8739 logIndex: entry.logIndex.toString(), 8740 logId: { 8741 keyId: logID, 8742 }, 8743 integratedTime: entry.integratedTime.toString(), 8744 kindVersion: { 8745 kind: entryBody.kind, 8746 version: entryBody.apiVersion, 8747 }, 8748 inclusionPromise: promise, 8749 inclusionProof: proof, 8750 canonicalizedBody: Buffer.from(entry.body, 'base64'), 8751 }; 8752 return { 8753 tlogEntries: [tlogEntry], 8754 }; 8755 } 8756 function inclusionPromise(promise) { 8757 return { 8758 signedEntryTimestamp: Buffer.from(promise, 'base64'), 8759 }; 8760 } 8761 function inclusionProof(proof) { 8762 return { 8763 logIndex: proof.logIndex.toString(), 8764 treeSize: proof.treeSize.toString(), 8765 rootHash: Buffer.from(proof.rootHash, 'hex'), 8766 hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')), 8767 checkpoint: { 8768 envelope: proof.checkpoint, 8769 }, 8770 }; 8771 } 8772 8773 8774 /***/ }), 8775 8776 /***/ 2239: 8777 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8778 8779 "use strict"; 8780 8781 Object.defineProperty(exports, "__esModule", ({ value: true })); 8782 exports.TSAClient = void 0; 8783 /* 8784 Copyright 2023 The Sigstore Authors. 8785 8786 Licensed under the Apache License, Version 2.0 (the "License"); 8787 you may not use this file except in compliance with the License. 8788 You may obtain a copy of the License at 8789 8790 http://www.apache.org/licenses/LICENSE-2.0 8791 8792 Unless required by applicable law or agreed to in writing, software 8793 distributed under the License is distributed on an "AS IS" BASIS, 8794 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8795 See the License for the specific language governing permissions and 8796 limitations under the License. 8797 */ 8798 const error_1 = __nccwpck_require__(532); 8799 const tsa_1 = __nccwpck_require__(2759); 8800 const util_1 = __nccwpck_require__(724); 8801 class TSAClient { 8802 constructor(options) { 8803 this.tsa = new tsa_1.TimestampAuthority({ 8804 baseURL: options.tsaBaseURL, 8805 retry: options.retry, 8806 timeout: options.timeout, 8807 }); 8808 } 8809 async createTimestamp(signature) { 8810 const request = { 8811 artifactHash: util_1.crypto.hash(signature).toString('base64'), 8812 hashAlgorithm: 'sha256', 8813 }; 8814 try { 8815 return await this.tsa.createTimestamp(request); 8816 } 8817 catch (err) { 8818 (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp'); 8819 } 8820 } 8821 } 8822 exports.TSAClient = TSAClient; 8823 8824 8825 /***/ }), 8826 8827 /***/ 49: 8828 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 8829 8830 "use strict"; 8831 8832 Object.defineProperty(exports, "__esModule", ({ value: true })); 8833 exports.TSAWitness = void 0; 8834 /* 8835 Copyright 2023 The Sigstore Authors. 8836 8837 Licensed under the Apache License, Version 2.0 (the "License"); 8838 you may not use this file except in compliance with the License. 8839 You may obtain a copy of the License at 8840 8841 http://www.apache.org/licenses/LICENSE-2.0 8842 8843 Unless required by applicable law or agreed to in writing, software 8844 distributed under the License is distributed on an "AS IS" BASIS, 8845 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8846 See the License for the specific language governing permissions and 8847 limitations under the License. 8848 */ 8849 const client_1 = __nccwpck_require__(2239); 8850 class TSAWitness { 8851 constructor(options) { 8852 this.tsa = new client_1.TSAClient({ 8853 tsaBaseURL: options.tsaBaseURL, 8854 retry: options.retry, 8855 timeout: options.timeout, 8856 }); 8857 } 8858 async testify(content) { 8859 const signature = extractSignature(content); 8860 const timestamp = await this.tsa.createTimestamp(signature); 8861 return { 8862 rfc3161Timestamps: [{ signedTimestamp: timestamp }], 8863 }; 8864 } 8865 } 8866 exports.TSAWitness = TSAWitness; 8867 function extractSignature(content) { 8868 switch (content.$case) { 8869 case 'dsseEnvelope': 8870 return content.dsseEnvelope.signatures[0].sig; 8871 case 'messageSignature': 8872 return content.messageSignature.signature; 8873 } 8874 } 8875 8876 8877 /***/ }), 8878 8879 /***/ 8134: 8880 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 8881 8882 "use strict"; 8883 8884 var __importDefault = (this && this.__importDefault) || function (mod) { 8885 return (mod && mod.__esModule) ? mod : { "default": mod }; 8886 }; 8887 Object.defineProperty(exports, "__esModule", ({ value: true })); 8888 exports.appDataPath = void 0; 8889 /* 8890 Copyright 2023 The Sigstore Authors. 8891 8892 Licensed under the Apache License, Version 2.0 (the "License"); 8893 you may not use this file except in compliance with the License. 8894 You may obtain a copy of the License at 8895 8896 http://www.apache.org/licenses/LICENSE-2.0 8897 8898 Unless required by applicable law or agreed to in writing, software 8899 distributed under the License is distributed on an "AS IS" BASIS, 8900 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8901 See the License for the specific language governing permissions and 8902 limitations under the License. 8903 */ 8904 const os_1 = __importDefault(__nccwpck_require__(2037)); 8905 const path_1 = __importDefault(__nccwpck_require__(1017)); 8906 function appDataPath(name) { 8907 const homedir = os_1.default.homedir(); 8908 switch (process.platform) { 8909 /* istanbul ignore next */ 8910 case 'darwin': { 8911 const appSupport = path_1.default.join(homedir, 'Library', 'Application Support'); 8912 return path_1.default.join(appSupport, name); 8913 } 8914 /* istanbul ignore next */ 8915 case 'win32': { 8916 const localAppData = process.env.LOCALAPPDATA || path_1.default.join(homedir, 'AppData', 'Local'); 8917 return path_1.default.join(localAppData, name, 'Data'); 8918 } 8919 /* istanbul ignore next */ 8920 default: { 8921 const localData = process.env.XDG_DATA_HOME || path_1.default.join(homedir, '.local', 'share'); 8922 return path_1.default.join(localData, name); 8923 } 8924 } 8925 } 8926 exports.appDataPath = appDataPath; 8927 8928 8929 /***/ }), 8930 8931 /***/ 9687: 8932 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 8933 8934 "use strict"; 8935 8936 var __importDefault = (this && this.__importDefault) || function (mod) { 8937 return (mod && mod.__esModule) ? mod : { "default": mod }; 8938 }; 8939 Object.defineProperty(exports, "__esModule", ({ value: true })); 8940 exports.TUFClient = void 0; 8941 /* 8942 Copyright 2023 The Sigstore Authors. 8943 8944 Licensed under the Apache License, Version 2.0 (the "License"); 8945 you may not use this file except in compliance with the License. 8946 You may obtain a copy of the License at 8947 8948 http://www.apache.org/licenses/LICENSE-2.0 8949 8950 Unless required by applicable law or agreed to in writing, software 8951 distributed under the License is distributed on an "AS IS" BASIS, 8952 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8953 See the License for the specific language governing permissions and 8954 limitations under the License. 8955 */ 8956 const fs_1 = __importDefault(__nccwpck_require__(7147)); 8957 const path_1 = __importDefault(__nccwpck_require__(1017)); 8958 const tuf_js_1 = __nccwpck_require__(9475); 8959 const _1 = __nccwpck_require__(8567); 8960 const target_1 = __nccwpck_require__(1412); 8961 const TARGETS_DIR_NAME = 'targets'; 8962 class TUFClient { 8963 constructor(options) { 8964 const url = new URL(options.mirrorURL); 8965 const repoName = encodeURIComponent(url.host + url.pathname.replace(/\/$/, '')); 8966 const cachePath = path_1.default.join(options.cachePath, repoName); 8967 initTufCache(cachePath); 8968 seedCache({ 8969 cachePath, 8970 mirrorURL: options.mirrorURL, 8971 tufRootPath: options.rootPath, 8972 forceInit: options.forceInit, 8973 }); 8974 this.updater = initClient({ 8975 mirrorURL: options.mirrorURL, 8976 cachePath, 8977 forceCache: options.forceCache, 8978 retry: options.retry, 8979 timeout: options.timeout, 8980 }); 8981 } 8982 async refresh() { 8983 return this.updater.refresh(); 8984 } 8985 getTarget(targetName) { 8986 return (0, target_1.readTarget)(this.updater, targetName); 8987 } 8988 } 8989 exports.TUFClient = TUFClient; 8990 // Initializes the TUF cache directory structure including the initial 8991 // root.json file. If the cache directory does not exist, it will be 8992 // created. If the targets directory does not exist, it will be created. 8993 // If the root.json file does not exist, it will be copied from the 8994 // rootPath argument. 8995 function initTufCache(cachePath) { 8996 const targetsPath = path_1.default.join(cachePath, TARGETS_DIR_NAME); 8997 if (!fs_1.default.existsSync(cachePath)) { 8998 fs_1.default.mkdirSync(cachePath, { recursive: true }); 8999 } 9000 if (!fs_1.default.existsSync(targetsPath)) { 9001 fs_1.default.mkdirSync(targetsPath); 9002 } 9003 } 9004 // Populates the TUF cache with the initial root.json file. If the root.json 9005 // file does not exist (or we're forcing re-initialization), copy it from either 9006 // the rootPath argument or from one of the repo seeds. 9007 function seedCache({ cachePath, mirrorURL, tufRootPath, forceInit, }) { 9008 const cachedRootPath = path_1.default.join(cachePath, 'root.json'); 9009 // If the root.json file does not exist (or we're forcing re-initialization), 9010 // populate it either from the supplied rootPath or from one of the repo seeds. 9011 if (!fs_1.default.existsSync(cachedRootPath) || forceInit) { 9012 if (tufRootPath) { 9013 fs_1.default.copyFileSync(tufRootPath, cachedRootPath); 9014 } 9015 else { 9016 /* eslint-disable @typescript-eslint/no-var-requires */ 9017 const seeds = __nccwpck_require__(4998); 9018 const repoSeed = seeds[mirrorURL]; 9019 if (!repoSeed) { 9020 throw new _1.TUFError({ 9021 code: 'TUF_INIT_CACHE_ERROR', 9022 message: `No root.json found for mirror: ${mirrorURL}`, 9023 }); 9024 } 9025 fs_1.default.writeFileSync(cachedRootPath, Buffer.from(repoSeed['root.json'], 'base64')); 9026 // Copy any seed targets into the cache 9027 Object.entries(repoSeed.targets).forEach(([targetName, target]) => { 9028 fs_1.default.writeFileSync(path_1.default.join(cachePath, TARGETS_DIR_NAME, targetName), Buffer.from(target, 'base64')); 9029 }); 9030 } 9031 } 9032 } 9033 function initClient(options) { 9034 const config = { 9035 fetchTimeout: options.timeout, 9036 fetchRetry: options.retry, 9037 }; 9038 return new tuf_js_1.Updater({ 9039 metadataBaseUrl: options.mirrorURL, 9040 targetBaseUrl: `${options.mirrorURL}/targets`, 9041 metadataDir: options.cachePath, 9042 targetDir: path_1.default.join(options.cachePath, TARGETS_DIR_NAME), 9043 forceCache: options.forceCache, 9044 config, 9045 }); 9046 } 9047 9048 9049 /***/ }), 9050 9051 /***/ 8624: 9052 /***/ ((__unused_webpack_module, exports) => { 9053 9054 "use strict"; 9055 9056 Object.defineProperty(exports, "__esModule", ({ value: true })); 9057 exports.TUFError = void 0; 9058 class TUFError extends Error { 9059 constructor({ code, message, cause, }) { 9060 super(message); 9061 this.code = code; 9062 this.cause = cause; 9063 this.name = this.constructor.name; 9064 } 9065 } 9066 exports.TUFError = TUFError; 9067 9068 9069 /***/ }), 9070 9071 /***/ 8567: 9072 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9073 9074 "use strict"; 9075 9076 Object.defineProperty(exports, "__esModule", ({ value: true })); 9077 exports.TUFError = exports.initTUF = exports.getTrustedRoot = exports.DEFAULT_MIRROR_URL = void 0; 9078 /* 9079 Copyright 2023 The Sigstore Authors. 9080 9081 Licensed under the Apache License, Version 2.0 (the "License"); 9082 you may not use this file except in compliance with the License. 9083 You may obtain a copy of the License at 9084 9085 http://www.apache.org/licenses/LICENSE-2.0 9086 9087 Unless required by applicable law or agreed to in writing, software 9088 distributed under the License is distributed on an "AS IS" BASIS, 9089 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9090 See the License for the specific language governing permissions and 9091 limitations under the License. 9092 */ 9093 const protobuf_specs_1 = __nccwpck_require__(530); 9094 const appdata_1 = __nccwpck_require__(8134); 9095 const client_1 = __nccwpck_require__(9687); 9096 exports.DEFAULT_MIRROR_URL = 'https://tuf-repo-cdn.sigstore.dev'; 9097 const DEFAULT_CACHE_DIR = 'sigstore-js'; 9098 const DEFAULT_RETRY = { retries: 2 }; 9099 const DEFAULT_TIMEOUT = 5000; 9100 const TRUSTED_ROOT_TARGET = 'trusted_root.json'; 9101 async function getTrustedRoot( 9102 /* istanbul ignore next */ 9103 options = {}) { 9104 const client = createClient(options); 9105 const trustedRoot = await client.getTarget(TRUSTED_ROOT_TARGET); 9106 return protobuf_specs_1.TrustedRoot.fromJSON(JSON.parse(trustedRoot)); 9107 } 9108 exports.getTrustedRoot = getTrustedRoot; 9109 async function initTUF( 9110 /* istanbul ignore next */ 9111 options = {}) { 9112 const client = createClient(options); 9113 return client.refresh().then(() => client); 9114 } 9115 exports.initTUF = initTUF; 9116 // Create a TUF client with default options 9117 function createClient(options) { 9118 /* istanbul ignore next */ 9119 return new client_1.TUFClient({ 9120 cachePath: options.cachePath || (0, appdata_1.appDataPath)(DEFAULT_CACHE_DIR), 9121 rootPath: options.rootPath, 9122 mirrorURL: options.mirrorURL || exports.DEFAULT_MIRROR_URL, 9123 retry: options.retry ?? DEFAULT_RETRY, 9124 timeout: options.timeout ?? DEFAULT_TIMEOUT, 9125 forceCache: options.forceCache ?? false, 9126 forceInit: options.forceInit ?? options.force ?? false, 9127 }); 9128 } 9129 var error_1 = __nccwpck_require__(8624); 9130 Object.defineProperty(exports, "TUFError", ({ enumerable: true, get: function () { return error_1.TUFError; } })); 9131 9132 9133 /***/ }), 9134 9135 /***/ 1412: 9136 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 9137 9138 "use strict"; 9139 9140 var __importDefault = (this && this.__importDefault) || function (mod) { 9141 return (mod && mod.__esModule) ? mod : { "default": mod }; 9142 }; 9143 Object.defineProperty(exports, "__esModule", ({ value: true })); 9144 exports.readTarget = void 0; 9145 /* 9146 Copyright 2023 The Sigstore Authors. 9147 9148 Licensed under the Apache License, Version 2.0 (the "License"); 9149 you may not use this file except in compliance with the License. 9150 You may obtain a copy of the License at 9151 9152 http://www.apache.org/licenses/LICENSE-2.0 9153 9154 Unless required by applicable law or agreed to in writing, software 9155 distributed under the License is distributed on an "AS IS" BASIS, 9156 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9157 See the License for the specific language governing permissions and 9158 limitations under the License. 9159 */ 9160 const fs_1 = __importDefault(__nccwpck_require__(7147)); 9161 const error_1 = __nccwpck_require__(8624); 9162 // Downloads and returns the specified target from the provided TUF Updater. 9163 async function readTarget(tuf, targetPath) { 9164 const path = await getTargetPath(tuf, targetPath); 9165 return new Promise((resolve, reject) => { 9166 fs_1.default.readFile(path, 'utf-8', (err, data) => { 9167 if (err) { 9168 reject(new error_1.TUFError({ 9169 code: 'TUF_READ_TARGET_ERROR', 9170 message: `error reading target ${path}`, 9171 cause: err, 9172 })); 9173 } 9174 else { 9175 resolve(data); 9176 } 9177 }); 9178 }); 9179 } 9180 exports.readTarget = readTarget; 9181 // Returns the local path to the specified target. If the target is not yet 9182 // cached locally, the provided TUF Updater will be used to download and 9183 // cache the target. 9184 async function getTargetPath(tuf, target) { 9185 let targetInfo; 9186 try { 9187 targetInfo = await tuf.getTargetInfo(target); 9188 } 9189 catch (err) { 9190 throw new error_1.TUFError({ 9191 code: 'TUF_REFRESH_METADATA_ERROR', 9192 message: 'error refreshing TUF metadata', 9193 cause: err, 9194 }); 9195 } 9196 if (!targetInfo) { 9197 throw new error_1.TUFError({ 9198 code: 'TUF_FIND_TARGET_ERROR', 9199 message: `target ${target} not found`, 9200 }); 9201 } 9202 let path = await tuf.findCachedTarget(targetInfo); 9203 // An empty path here means the target has not been cached locally, or is 9204 // out of date. In either case, we need to download it. 9205 if (!path) { 9206 try { 9207 path = await tuf.downloadTarget(targetInfo); 9208 } 9209 catch (err) { 9210 throw new error_1.TUFError({ 9211 code: 'TUF_DOWNLOAD_TARGET_ERROR', 9212 message: `error downloading target ${path}`, 9213 cause: err, 9214 }); 9215 } 9216 } 9217 return path; 9218 } 9219 9220 9221 /***/ }), 9222 9223 /***/ 4542: 9224 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9225 9226 "use strict"; 9227 9228 Object.defineProperty(exports, "__esModule", ({ value: true })); 9229 exports.DSSESignatureContent = void 0; 9230 /* 9231 Copyright 2023 The Sigstore Authors. 9232 9233 Licensed under the Apache License, Version 2.0 (the "License"); 9234 you may not use this file except in compliance with the License. 9235 You may obtain a copy of the License at 9236 9237 http://www.apache.org/licenses/LICENSE-2.0 9238 9239 Unless required by applicable law or agreed to in writing, software 9240 distributed under the License is distributed on an "AS IS" BASIS, 9241 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9242 See the License for the specific language governing permissions and 9243 limitations under the License. 9244 */ 9245 const core_1 = __nccwpck_require__(3352); 9246 class DSSESignatureContent { 9247 constructor(env) { 9248 this.env = env; 9249 } 9250 compareDigest(digest) { 9251 return core_1.crypto.bufferEqual(digest, core_1.crypto.hash(this.env.payload)); 9252 } 9253 compareSignature(signature) { 9254 return core_1.crypto.bufferEqual(signature, this.signature); 9255 } 9256 verifySignature(key) { 9257 return core_1.crypto.verify(this.preAuthEncoding, key, this.signature); 9258 } 9259 get signature() { 9260 return this.env.signatures.length > 0 9261 ? this.env.signatures[0].sig 9262 : Buffer.from(''); 9263 } 9264 // DSSE Pre-Authentication Encoding 9265 get preAuthEncoding() { 9266 return core_1.dsse.preAuthEncoding(this.env.payloadType, this.env.payload); 9267 } 9268 } 9269 exports.DSSESignatureContent = DSSESignatureContent; 9270 9271 9272 /***/ }), 9273 9274 /***/ 9045: 9275 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9276 9277 "use strict"; 9278 9279 Object.defineProperty(exports, "__esModule", ({ value: true })); 9280 exports.signatureContent = exports.toSignedEntity = void 0; 9281 const core_1 = __nccwpck_require__(3352); 9282 const dsse_1 = __nccwpck_require__(4542); 9283 const message_1 = __nccwpck_require__(6843); 9284 function toSignedEntity(bundle, artifact) { 9285 const { tlogEntries, timestampVerificationData } = bundle.verificationMaterial; 9286 const timestamps = []; 9287 for (const entry of tlogEntries) { 9288 timestamps.push({ 9289 $case: 'transparency-log', 9290 tlogEntry: entry, 9291 }); 9292 } 9293 for (const ts of timestampVerificationData?.rfc3161Timestamps ?? []) { 9294 timestamps.push({ 9295 $case: 'timestamp-authority', 9296 timestamp: core_1.RFC3161Timestamp.parse(ts.signedTimestamp), 9297 }); 9298 } 9299 return { 9300 signature: signatureContent(bundle, artifact), 9301 key: key(bundle), 9302 tlogEntries, 9303 timestamps, 9304 }; 9305 } 9306 exports.toSignedEntity = toSignedEntity; 9307 function signatureContent(bundle, artifact) { 9308 switch (bundle.content.$case) { 9309 case 'dsseEnvelope': 9310 return new dsse_1.DSSESignatureContent(bundle.content.dsseEnvelope); 9311 case 'messageSignature': 9312 return new message_1.MessageSignatureContent(bundle.content.messageSignature, artifact); 9313 } 9314 } 9315 exports.signatureContent = signatureContent; 9316 function key(bundle) { 9317 switch (bundle.verificationMaterial.content.$case) { 9318 case 'publicKey': 9319 return { 9320 $case: 'public-key', 9321 hint: bundle.verificationMaterial.content.publicKey.hint, 9322 }; 9323 case 'x509CertificateChain': 9324 return { 9325 $case: 'certificate', 9326 certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.x509CertificateChain 9327 .certificates[0].rawBytes), 9328 }; 9329 case 'certificate': 9330 return { 9331 $case: 'certificate', 9332 certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.certificate.rawBytes), 9333 }; 9334 } 9335 } 9336 9337 9338 /***/ }), 9339 9340 /***/ 6843: 9341 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9342 9343 "use strict"; 9344 9345 Object.defineProperty(exports, "__esModule", ({ value: true })); 9346 exports.MessageSignatureContent = void 0; 9347 /* 9348 Copyright 2023 The Sigstore Authors. 9349 9350 Licensed under the Apache License, Version 2.0 (the "License"); 9351 you may not use this file except in compliance with the License. 9352 You may obtain a copy of the License at 9353 9354 http://www.apache.org/licenses/LICENSE-2.0 9355 9356 Unless required by applicable law or agreed to in writing, software 9357 distributed under the License is distributed on an "AS IS" BASIS, 9358 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9359 See the License for the specific language governing permissions and 9360 limitations under the License. 9361 */ 9362 const core_1 = __nccwpck_require__(3352); 9363 class MessageSignatureContent { 9364 constructor(messageSignature, artifact) { 9365 this.signature = messageSignature.signature; 9366 this.messageDigest = messageSignature.messageDigest.digest; 9367 this.artifact = artifact; 9368 } 9369 compareSignature(signature) { 9370 return core_1.crypto.bufferEqual(signature, this.signature); 9371 } 9372 compareDigest(digest) { 9373 return core_1.crypto.bufferEqual(digest, this.messageDigest); 9374 } 9375 verifySignature(key) { 9376 return core_1.crypto.verify(this.artifact, key, this.signature); 9377 } 9378 } 9379 exports.MessageSignatureContent = MessageSignatureContent; 9380 9381 9382 /***/ }), 9383 9384 /***/ 8948: 9385 /***/ ((__unused_webpack_module, exports) => { 9386 9387 "use strict"; 9388 9389 Object.defineProperty(exports, "__esModule", ({ value: true })); 9390 exports.PolicyError = exports.VerificationError = void 0; 9391 /* 9392 Copyright 2023 The Sigstore Authors. 9393 9394 Licensed under the Apache License, Version 2.0 (the "License"); 9395 you may not use this file except in compliance with the License. 9396 You may obtain a copy of the License at 9397 9398 http://www.apache.org/licenses/LICENSE-2.0 9399 9400 Unless required by applicable law or agreed to in writing, software 9401 distributed under the License is distributed on an "AS IS" BASIS, 9402 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9403 See the License for the specific language governing permissions and 9404 limitations under the License. 9405 */ 9406 class BaseError extends Error { 9407 constructor({ code, message, cause, }) { 9408 super(message); 9409 this.code = code; 9410 this.cause = cause; 9411 this.name = this.constructor.name; 9412 } 9413 } 9414 class VerificationError extends BaseError { 9415 } 9416 exports.VerificationError = VerificationError; 9417 class PolicyError extends BaseError { 9418 } 9419 exports.PolicyError = PolicyError; 9420 9421 9422 /***/ }), 9423 9424 /***/ 666: 9425 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9426 9427 "use strict"; 9428 9429 Object.defineProperty(exports, "__esModule", ({ value: true })); 9430 exports.Verifier = exports.toTrustMaterial = exports.VerificationError = exports.PolicyError = exports.toSignedEntity = void 0; 9431 /* istanbul ignore file */ 9432 /* 9433 Copyright 2023 The Sigstore Authors. 9434 9435 Licensed under the Apache License, Version 2.0 (the "License"); 9436 you may not use this file except in compliance with the License. 9437 You may obtain a copy of the License at 9438 9439 http://www.apache.org/licenses/LICENSE-2.0 9440 9441 Unless required by applicable law or agreed to in writing, software 9442 distributed under the License is distributed on an "AS IS" BASIS, 9443 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9444 See the License for the specific language governing permissions and 9445 limitations under the License. 9446 */ 9447 var bundle_1 = __nccwpck_require__(9045); 9448 Object.defineProperty(exports, "toSignedEntity", ({ enumerable: true, get: function () { return bundle_1.toSignedEntity; } })); 9449 var error_1 = __nccwpck_require__(8948); 9450 Object.defineProperty(exports, "PolicyError", ({ enumerable: true, get: function () { return error_1.PolicyError; } })); 9451 Object.defineProperty(exports, "VerificationError", ({ enumerable: true, get: function () { return error_1.VerificationError; } })); 9452 var trust_1 = __nccwpck_require__(4503); 9453 Object.defineProperty(exports, "toTrustMaterial", ({ enumerable: true, get: function () { return trust_1.toTrustMaterial; } })); 9454 var verifier_1 = __nccwpck_require__(5456); 9455 Object.defineProperty(exports, "Verifier", ({ enumerable: true, get: function () { return verifier_1.Verifier; } })); 9456 9457 9458 /***/ }), 9459 9460 /***/ 8766: 9461 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9462 9463 "use strict"; 9464 9465 Object.defineProperty(exports, "__esModule", ({ value: true })); 9466 exports.CertificateChainVerifier = exports.verifyCertificateChain = void 0; 9467 const error_1 = __nccwpck_require__(8948); 9468 const trust_1 = __nccwpck_require__(4503); 9469 function verifyCertificateChain(leaf, certificateAuthorities) { 9470 // Filter list of trusted CAs to those which are valid for the given 9471 // leaf certificate. 9472 const cas = (0, trust_1.filterCertAuthorities)(certificateAuthorities, { 9473 start: leaf.notBefore, 9474 end: leaf.notAfter, 9475 }); 9476 /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ 9477 let error; 9478 for (const ca of cas) { 9479 try { 9480 const verifier = new CertificateChainVerifier({ 9481 trustedCerts: ca.certChain, 9482 untrustedCert: leaf, 9483 }); 9484 return verifier.verify(); 9485 } 9486 catch (err) { 9487 error = err; 9488 } 9489 } 9490 // If we failed to verify the certificate chain for all of the trusted 9491 // CAs, throw the last error we encountered. 9492 throw new error_1.VerificationError({ 9493 code: 'CERTIFICATE_ERROR', 9494 message: 'Failed to verify certificate chain', 9495 cause: error, 9496 }); 9497 } 9498 exports.verifyCertificateChain = verifyCertificateChain; 9499 class CertificateChainVerifier { 9500 constructor(opts) { 9501 this.untrustedCert = opts.untrustedCert; 9502 this.trustedCerts = opts.trustedCerts; 9503 this.localCerts = dedupeCertificates([ 9504 ...opts.trustedCerts, 9505 opts.untrustedCert, 9506 ]); 9507 } 9508 verify() { 9509 // Construct certificate path from leaf to root 9510 const certificatePath = this.sort(); 9511 // Perform validation checks on each certificate in the path 9512 this.checkPath(certificatePath); 9513 // Return verified certificate path 9514 return certificatePath; 9515 } 9516 sort() { 9517 const leafCert = this.untrustedCert; 9518 // Construct all possible paths from the leaf 9519 let paths = this.buildPaths(leafCert); 9520 // Filter for paths which contain a trusted certificate 9521 paths = paths.filter((path) => path.some((cert) => this.trustedCerts.includes(cert))); 9522 if (paths.length === 0) { 9523 throw new error_1.VerificationError({ 9524 code: 'CERTIFICATE_ERROR', 9525 message: 'no trusted certificate path found', 9526 }); 9527 } 9528 // Find the shortest of possible paths 9529 /* istanbul ignore next */ 9530 const path = paths.reduce((prev, curr) => prev.length < curr.length ? prev : curr); 9531 // Construct chain from shortest path 9532 // Removes the last certificate in the path, which will be a second copy 9533 // of the root certificate given that the root is self-signed. 9534 return [leafCert, ...path].slice(0, -1); 9535 } 9536 // Recursively build all possible paths from the leaf to the root 9537 buildPaths(certificate) { 9538 const paths = []; 9539 const issuers = this.findIssuer(certificate); 9540 if (issuers.length === 0) { 9541 throw new error_1.VerificationError({ 9542 code: 'CERTIFICATE_ERROR', 9543 message: 'no valid certificate path found', 9544 }); 9545 } 9546 for (let i = 0; i < issuers.length; i++) { 9547 const issuer = issuers[i]; 9548 // Base case - issuer is self 9549 if (issuer.equals(certificate)) { 9550 paths.push([certificate]); 9551 continue; 9552 } 9553 // Recursively build path for the issuer 9554 const subPaths = this.buildPaths(issuer); 9555 // Construct paths by appending the issuer to each subpath 9556 for (let j = 0; j < subPaths.length; j++) { 9557 paths.push([issuer, ...subPaths[j]]); 9558 } 9559 } 9560 return paths; 9561 } 9562 // Return all possible issuers for the given certificate 9563 findIssuer(certificate) { 9564 let issuers = []; 9565 let keyIdentifier; 9566 // Exit early if the certificate is self-signed 9567 if (certificate.subject.equals(certificate.issuer)) { 9568 if (certificate.verify()) { 9569 return [certificate]; 9570 } 9571 } 9572 // If the certificate has an authority key identifier, use that 9573 // to find the issuer 9574 if (certificate.extAuthorityKeyID) { 9575 keyIdentifier = certificate.extAuthorityKeyID.keyIdentifier; 9576 // TODO: Add support for authorityCertIssuer/authorityCertSerialNumber 9577 // though Fulcio doesn't appear to use these 9578 } 9579 // Find possible issuers by comparing the authorityKeyID/subjectKeyID 9580 // or issuer/subject. Potential issuers are added to the result array. 9581 this.localCerts.forEach((possibleIssuer) => { 9582 if (keyIdentifier) { 9583 if (possibleIssuer.extSubjectKeyID) { 9584 if (possibleIssuer.extSubjectKeyID.keyIdentifier.equals(keyIdentifier)) { 9585 issuers.push(possibleIssuer); 9586 } 9587 return; 9588 } 9589 } 9590 // Fallback to comparing certificate issuer and subject if 9591 // subjectKey/authorityKey extensions are not present 9592 if (possibleIssuer.subject.equals(certificate.issuer)) { 9593 issuers.push(possibleIssuer); 9594 } 9595 }); 9596 // Remove any issuers which fail to verify the certificate 9597 issuers = issuers.filter((issuer) => { 9598 try { 9599 return certificate.verify(issuer); 9600 } 9601 catch (ex) { 9602 /* istanbul ignore next - should never error */ 9603 return false; 9604 } 9605 }); 9606 return issuers; 9607 } 9608 checkPath(path) { 9609 /* istanbul ignore if */ 9610 if (path.length < 1) { 9611 throw new error_1.VerificationError({ 9612 code: 'CERTIFICATE_ERROR', 9613 message: 'certificate chain must contain at least one certificate', 9614 }); 9615 } 9616 // Ensure that all certificates beyond the leaf are CAs 9617 const validCAs = path.slice(1).every((cert) => cert.isCA); 9618 if (!validCAs) { 9619 throw new error_1.VerificationError({ 9620 code: 'CERTIFICATE_ERROR', 9621 message: 'intermediate certificate is not a CA', 9622 }); 9623 } 9624 // Certificate's issuer must match the subject of the next certificate 9625 // in the chain 9626 for (let i = path.length - 2; i >= 0; i--) { 9627 /* istanbul ignore if */ 9628 if (!path[i].issuer.equals(path[i + 1].subject)) { 9629 throw new error_1.VerificationError({ 9630 code: 'CERTIFICATE_ERROR', 9631 message: 'incorrect certificate name chaining', 9632 }); 9633 } 9634 } 9635 // Check pathlength constraints 9636 for (let i = 0; i < path.length; i++) { 9637 const cert = path[i]; 9638 // If the certificate is a CA, check the path length 9639 if (cert.extBasicConstraints?.isCA) { 9640 const pathLength = cert.extBasicConstraints.pathLenConstraint; 9641 // The path length, if set, indicates how many intermediate 9642 // certificates (NOT including the leaf) are allowed to follow. The 9643 // pathLength constraint of any intermediate CA certificate MUST be 9644 // greater than or equal to it's own depth in the chain (with an 9645 // adjustment for the leaf certificate) 9646 if (pathLength !== undefined && pathLength < i - 1) { 9647 throw new error_1.VerificationError({ 9648 code: 'CERTIFICATE_ERROR', 9649 message: 'path length constraint exceeded', 9650 }); 9651 } 9652 } 9653 } 9654 } 9655 } 9656 exports.CertificateChainVerifier = CertificateChainVerifier; 9657 // Remove duplicate certificates from the array 9658 function dedupeCertificates(certs) { 9659 for (let i = 0; i < certs.length; i++) { 9660 for (let j = i + 1; j < certs.length; j++) { 9661 if (certs[i].equals(certs[j])) { 9662 certs.splice(j, 1); 9663 j--; 9664 } 9665 } 9666 } 9667 return certs; 9668 } 9669 9670 9671 /***/ }), 9672 9673 /***/ 6829: 9674 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9675 9676 "use strict"; 9677 9678 Object.defineProperty(exports, "__esModule", ({ value: true })); 9679 exports.verifyCertificate = exports.verifyPublicKey = void 0; 9680 /* 9681 Copyright 2023 The Sigstore Authors. 9682 9683 Licensed under the Apache License, Version 2.0 (the "License"); 9684 you may not use this file except in compliance with the License. 9685 You may obtain a copy of the License at 9686 9687 http://www.apache.org/licenses/LICENSE-2.0 9688 9689 Unless required by applicable law or agreed to in writing, software 9690 distributed under the License is distributed on an "AS IS" BASIS, 9691 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9692 See the License for the specific language governing permissions and 9693 limitations under the License. 9694 */ 9695 const core_1 = __nccwpck_require__(3352); 9696 const error_1 = __nccwpck_require__(8948); 9697 const certificate_1 = __nccwpck_require__(8766); 9698 const sct_1 = __nccwpck_require__(8669); 9699 const OID_FULCIO_ISSUER_V1 = '1.3.6.1.4.1.57264.1.1'; 9700 const OID_FULCIO_ISSUER_V2 = '1.3.6.1.4.1.57264.1.8'; 9701 function verifyPublicKey(hint, timestamps, trustMaterial) { 9702 const key = trustMaterial.publicKey(hint); 9703 timestamps.forEach((timestamp) => { 9704 if (!key.validFor(timestamp)) { 9705 throw new error_1.VerificationError({ 9706 code: 'PUBLIC_KEY_ERROR', 9707 message: `Public key is not valid for timestamp: ${timestamp.toISOString()}`, 9708 }); 9709 } 9710 }); 9711 return { key: key.publicKey }; 9712 } 9713 exports.verifyPublicKey = verifyPublicKey; 9714 function verifyCertificate(leaf, timestamps, trustMaterial) { 9715 // Check that leaf certificate chains to a trusted CA 9716 const path = (0, certificate_1.verifyCertificateChain)(leaf, trustMaterial.certificateAuthorities); 9717 // Check that ALL certificates are valid for ALL of the timestamps 9718 const validForDate = timestamps.every((timestamp) => path.every((cert) => cert.validForDate(timestamp))); 9719 if (!validForDate) { 9720 throw new error_1.VerificationError({ 9721 code: 'CERTIFICATE_ERROR', 9722 message: 'certificate is not valid or expired at the specified date', 9723 }); 9724 } 9725 return { 9726 scts: (0, sct_1.verifySCTs)(path[0], path[1], trustMaterial.ctlogs), 9727 signer: getSigner(path[0]), 9728 }; 9729 } 9730 exports.verifyCertificate = verifyCertificate; 9731 function getSigner(cert) { 9732 let issuer; 9733 const issuerExtension = cert.extension(OID_FULCIO_ISSUER_V2); 9734 if (issuerExtension) { 9735 issuer = issuerExtension.valueObj.subs?.[0]?.value.toString('ascii'); 9736 } 9737 else { 9738 issuer = cert.extension(OID_FULCIO_ISSUER_V1)?.value.toString('ascii'); 9739 } 9740 const identity = { 9741 extensions: { issuer }, 9742 subjectAlternativeName: cert.subjectAltName, 9743 }; 9744 return { 9745 key: core_1.crypto.createPublicKey(cert.publicKey), 9746 identity, 9747 }; 9748 } 9749 9750 9751 /***/ }), 9752 9753 /***/ 8669: 9754 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9755 9756 "use strict"; 9757 9758 Object.defineProperty(exports, "__esModule", ({ value: true })); 9759 exports.verifySCTs = void 0; 9760 /* 9761 Copyright 2023 The Sigstore Authors. 9762 9763 Licensed under the Apache License, Version 2.0 (the "License"); 9764 you may not use this file except in compliance with the License. 9765 You may obtain a copy of the License at 9766 9767 http://www.apache.org/licenses/LICENSE-2.0 9768 9769 Unless required by applicable law or agreed to in writing, software 9770 distributed under the License is distributed on an "AS IS" BASIS, 9771 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9772 See the License for the specific language governing permissions and 9773 limitations under the License. 9774 */ 9775 const core_1 = __nccwpck_require__(3352); 9776 const error_1 = __nccwpck_require__(8948); 9777 const trust_1 = __nccwpck_require__(4503); 9778 function verifySCTs(cert, issuer, ctlogs) { 9779 let extSCT; 9780 // Verifying the SCT requires that we remove the SCT extension and 9781 // re-encode the TBS structure to DER -- this value is part of the data 9782 // over which the signature is calculated. Since this is a destructive action 9783 // we create a copy of the certificate so we can remove the SCT extension 9784 // without affecting the original certificate. 9785 const clone = cert.clone(); 9786 // Intentionally not using the findExtension method here because we want to 9787 // remove the the SCT extension from the certificate before calculating the 9788 // PreCert structure 9789 for (let i = 0; i < clone.extensions.length; i++) { 9790 const ext = clone.extensions[i]; 9791 if (ext.subs[0].toOID() === core_1.EXTENSION_OID_SCT) { 9792 extSCT = new core_1.X509SCTExtension(ext); 9793 // Remove the extension from the certificate 9794 clone.extensions.splice(i, 1); 9795 break; 9796 } 9797 } 9798 // No SCT extension found to verify 9799 if (!extSCT) { 9800 return []; 9801 } 9802 // Found an SCT extension but it has no SCTs 9803 /* istanbul ignore if -- too difficult to fabricate test case for this */ 9804 if (extSCT.signedCertificateTimestamps.length === 0) { 9805 return []; 9806 } 9807 // Construct the PreCert structure 9808 // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 9809 const preCert = new core_1.ByteStream(); 9810 // Calculate hash of the issuer's public key 9811 const issuerId = core_1.crypto.hash(issuer.publicKey); 9812 preCert.appendView(issuerId); 9813 // Re-encodes the certificate to DER after removing the SCT extension 9814 const tbs = clone.tbsCertificate.toDER(); 9815 preCert.appendUint24(tbs.length); 9816 preCert.appendView(tbs); 9817 // Calculate and return the verification results for each SCT 9818 return extSCT.signedCertificateTimestamps.map((sct) => { 9819 // Find the ctlog instance that corresponds to the SCT's logID 9820 const validCTLogs = (0, trust_1.filterTLogAuthorities)(ctlogs, { 9821 logID: sct.logID, 9822 targetDate: sct.datetime, 9823 }); 9824 // See if the SCT is valid for any of the CT logs 9825 const verified = validCTLogs.some((log) => sct.verify(preCert.buffer, log.publicKey)); 9826 if (!verified) { 9827 throw new error_1.VerificationError({ 9828 code: 'CERTIFICATE_ERROR', 9829 message: 'SCT verification failed', 9830 }); 9831 } 9832 return sct.logID; 9833 }); 9834 } 9835 exports.verifySCTs = verifySCTs; 9836 9837 9838 /***/ }), 9839 9840 /***/ 3978: 9841 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9842 9843 "use strict"; 9844 9845 Object.defineProperty(exports, "__esModule", ({ value: true })); 9846 exports.verifyExtensions = exports.verifySubjectAlternativeName = void 0; 9847 const error_1 = __nccwpck_require__(8948); 9848 function verifySubjectAlternativeName(policyIdentity, signerIdentity) { 9849 if (signerIdentity === undefined || !signerIdentity.match(policyIdentity)) { 9850 throw new error_1.PolicyError({ 9851 code: 'UNTRUSTED_SIGNER_ERROR', 9852 message: `certificate identity error - expected ${policyIdentity}, got ${signerIdentity}`, 9853 }); 9854 } 9855 } 9856 exports.verifySubjectAlternativeName = verifySubjectAlternativeName; 9857 function verifyExtensions(policyExtensions, signerExtensions = {}) { 9858 let key; 9859 for (key in policyExtensions) { 9860 if (signerExtensions[key] !== policyExtensions[key]) { 9861 throw new error_1.PolicyError({ 9862 code: 'UNTRUSTED_SIGNER_ERROR', 9863 message: `invalid certificate extension - expected ${key}=${policyExtensions[key]}, got ${key}=${signerExtensions[key]}`, 9864 }); 9865 } 9866 } 9867 } 9868 exports.verifyExtensions = verifyExtensions; 9869 9870 9871 /***/ }), 9872 9873 /***/ 6896: 9874 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 9875 9876 "use strict"; 9877 9878 Object.defineProperty(exports, "__esModule", ({ value: true })); 9879 exports.verifyCheckpoint = void 0; 9880 /* 9881 Copyright 2023 The Sigstore Authors. 9882 9883 Licensed under the Apache License, Version 2.0 (the "License"); 9884 you may not use this file except in compliance with the License. 9885 You may obtain a copy of the License at 9886 9887 http://www.apache.org/licenses/LICENSE-2.0 9888 9889 Unless required by applicable law or agreed to in writing, software 9890 distributed under the License is distributed on an "AS IS" BASIS, 9891 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9892 See the License for the specific language governing permissions and 9893 limitations under the License. 9894 */ 9895 const core_1 = __nccwpck_require__(3352); 9896 const error_1 = __nccwpck_require__(8948); 9897 const trust_1 = __nccwpck_require__(4503); 9898 // Separator between the note and the signatures in a checkpoint 9899 const CHECKPOINT_SEPARATOR = '\n\n'; 9900 // Checkpoint signatures are of the following form: 9901 // "– <identity> <key_hint+signature_bytes>\n" 9902 // where: 9903 // - the prefix is an emdash (U+2014). 9904 // - <identity> gives a human-readable representation of the signing ID. 9905 // - <key_hint+signature_bytes> is the first 4 bytes of the SHA256 hash of the 9906 // associated public key followed by the signature bytes. 9907 const SIGNATURE_REGEX = /\u2014 (\S+) (\S+)\n/g; 9908 // Verifies the checkpoint value in the given tlog entry. There are two steps 9909 // to the verification: 9910 // 1. Verify that all signatures in the checkpoint can be verified against a 9911 // trusted public key 9912 // 2. Verify that the root hash in the checkpoint matches the root hash in the 9913 // inclusion proof 9914 // See: https://github.com/transparency-dev/formats/blob/main/log/README.md 9915 function verifyCheckpoint(entry, tlogs) { 9916 // Filter tlog instances to just those which were valid at the time of the 9917 // entry 9918 const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, { 9919 targetDate: new Date(Number(entry.integratedTime) * 1000), 9920 }); 9921 const inclusionProof = entry.inclusionProof; 9922 const signedNote = SignedNote.fromString(inclusionProof.checkpoint.envelope); 9923 const checkpoint = LogCheckpoint.fromString(signedNote.note); 9924 // Verify that the signatures in the checkpoint are all valid 9925 if (!verifySignedNote(signedNote, validTLogs)) { 9926 throw new error_1.VerificationError({ 9927 code: 'TLOG_INCLUSION_PROOF_ERROR', 9928 message: 'invalid checkpoint signature', 9929 }); 9930 } 9931 // Verify that the root hash from the checkpoint matches the root hash in the 9932 // inclusion proof 9933 if (!core_1.crypto.bufferEqual(checkpoint.logHash, inclusionProof.rootHash)) { 9934 throw new error_1.VerificationError({ 9935 code: 'TLOG_INCLUSION_PROOF_ERROR', 9936 message: 'root hash mismatch', 9937 }); 9938 } 9939 } 9940 exports.verifyCheckpoint = verifyCheckpoint; 9941 // Verifies the signatures in the SignedNote. For each signature, the 9942 // corresponding transparency log is looked up by the key hint and the 9943 // signature is verified against the public key in the transparency log. 9944 // Throws an error if any of the signatures are invalid. 9945 function verifySignedNote(signedNote, tlogs) { 9946 const data = Buffer.from(signedNote.note, 'utf-8'); 9947 return signedNote.signatures.every((signature) => { 9948 // Find the transparency log instance with the matching key hint 9949 const tlog = tlogs.find((tlog) => core_1.crypto.bufferEqual(tlog.logID.subarray(0, 4), signature.keyHint)); 9950 if (!tlog) { 9951 return false; 9952 } 9953 return core_1.crypto.verify(data, tlog.publicKey, signature.signature); 9954 }); 9955 } 9956 // SignedNote represents a signed note from a transparency log checkpoint. Consists 9957 // of a body (or note) and one more signatures calculated over the body. See 9958 // https://github.com/transparency-dev/formats/blob/main/log/README.md#signed-envelope 9959 class SignedNote { 9960 constructor(note, signatures) { 9961 this.note = note; 9962 this.signatures = signatures; 9963 } 9964 // Deserialize a SignedNote from a string 9965 static fromString(envelope) { 9966 if (!envelope.includes(CHECKPOINT_SEPARATOR)) { 9967 throw new error_1.VerificationError({ 9968 code: 'TLOG_INCLUSION_PROOF_ERROR', 9969 message: 'missing checkpoint separator', 9970 }); 9971 } 9972 // Split the note into the header and the data portions at the separator 9973 const split = envelope.indexOf(CHECKPOINT_SEPARATOR); 9974 const header = envelope.slice(0, split + 1); 9975 const data = envelope.slice(split + CHECKPOINT_SEPARATOR.length); 9976 // Find all the signature lines in the data portion 9977 const matches = data.matchAll(SIGNATURE_REGEX); 9978 // Parse each of the matched signature lines into the name and signature. 9979 // The first four bytes of the signature are the key hint (should match the 9980 // first four bytes of the log ID), and the rest is the signature itself. 9981 const signatures = Array.from(matches, (match) => { 9982 const [, name, signature] = match; 9983 const sigBytes = Buffer.from(signature, 'base64'); 9984 if (sigBytes.length < 5) { 9985 throw new error_1.VerificationError({ 9986 code: 'TLOG_INCLUSION_PROOF_ERROR', 9987 message: 'malformed checkpoint signature', 9988 }); 9989 } 9990 return { 9991 name, 9992 keyHint: sigBytes.subarray(0, 4), 9993 signature: sigBytes.subarray(4), 9994 }; 9995 }); 9996 if (signatures.length === 0) { 9997 throw new error_1.VerificationError({ 9998 code: 'TLOG_INCLUSION_PROOF_ERROR', 9999 message: 'no signatures found in checkpoint', 10000 }); 10001 } 10002 return new SignedNote(header, signatures); 10003 } 10004 } 10005 // LogCheckpoint represents a transparency log checkpoint. Consists of the 10006 // following: 10007 // - origin: the name of the transparency log 10008 // - logSize: the size of the log at the time of the checkpoint 10009 // - logHash: the root hash of the log at the time of the checkpoint 10010 // - rest: the rest of the checkpoint body, which is a list of log entries 10011 // See: 10012 // https://github.com/transparency-dev/formats/blob/main/log/README.md#checkpoint-body 10013 class LogCheckpoint { 10014 constructor(origin, logSize, logHash, rest) { 10015 this.origin = origin; 10016 this.logSize = logSize; 10017 this.logHash = logHash; 10018 this.rest = rest; 10019 } 10020 static fromString(note) { 10021 const lines = note.trimEnd().split('\n'); 10022 if (lines.length < 3) { 10023 throw new error_1.VerificationError({ 10024 code: 'TLOG_INCLUSION_PROOF_ERROR', 10025 message: 'too few lines in checkpoint header', 10026 }); 10027 } 10028 const origin = lines[0]; 10029 const logSize = BigInt(lines[1]); 10030 const rootHash = Buffer.from(lines[2], 'base64'); 10031 const rest = lines.slice(3); 10032 return new LogCheckpoint(origin, logSize, rootHash, rest); 10033 } 10034 } 10035 10036 10037 /***/ }), 10038 10039 /***/ 9511: 10040 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10041 10042 "use strict"; 10043 10044 Object.defineProperty(exports, "__esModule", ({ value: true })); 10045 exports.verifyTLogTimestamp = exports.verifyTSATimestamp = void 0; 10046 const error_1 = __nccwpck_require__(8948); 10047 const checkpoint_1 = __nccwpck_require__(6896); 10048 const merkle_1 = __nccwpck_require__(1407); 10049 const set_1 = __nccwpck_require__(7527); 10050 const tsa_1 = __nccwpck_require__(2574); 10051 function verifyTSATimestamp(timestamp, data, timestampAuthorities) { 10052 (0, tsa_1.verifyRFC3161Timestamp)(timestamp, data, timestampAuthorities); 10053 return { 10054 type: 'timestamp-authority', 10055 logID: timestamp.signerSerialNumber, 10056 timestamp: timestamp.signingTime, 10057 }; 10058 } 10059 exports.verifyTSATimestamp = verifyTSATimestamp; 10060 function verifyTLogTimestamp(entry, tlogAuthorities) { 10061 let inclusionVerified = false; 10062 if (isTLogEntryWithInclusionPromise(entry)) { 10063 (0, set_1.verifyTLogSET)(entry, tlogAuthorities); 10064 inclusionVerified = true; 10065 } 10066 if (isTLogEntryWithInclusionProof(entry)) { 10067 (0, merkle_1.verifyMerkleInclusion)(entry); 10068 (0, checkpoint_1.verifyCheckpoint)(entry, tlogAuthorities); 10069 inclusionVerified = true; 10070 } 10071 if (!inclusionVerified) { 10072 throw new error_1.VerificationError({ 10073 code: 'TLOG_MISSING_INCLUSION_ERROR', 10074 message: 'inclusion could not be verified', 10075 }); 10076 } 10077 return { 10078 type: 'transparency-log', 10079 logID: entry.logId.keyId, 10080 timestamp: new Date(Number(entry.integratedTime) * 1000), 10081 }; 10082 } 10083 exports.verifyTLogTimestamp = verifyTLogTimestamp; 10084 function isTLogEntryWithInclusionPromise(entry) { 10085 return entry.inclusionPromise !== undefined; 10086 } 10087 function isTLogEntryWithInclusionProof(entry) { 10088 return entry.inclusionProof !== undefined; 10089 } 10090 10091 10092 /***/ }), 10093 10094 /***/ 1407: 10095 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10096 10097 "use strict"; 10098 10099 Object.defineProperty(exports, "__esModule", ({ value: true })); 10100 exports.verifyMerkleInclusion = void 0; 10101 /* 10102 Copyright 2023 The Sigstore Authors. 10103 10104 Licensed under the Apache License, Version 2.0 (the "License"); 10105 you may not use this file except in compliance with the License. 10106 You may obtain a copy of the License at 10107 10108 http://www.apache.org/licenses/LICENSE-2.0 10109 10110 Unless required by applicable law or agreed to in writing, software 10111 distributed under the License is distributed on an "AS IS" BASIS, 10112 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10113 See the License for the specific language governing permissions and 10114 limitations under the License. 10115 */ 10116 const core_1 = __nccwpck_require__(3352); 10117 const error_1 = __nccwpck_require__(8948); 10118 const RFC6962_LEAF_HASH_PREFIX = Buffer.from([0x00]); 10119 const RFC6962_NODE_HASH_PREFIX = Buffer.from([0x01]); 10120 function verifyMerkleInclusion(entry) { 10121 const inclusionProof = entry.inclusionProof; 10122 const logIndex = BigInt(inclusionProof.logIndex); 10123 const treeSize = BigInt(inclusionProof.treeSize); 10124 if (logIndex < 0n || logIndex >= treeSize) { 10125 throw new error_1.VerificationError({ 10126 code: 'TLOG_INCLUSION_PROOF_ERROR', 10127 message: `invalid index: ${logIndex}`, 10128 }); 10129 } 10130 // Figure out which subset of hashes corresponds to the inner and border 10131 // nodes 10132 const { inner, border } = decompInclProof(logIndex, treeSize); 10133 if (inclusionProof.hashes.length !== inner + border) { 10134 throw new error_1.VerificationError({ 10135 code: 'TLOG_INCLUSION_PROOF_ERROR', 10136 message: 'invalid hash count', 10137 }); 10138 } 10139 const innerHashes = inclusionProof.hashes.slice(0, inner); 10140 const borderHashes = inclusionProof.hashes.slice(inner); 10141 // The entry's hash is the leaf hash 10142 const leafHash = hashLeaf(entry.canonicalizedBody); 10143 // Chain the hashes belonging to the inner and border portions 10144 const calculatedHash = chainBorderRight(chainInner(leafHash, innerHashes, logIndex), borderHashes); 10145 // Calculated hash should match the root hash in the inclusion proof 10146 if (!core_1.crypto.bufferEqual(calculatedHash, inclusionProof.rootHash)) { 10147 throw new error_1.VerificationError({ 10148 code: 'TLOG_INCLUSION_PROOF_ERROR', 10149 message: 'calculated root hash does not match inclusion proof', 10150 }); 10151 } 10152 } 10153 exports.verifyMerkleInclusion = verifyMerkleInclusion; 10154 // Breaks down inclusion proof for a leaf at the specified index in a tree of 10155 // the specified size. The split point is where paths to the index leaf and 10156 // the (size - 1) leaf diverge. Returns lengths of the bottom and upper proof 10157 // parts. 10158 function decompInclProof(index, size) { 10159 const inner = innerProofSize(index, size); 10160 const border = onesCount(index >> BigInt(inner)); 10161 return { inner, border }; 10162 } 10163 // Computes a subtree hash for a node on or below the tree's right border. 10164 // Assumes the provided proof hashes are ordered from lower to higher levels 10165 // and seed is the initial hash of the node specified by the index. 10166 function chainInner(seed, hashes, index) { 10167 return hashes.reduce((acc, h, i) => { 10168 if ((index >> BigInt(i)) & BigInt(1)) { 10169 return hashChildren(h, acc); 10170 } 10171 else { 10172 return hashChildren(acc, h); 10173 } 10174 }, seed); 10175 } 10176 // Computes a subtree hash for nodes along the tree's right border. 10177 function chainBorderRight(seed, hashes) { 10178 return hashes.reduce((acc, h) => hashChildren(h, acc), seed); 10179 } 10180 function innerProofSize(index, size) { 10181 return bitLength(index ^ (size - BigInt(1))); 10182 } 10183 // Counts the number of ones in the binary representation of the given number. 10184 // https://en.wikipedia.org/wiki/Hamming_weight 10185 function onesCount(num) { 10186 return num.toString(2).split('1').length - 1; 10187 } 10188 // Returns the number of bits necessary to represent an integer in binary. 10189 function bitLength(n) { 10190 if (n === 0n) { 10191 return 0; 10192 } 10193 return n.toString(2).length; 10194 } 10195 // Hashing logic according to RFC6962. 10196 // https://datatracker.ietf.org/doc/html/rfc6962#section-2 10197 function hashChildren(left, right) { 10198 return core_1.crypto.hash(RFC6962_NODE_HASH_PREFIX, left, right); 10199 } 10200 function hashLeaf(leaf) { 10201 return core_1.crypto.hash(RFC6962_LEAF_HASH_PREFIX, leaf); 10202 } 10203 10204 10205 /***/ }), 10206 10207 /***/ 7527: 10208 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10209 10210 "use strict"; 10211 10212 Object.defineProperty(exports, "__esModule", ({ value: true })); 10213 exports.verifyTLogSET = void 0; 10214 /* 10215 Copyright 2023 The Sigstore Authors. 10216 10217 Licensed under the Apache License, Version 2.0 (the "License"); 10218 you may not use this file except in compliance with the License. 10219 You may obtain a copy of the License at 10220 10221 http://www.apache.org/licenses/LICENSE-2.0 10222 10223 Unless required by applicable law or agreed to in writing, software 10224 distributed under the License is distributed on an "AS IS" BASIS, 10225 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10226 See the License for the specific language governing permissions and 10227 limitations under the License. 10228 */ 10229 const core_1 = __nccwpck_require__(3352); 10230 const error_1 = __nccwpck_require__(8948); 10231 const trust_1 = __nccwpck_require__(4503); 10232 // Verifies the SET for the given entry against the list of trusted 10233 // transparency logs. Returns true if the SET can be verified against at least 10234 // one of the trusted logs; otherwise, returns false. 10235 function verifyTLogSET(entry, tlogs) { 10236 // Filter the list of tlog instances to only those which might be able to 10237 // verify the SET 10238 const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, { 10239 logID: entry.logId.keyId, 10240 targetDate: new Date(Number(entry.integratedTime) * 1000), 10241 }); 10242 // Check to see if we can verify the SET against any of the valid tlogs 10243 const verified = validTLogs.some((tlog) => { 10244 // Re-create the original Rekor verification payload 10245 const payload = toVerificationPayload(entry); 10246 // Canonicalize the payload and turn into a buffer for verification 10247 const data = Buffer.from(core_1.json.canonicalize(payload), 'utf8'); 10248 // Extract the SET from the tlog entry 10249 const signature = entry.inclusionPromise.signedEntryTimestamp; 10250 return core_1.crypto.verify(data, tlog.publicKey, signature); 10251 }); 10252 if (!verified) { 10253 throw new error_1.VerificationError({ 10254 code: 'TLOG_INCLUSION_PROMISE_ERROR', 10255 message: 'inclusion promise could not be verified', 10256 }); 10257 } 10258 } 10259 exports.verifyTLogSET = verifyTLogSET; 10260 // Returns a properly formatted "VerificationPayload" for one of the 10261 // transaction log entires in the given bundle which can be used for SET 10262 // verification. 10263 function toVerificationPayload(entry) { 10264 const { integratedTime, logIndex, logId, canonicalizedBody } = entry; 10265 return { 10266 body: canonicalizedBody.toString('base64'), 10267 integratedTime: Number(integratedTime), 10268 logIndex: Number(logIndex), 10269 logID: logId.keyId.toString('hex'), 10270 }; 10271 } 10272 10273 10274 /***/ }), 10275 10276 /***/ 2574: 10277 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10278 10279 "use strict"; 10280 10281 Object.defineProperty(exports, "__esModule", ({ value: true })); 10282 exports.verifyRFC3161Timestamp = void 0; 10283 const core_1 = __nccwpck_require__(3352); 10284 const error_1 = __nccwpck_require__(8948); 10285 const certificate_1 = __nccwpck_require__(8766); 10286 const trust_1 = __nccwpck_require__(4503); 10287 function verifyRFC3161Timestamp(timestamp, data, timestampAuthorities) { 10288 const signingTime = timestamp.signingTime; 10289 // Filter for CAs which were valid at the time of signing 10290 timestampAuthorities = (0, trust_1.filterCertAuthorities)(timestampAuthorities, { 10291 start: signingTime, 10292 end: signingTime, 10293 }); 10294 // Filter for CAs which match serial and issuer embedded in the timestamp 10295 timestampAuthorities = filterCAsBySerialAndIssuer(timestampAuthorities, { 10296 serialNumber: timestamp.signerSerialNumber, 10297 issuer: timestamp.signerIssuer, 10298 }); 10299 // Check that we can verify the timestamp with AT LEAST ONE of the remaining 10300 // CAs 10301 const verified = timestampAuthorities.some((ca) => { 10302 try { 10303 verifyTimestampForCA(timestamp, data, ca); 10304 return true; 10305 } 10306 catch (e) { 10307 return false; 10308 } 10309 }); 10310 if (!verified) { 10311 throw new error_1.VerificationError({ 10312 code: 'TIMESTAMP_ERROR', 10313 message: 'timestamp could not be verified', 10314 }); 10315 } 10316 } 10317 exports.verifyRFC3161Timestamp = verifyRFC3161Timestamp; 10318 function verifyTimestampForCA(timestamp, data, ca) { 10319 const [leaf, ...cas] = ca.certChain; 10320 const signingKey = core_1.crypto.createPublicKey(leaf.publicKey); 10321 const signingTime = timestamp.signingTime; 10322 // Verify the certificate chain for the provided CA 10323 try { 10324 new certificate_1.CertificateChainVerifier({ 10325 untrustedCert: leaf, 10326 trustedCerts: cas, 10327 }).verify(); 10328 } 10329 catch (e) { 10330 throw new error_1.VerificationError({ 10331 code: 'TIMESTAMP_ERROR', 10332 message: 'invalid certificate chain', 10333 }); 10334 } 10335 // Check that all of the CA certs were valid at the time of signing 10336 const validAtSigningTime = ca.certChain.every((cert) => cert.validForDate(signingTime)); 10337 if (!validAtSigningTime) { 10338 throw new error_1.VerificationError({ 10339 code: 'TIMESTAMP_ERROR', 10340 message: 'timestamp was signed with an expired certificate', 10341 }); 10342 } 10343 // Check that the signing certificate's key can be used to verify the 10344 // timestamp signature. 10345 timestamp.verify(data, signingKey); 10346 } 10347 // Filters the list of CAs to those which have a leaf signing certificate which 10348 // matches the given serial number and issuer. 10349 function filterCAsBySerialAndIssuer(timestampAuthorities, criteria) { 10350 return timestampAuthorities.filter((ca) => ca.certChain.length > 0 && 10351 core_1.crypto.bufferEqual(ca.certChain[0].serialNumber, criteria.serialNumber) && 10352 core_1.crypto.bufferEqual(ca.certChain[0].issuer, criteria.issuer)); 10353 } 10354 10355 10356 /***/ }), 10357 10358 /***/ 4625: 10359 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10360 10361 "use strict"; 10362 10363 Object.defineProperty(exports, "__esModule", ({ value: true })); 10364 exports.verifyDSSETLogBody = void 0; 10365 /* 10366 Copyright 2023 The Sigstore Authors. 10367 10368 Licensed under the Apache License, Version 2.0 (the "License"); 10369 you may not use this file except in compliance with the License. 10370 You may obtain a copy of the License at 10371 10372 http://www.apache.org/licenses/LICENSE-2.0 10373 10374 Unless required by applicable law or agreed to in writing, software 10375 distributed under the License is distributed on an "AS IS" BASIS, 10376 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10377 See the License for the specific language governing permissions and 10378 limitations under the License. 10379 */ 10380 const error_1 = __nccwpck_require__(8948); 10381 // Compare the given intoto tlog entry to the given bundle 10382 function verifyDSSETLogBody(tlogEntry, content) { 10383 switch (tlogEntry.apiVersion) { 10384 case '0.0.1': 10385 return verifyDSSE001TLogBody(tlogEntry, content); 10386 default: 10387 throw new error_1.VerificationError({ 10388 code: 'TLOG_BODY_ERROR', 10389 message: `unsupported dsse version: ${tlogEntry.apiVersion}`, 10390 }); 10391 } 10392 } 10393 exports.verifyDSSETLogBody = verifyDSSETLogBody; 10394 // Compare the given dsse v0.0.1 tlog entry to the given DSSE envelope. 10395 function verifyDSSE001TLogBody(tlogEntry, content) { 10396 // Ensure the bundle's DSSE only contains a single signature 10397 if (tlogEntry.spec.signatures?.length !== 1) { 10398 throw new error_1.VerificationError({ 10399 code: 'TLOG_BODY_ERROR', 10400 message: 'signature count mismatch', 10401 }); 10402 } 10403 const tlogSig = tlogEntry.spec.signatures[0].signature; 10404 // Ensure that the signature in the bundle's DSSE matches tlog entry 10405 if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) 10406 throw new error_1.VerificationError({ 10407 code: 'TLOG_BODY_ERROR', 10408 message: 'tlog entry signature mismatch', 10409 }); 10410 // Ensure the digest of the bundle's DSSE payload matches the digest in the 10411 // tlog entry 10412 const tlogHash = tlogEntry.spec.payloadHash?.value || ''; 10413 if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) { 10414 throw new error_1.VerificationError({ 10415 code: 'TLOG_BODY_ERROR', 10416 message: 'DSSE payload hash mismatch', 10417 }); 10418 } 10419 } 10420 10421 10422 /***/ }), 10423 10424 /***/ 935: 10425 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10426 10427 "use strict"; 10428 10429 Object.defineProperty(exports, "__esModule", ({ value: true })); 10430 exports.verifyHashedRekordTLogBody = void 0; 10431 /* 10432 Copyright 2023 The Sigstore Authors. 10433 10434 Licensed under the Apache License, Version 2.0 (the "License"); 10435 you may not use this file except in compliance with the License. 10436 You may obtain a copy of the License at 10437 10438 http://www.apache.org/licenses/LICENSE-2.0 10439 10440 Unless required by applicable law or agreed to in writing, software 10441 distributed under the License is distributed on an "AS IS" BASIS, 10442 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10443 See the License for the specific language governing permissions and 10444 limitations under the License. 10445 */ 10446 const error_1 = __nccwpck_require__(8948); 10447 // Compare the given hashedrekord tlog entry to the given bundle 10448 function verifyHashedRekordTLogBody(tlogEntry, content) { 10449 switch (tlogEntry.apiVersion) { 10450 case '0.0.1': 10451 return verifyHashedrekord001TLogBody(tlogEntry, content); 10452 default: 10453 throw new error_1.VerificationError({ 10454 code: 'TLOG_BODY_ERROR', 10455 message: `unsupported hashedrekord version: ${tlogEntry.apiVersion}`, 10456 }); 10457 } 10458 } 10459 exports.verifyHashedRekordTLogBody = verifyHashedRekordTLogBody; 10460 // Compare the given hashedrekord v0.0.1 tlog entry to the given message 10461 // signature 10462 function verifyHashedrekord001TLogBody(tlogEntry, content) { 10463 // Ensure that the bundles message signature matches the tlog entry 10464 const tlogSig = tlogEntry.spec.signature.content || ''; 10465 if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) { 10466 throw new error_1.VerificationError({ 10467 code: 'TLOG_BODY_ERROR', 10468 message: 'signature mismatch', 10469 }); 10470 } 10471 // Ensure that the bundle's message digest matches the tlog entry 10472 const tlogDigest = tlogEntry.spec.data.hash?.value || ''; 10473 if (!content.compareDigest(Buffer.from(tlogDigest, 'hex'))) { 10474 throw new error_1.VerificationError({ 10475 code: 'TLOG_BODY_ERROR', 10476 message: 'digest mismatch', 10477 }); 10478 } 10479 } 10480 10481 10482 /***/ }), 10483 10484 /***/ 4566: 10485 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10486 10487 "use strict"; 10488 10489 Object.defineProperty(exports, "__esModule", ({ value: true })); 10490 exports.verifyTLogBody = void 0; 10491 /* 10492 Copyright 2023 The Sigstore Authors. 10493 10494 Licensed under the Apache License, Version 2.0 (the "License"); 10495 you may not use this file except in compliance with the License. 10496 You may obtain a copy of the License at 10497 10498 http://www.apache.org/licenses/LICENSE-2.0 10499 10500 Unless required by applicable law or agreed to in writing, software 10501 distributed under the License is distributed on an "AS IS" BASIS, 10502 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10503 See the License for the specific language governing permissions and 10504 limitations under the License. 10505 */ 10506 const error_1 = __nccwpck_require__(8948); 10507 const dsse_1 = __nccwpck_require__(4625); 10508 const hashedrekord_1 = __nccwpck_require__(935); 10509 const intoto_1 = __nccwpck_require__(8645); 10510 // Verifies that the given tlog entry matches the supplied signature content. 10511 function verifyTLogBody(entry, sigContent) { 10512 const { kind, version } = entry.kindVersion; 10513 const body = JSON.parse(entry.canonicalizedBody.toString('utf8')); 10514 if (kind !== body.kind || version !== body.apiVersion) { 10515 throw new error_1.VerificationError({ 10516 code: 'TLOG_BODY_ERROR', 10517 message: `kind/version mismatch - expected: ${kind}/${version}, received: ${body.kind}/${body.apiVersion}`, 10518 }); 10519 } 10520 switch (body.kind) { 10521 case 'dsse': 10522 return (0, dsse_1.verifyDSSETLogBody)(body, sigContent); 10523 case 'intoto': 10524 return (0, intoto_1.verifyIntotoTLogBody)(body, sigContent); 10525 case 'hashedrekord': 10526 return (0, hashedrekord_1.verifyHashedRekordTLogBody)(body, sigContent); 10527 /* istanbul ignore next */ 10528 default: 10529 throw new error_1.VerificationError({ 10530 code: 'TLOG_BODY_ERROR', 10531 message: `unsupported kind: ${kind}`, 10532 }); 10533 } 10534 } 10535 exports.verifyTLogBody = verifyTLogBody; 10536 10537 10538 /***/ }), 10539 10540 /***/ 8645: 10541 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10542 10543 "use strict"; 10544 10545 Object.defineProperty(exports, "__esModule", ({ value: true })); 10546 exports.verifyIntotoTLogBody = void 0; 10547 /* 10548 Copyright 2023 The Sigstore Authors. 10549 10550 Licensed under the Apache License, Version 2.0 (the "License"); 10551 you may not use this file except in compliance with the License. 10552 You may obtain a copy of the License at 10553 10554 http://www.apache.org/licenses/LICENSE-2.0 10555 10556 Unless required by applicable law or agreed to in writing, software 10557 distributed under the License is distributed on an "AS IS" BASIS, 10558 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10559 See the License for the specific language governing permissions and 10560 limitations under the License. 10561 */ 10562 const error_1 = __nccwpck_require__(8948); 10563 // Compare the given intoto tlog entry to the given bundle 10564 function verifyIntotoTLogBody(tlogEntry, content) { 10565 switch (tlogEntry.apiVersion) { 10566 case '0.0.2': 10567 return verifyIntoto002TLogBody(tlogEntry, content); 10568 default: 10569 throw new error_1.VerificationError({ 10570 code: 'TLOG_BODY_ERROR', 10571 message: `unsupported intoto version: ${tlogEntry.apiVersion}`, 10572 }); 10573 } 10574 } 10575 exports.verifyIntotoTLogBody = verifyIntotoTLogBody; 10576 // Compare the given intoto v0.0.2 tlog entry to the given DSSE envelope. 10577 function verifyIntoto002TLogBody(tlogEntry, content) { 10578 // Ensure the bundle's DSSE contains a single signature 10579 if (tlogEntry.spec.content.envelope.signatures?.length !== 1) { 10580 throw new error_1.VerificationError({ 10581 code: 'TLOG_BODY_ERROR', 10582 message: 'signature count mismatch', 10583 }); 10584 } 10585 // Signature is double-base64-encoded in the tlog entry 10586 const tlogSig = base64Decode(tlogEntry.spec.content.envelope.signatures[0].sig); 10587 // Ensure that the signature in the bundle's DSSE matches tlog entry 10588 if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) { 10589 throw new error_1.VerificationError({ 10590 code: 'TLOG_BODY_ERROR', 10591 message: 'tlog entry signature mismatch', 10592 }); 10593 } 10594 // Ensure the digest of the bundle's DSSE payload matches the digest in the 10595 // tlog entry 10596 const tlogHash = tlogEntry.spec.content.payloadHash?.value || ''; 10597 if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) { 10598 throw new error_1.VerificationError({ 10599 code: 'TLOG_BODY_ERROR', 10600 message: 'DSSE payload hash mismatch', 10601 }); 10602 } 10603 } 10604 function base64Decode(str) { 10605 return Buffer.from(str, 'base64').toString('utf-8'); 10606 } 10607 10608 10609 /***/ }), 10610 10611 /***/ 6906: 10612 /***/ ((__unused_webpack_module, exports) => { 10613 10614 "use strict"; 10615 10616 Object.defineProperty(exports, "__esModule", ({ value: true })); 10617 exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0; 10618 function filterCertAuthorities(certAuthorities, criteria) { 10619 return certAuthorities.filter((ca) => { 10620 return (ca.validFor.start <= criteria.start && ca.validFor.end >= criteria.end); 10621 }); 10622 } 10623 exports.filterCertAuthorities = filterCertAuthorities; 10624 // Filter the list of tlog instances to only those which match the given log 10625 // ID and have public keys which are valid for the given integrated time. 10626 function filterTLogAuthorities(tlogAuthorities, criteria) { 10627 return tlogAuthorities.filter((tlog) => { 10628 // If we're filtering by log ID and the log IDs don't match, we can't use 10629 // this tlog 10630 if (criteria.logID && !tlog.logID.equals(criteria.logID)) { 10631 return false; 10632 } 10633 // Check that the integrated time is within the validFor range 10634 return (tlog.validFor.start <= criteria.targetDate && 10635 criteria.targetDate <= tlog.validFor.end); 10636 }); 10637 } 10638 exports.filterTLogAuthorities = filterTLogAuthorities; 10639 10640 10641 /***/ }), 10642 10643 /***/ 4503: 10644 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10645 10646 "use strict"; 10647 10648 Object.defineProperty(exports, "__esModule", ({ value: true })); 10649 exports.toTrustMaterial = exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0; 10650 /* 10651 Copyright 2023 The Sigstore Authors. 10652 10653 Licensed under the Apache License, Version 2.0 (the "License"); 10654 you may not use this file except in compliance with the License. 10655 You may obtain a copy of the License at 10656 10657 http://www.apache.org/licenses/LICENSE-2.0 10658 10659 Unless required by applicable law or agreed to in writing, software 10660 distributed under the License is distributed on an "AS IS" BASIS, 10661 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10662 See the License for the specific language governing permissions and 10663 limitations under the License. 10664 */ 10665 const core_1 = __nccwpck_require__(3352); 10666 const protobuf_specs_1 = __nccwpck_require__(530); 10667 const error_1 = __nccwpck_require__(8948); 10668 const BEGINNING_OF_TIME = new Date(0); 10669 const END_OF_TIME = new Date(8640000000000000); 10670 var filter_1 = __nccwpck_require__(6906); 10671 Object.defineProperty(exports, "filterCertAuthorities", ({ enumerable: true, get: function () { return filter_1.filterCertAuthorities; } })); 10672 Object.defineProperty(exports, "filterTLogAuthorities", ({ enumerable: true, get: function () { return filter_1.filterTLogAuthorities; } })); 10673 function toTrustMaterial(root, keys) { 10674 const keyFinder = typeof keys === 'function' ? keys : keyLocator(keys); 10675 return { 10676 certificateAuthorities: root.certificateAuthorities.map(createCertAuthority), 10677 timestampAuthorities: root.timestampAuthorities.map(createCertAuthority), 10678 tlogs: root.tlogs.map(createTLogAuthority), 10679 ctlogs: root.ctlogs.map(createTLogAuthority), 10680 publicKey: keyFinder, 10681 }; 10682 } 10683 exports.toTrustMaterial = toTrustMaterial; 10684 function createTLogAuthority(tlogInstance) { 10685 const keyDetails = tlogInstance.publicKey.keyDetails; 10686 const keyType = keyDetails === protobuf_specs_1.PublicKeyDetails.PKCS1_RSA_PKCS1V5 || 10687 keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V5 || 10688 keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256 || 10689 keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256 || 10690 keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256 10691 ? 'pkcs1' 10692 : 'spki'; 10693 return { 10694 logID: tlogInstance.logId.keyId, 10695 publicKey: core_1.crypto.createPublicKey(tlogInstance.publicKey.rawBytes, keyType), 10696 validFor: { 10697 start: tlogInstance.publicKey.validFor?.start || BEGINNING_OF_TIME, 10698 end: tlogInstance.publicKey.validFor?.end || END_OF_TIME, 10699 }, 10700 }; 10701 } 10702 function createCertAuthority(ca) { 10703 return { 10704 certChain: ca.certChain.certificates.map((cert) => { 10705 return core_1.X509Certificate.parse(cert.rawBytes); 10706 }), 10707 validFor: { 10708 start: ca.validFor?.start || BEGINNING_OF_TIME, 10709 end: ca.validFor?.end || END_OF_TIME, 10710 }, 10711 }; 10712 } 10713 function keyLocator(keys) { 10714 return (hint) => { 10715 const key = (keys || {})[hint]; 10716 if (!key) { 10717 throw new error_1.VerificationError({ 10718 code: 'PUBLIC_KEY_ERROR', 10719 message: `key not found: ${hint}`, 10720 }); 10721 } 10722 return { 10723 publicKey: core_1.crypto.createPublicKey(key.rawBytes), 10724 validFor: (date) => { 10725 return ((key.validFor?.start || BEGINNING_OF_TIME) <= date && 10726 (key.validFor?.end || END_OF_TIME) >= date); 10727 }, 10728 }; 10729 }; 10730 } 10731 10732 10733 /***/ }), 10734 10735 /***/ 5456: 10736 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 10737 10738 "use strict"; 10739 10740 Object.defineProperty(exports, "__esModule", ({ value: true })); 10741 exports.Verifier = void 0; 10742 /* 10743 Copyright 2023 The Sigstore Authors. 10744 10745 Licensed under the Apache License, Version 2.0 (the "License"); 10746 you may not use this file except in compliance with the License. 10747 You may obtain a copy of the License at 10748 10749 http://www.apache.org/licenses/LICENSE-2.0 10750 10751 Unless required by applicable law or agreed to in writing, software 10752 distributed under the License is distributed on an "AS IS" BASIS, 10753 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10754 See the License for the specific language governing permissions and 10755 limitations under the License. 10756 */ 10757 const util_1 = __nccwpck_require__(3837); 10758 const error_1 = __nccwpck_require__(8948); 10759 const key_1 = __nccwpck_require__(6829); 10760 const policy_1 = __nccwpck_require__(3978); 10761 const timestamp_1 = __nccwpck_require__(9511); 10762 const tlog_1 = __nccwpck_require__(4566); 10763 class Verifier { 10764 constructor(trustMaterial, options = {}) { 10765 this.trustMaterial = trustMaterial; 10766 this.options = { 10767 ctlogThreshold: options.ctlogThreshold ?? 1, 10768 tlogThreshold: options.tlogThreshold ?? 1, 10769 tsaThreshold: options.tsaThreshold ?? 0, 10770 }; 10771 } 10772 verify(entity, policy) { 10773 const timestamps = this.verifyTimestamps(entity); 10774 const signer = this.verifySigningKey(entity, timestamps); 10775 this.verifyTLogs(entity); 10776 this.verifySignature(entity, signer); 10777 if (policy) { 10778 this.verifyPolicy(policy, signer.identity || {}); 10779 } 10780 return signer; 10781 } 10782 // Checks that all of the timestamps in the entity are valid and returns them 10783 verifyTimestamps(entity) { 10784 let tlogCount = 0; 10785 let tsaCount = 0; 10786 const timestamps = entity.timestamps.map((timestamp) => { 10787 switch (timestamp.$case) { 10788 case 'timestamp-authority': 10789 tsaCount++; 10790 return (0, timestamp_1.verifyTSATimestamp)(timestamp.timestamp, entity.signature.signature, this.trustMaterial.timestampAuthorities); 10791 case 'transparency-log': 10792 tlogCount++; 10793 return (0, timestamp_1.verifyTLogTimestamp)(timestamp.tlogEntry, this.trustMaterial.tlogs); 10794 } 10795 }); 10796 // Check for duplicate timestamps 10797 if (containsDupes(timestamps)) { 10798 throw new error_1.VerificationError({ 10799 code: 'TIMESTAMP_ERROR', 10800 message: 'duplicate timestamp', 10801 }); 10802 } 10803 if (tlogCount < this.options.tlogThreshold) { 10804 throw new error_1.VerificationError({ 10805 code: 'TIMESTAMP_ERROR', 10806 message: `expected ${this.options.tlogThreshold} tlog timestamps, got ${tlogCount}`, 10807 }); 10808 } 10809 if (tsaCount < this.options.tsaThreshold) { 10810 throw new error_1.VerificationError({ 10811 code: 'TIMESTAMP_ERROR', 10812 message: `expected ${this.options.tsaThreshold} tsa timestamps, got ${tsaCount}`, 10813 }); 10814 } 10815 return timestamps.map((t) => t.timestamp); 10816 } 10817 // Checks that the signing key is valid for all of the the supplied timestamps 10818 // and returns the signer. 10819 verifySigningKey({ key }, timestamps) { 10820 switch (key.$case) { 10821 case 'public-key': { 10822 return (0, key_1.verifyPublicKey)(key.hint, timestamps, this.trustMaterial); 10823 } 10824 case 'certificate': { 10825 const result = (0, key_1.verifyCertificate)(key.certificate, timestamps, this.trustMaterial); 10826 /* istanbul ignore next - no fixture */ 10827 if (containsDupes(result.scts)) { 10828 throw new error_1.VerificationError({ 10829 code: 'CERTIFICATE_ERROR', 10830 message: 'duplicate SCT', 10831 }); 10832 } 10833 if (result.scts.length < this.options.ctlogThreshold) { 10834 throw new error_1.VerificationError({ 10835 code: 'CERTIFICATE_ERROR', 10836 message: `expected ${this.options.ctlogThreshold} SCTs, got ${result.scts.length}`, 10837 }); 10838 } 10839 return result.signer; 10840 } 10841 } 10842 } 10843 // Checks that the tlog entries are valid for the supplied content 10844 verifyTLogs({ signature: content, tlogEntries }) { 10845 tlogEntries.forEach((entry) => (0, tlog_1.verifyTLogBody)(entry, content)); 10846 } 10847 // Checks that the signature is valid for the supplied content 10848 verifySignature(entity, signer) { 10849 if (!entity.signature.verifySignature(signer.key)) { 10850 throw new error_1.VerificationError({ 10851 code: 'SIGNATURE_ERROR', 10852 message: 'signature verification failed', 10853 }); 10854 } 10855 } 10856 verifyPolicy(policy, identity) { 10857 // Check the subject alternative name of the signer matches the policy 10858 if (policy.subjectAlternativeName) { 10859 (0, policy_1.verifySubjectAlternativeName)(policy.subjectAlternativeName, identity.subjectAlternativeName); 10860 } 10861 // Check that the extensions of the signer match the policy 10862 if (policy.extensions) { 10863 (0, policy_1.verifyExtensions)(policy.extensions, identity.extensions); 10864 } 10865 } 10866 } 10867 exports.Verifier = Verifier; 10868 // Checks for duplicate items in the array. Objects are compared using 10869 // deep equality. 10870 function containsDupes(arr) { 10871 for (let i = 0; i < arr.length; i++) { 10872 for (let j = i + 1; j < arr.length; j++) { 10873 if ((0, util_1.isDeepStrictEqual)(arr[i], arr[j])) { 10874 return true; 10875 } 10876 } 10877 } 10878 return false; 10879 } 10880 10881 10882 /***/ }), 10883 10884 /***/ 9652: 10885 /***/ ((module) => { 10886 10887 const COMMA = ','; 10888 const COLON = ':'; 10889 const LEFT_SQUARE_BRACKET = '['; 10890 const RIGHT_SQUARE_BRACKET = ']'; 10891 const LEFT_CURLY_BRACKET = '{'; 10892 const RIGHT_CURLY_BRACKET = '}'; 10893 10894 // Recursively encodes the supplied object according to the canonical JSON form 10895 // as specified at http://wiki.laptop.org/go/Canonical_JSON. It's a restricted 10896 // dialect of JSON in which keys are lexically sorted, floats are not allowed, 10897 // and only double quotes and backslashes are escaped. 10898 function canonicalize(object) { 10899 const buffer = []; 10900 if (typeof object === 'string') { 10901 buffer.push(canonicalizeString(object)); 10902 } else if (typeof object === 'boolean') { 10903 buffer.push(JSON.stringify(object)); 10904 } else if (Number.isInteger(object)) { 10905 buffer.push(JSON.stringify(object)); 10906 } else if (object === null) { 10907 buffer.push(JSON.stringify(object)); 10908 } else if (Array.isArray(object)) { 10909 buffer.push(LEFT_SQUARE_BRACKET); 10910 let first = true; 10911 object.forEach((element) => { 10912 if (!first) { 10913 buffer.push(COMMA); 10914 } 10915 first = false; 10916 buffer.push(canonicalize(element)); 10917 }); 10918 buffer.push(RIGHT_SQUARE_BRACKET); 10919 } else if (typeof object === 'object') { 10920 buffer.push(LEFT_CURLY_BRACKET); 10921 let first = true; 10922 Object.keys(object) 10923 .sort() 10924 .forEach((property) => { 10925 if (!first) { 10926 buffer.push(COMMA); 10927 } 10928 first = false; 10929 buffer.push(canonicalizeString(property)); 10930 buffer.push(COLON); 10931 buffer.push(canonicalize(object[property])); 10932 }); 10933 buffer.push(RIGHT_CURLY_BRACKET); 10934 } else { 10935 throw new TypeError('cannot encode ' + object.toString()); 10936 } 10937 10938 return buffer.join(''); 10939 } 10940 10941 // String canonicalization consists of escaping backslash (\) and double 10942 // quote (") characters and wrapping the resulting string in double quotes. 10943 function canonicalizeString(string) { 10944 const escapedString = string.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); 10945 return '"' + escapedString + '"'; 10946 } 10947 10948 module.exports = { 10949 canonicalize, 10950 }; 10951 10952 10953 /***/ }), 10954 10955 /***/ 159: 10956 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 10957 10958 "use strict"; 10959 10960 var __importDefault = (this && this.__importDefault) || function (mod) { 10961 return (mod && mod.__esModule) ? mod : { "default": mod }; 10962 }; 10963 Object.defineProperty(exports, "__esModule", ({ value: true })); 10964 exports.Signed = exports.isMetadataKind = exports.MetadataKind = void 0; 10965 const util_1 = __importDefault(__nccwpck_require__(3837)); 10966 const error_1 = __nccwpck_require__(8448); 10967 const utils_1 = __nccwpck_require__(5688); 10968 const SPECIFICATION_VERSION = ['1', '0', '31']; 10969 var MetadataKind; 10970 (function (MetadataKind) { 10971 MetadataKind["Root"] = "root"; 10972 MetadataKind["Timestamp"] = "timestamp"; 10973 MetadataKind["Snapshot"] = "snapshot"; 10974 MetadataKind["Targets"] = "targets"; 10975 })(MetadataKind || (exports.MetadataKind = MetadataKind = {})); 10976 function isMetadataKind(value) { 10977 return (typeof value === 'string' && 10978 Object.values(MetadataKind).includes(value)); 10979 } 10980 exports.isMetadataKind = isMetadataKind; 10981 /*** 10982 * A base class for the signed part of TUF metadata. 10983 * 10984 * Objects with base class Signed are usually included in a ``Metadata`` object 10985 * on the signed attribute. This class provides attributes and methods that 10986 * are common for all TUF metadata types (roles). 10987 */ 10988 class Signed { 10989 constructor(options) { 10990 this.specVersion = options.specVersion || SPECIFICATION_VERSION.join('.'); 10991 const specList = this.specVersion.split('.'); 10992 if (!(specList.length === 2 || specList.length === 3) || 10993 !specList.every((item) => isNumeric(item))) { 10994 throw new error_1.ValueError('Failed to parse specVersion'); 10995 } 10996 // major version must match 10997 if (specList[0] != SPECIFICATION_VERSION[0]) { 10998 throw new error_1.ValueError('Unsupported specVersion'); 10999 } 11000 this.expires = options.expires || new Date().toISOString(); 11001 this.version = options.version || 1; 11002 this.unrecognizedFields = options.unrecognizedFields || {}; 11003 } 11004 equals(other) { 11005 if (!(other instanceof Signed)) { 11006 return false; 11007 } 11008 return (this.specVersion === other.specVersion && 11009 this.expires === other.expires && 11010 this.version === other.version && 11011 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11012 } 11013 isExpired(referenceTime) { 11014 if (!referenceTime) { 11015 referenceTime = new Date(); 11016 } 11017 return referenceTime >= new Date(this.expires); 11018 } 11019 static commonFieldsFromJSON(data) { 11020 const { spec_version, expires, version, ...rest } = data; 11021 if (utils_1.guard.isDefined(spec_version) && !(typeof spec_version === 'string')) { 11022 throw new TypeError('spec_version must be a string'); 11023 } 11024 if (utils_1.guard.isDefined(expires) && !(typeof expires === 'string')) { 11025 throw new TypeError('expires must be a string'); 11026 } 11027 if (utils_1.guard.isDefined(version) && !(typeof version === 'number')) { 11028 throw new TypeError('version must be a number'); 11029 } 11030 return { 11031 specVersion: spec_version, 11032 expires, 11033 version, 11034 unrecognizedFields: rest, 11035 }; 11036 } 11037 } 11038 exports.Signed = Signed; 11039 function isNumeric(str) { 11040 return !isNaN(Number(str)); 11041 } 11042 11043 11044 /***/ }), 11045 11046 /***/ 1662: 11047 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11048 11049 "use strict"; 11050 11051 var __importDefault = (this && this.__importDefault) || function (mod) { 11052 return (mod && mod.__esModule) ? mod : { "default": mod }; 11053 }; 11054 Object.defineProperty(exports, "__esModule", ({ value: true })); 11055 exports.Delegations = void 0; 11056 const util_1 = __importDefault(__nccwpck_require__(3837)); 11057 const error_1 = __nccwpck_require__(8448); 11058 const key_1 = __nccwpck_require__(6697); 11059 const role_1 = __nccwpck_require__(9393); 11060 const utils_1 = __nccwpck_require__(5688); 11061 /** 11062 * A container object storing information about all delegations. 11063 * 11064 * Targets roles that are trusted to provide signed metadata files 11065 * describing targets with designated pathnames and/or further delegations. 11066 */ 11067 class Delegations { 11068 constructor(options) { 11069 this.keys = options.keys; 11070 this.unrecognizedFields = options.unrecognizedFields || {}; 11071 if (options.roles) { 11072 if (Object.keys(options.roles).some((roleName) => role_1.TOP_LEVEL_ROLE_NAMES.includes(roleName))) { 11073 throw new error_1.ValueError('Delegated role name conflicts with top-level role name'); 11074 } 11075 } 11076 this.succinctRoles = options.succinctRoles; 11077 this.roles = options.roles; 11078 } 11079 equals(other) { 11080 if (!(other instanceof Delegations)) { 11081 return false; 11082 } 11083 return (util_1.default.isDeepStrictEqual(this.keys, other.keys) && 11084 util_1.default.isDeepStrictEqual(this.roles, other.roles) && 11085 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields) && 11086 util_1.default.isDeepStrictEqual(this.succinctRoles, other.succinctRoles)); 11087 } 11088 *rolesForTarget(targetPath) { 11089 if (this.roles) { 11090 for (const role of Object.values(this.roles)) { 11091 if (role.isDelegatedPath(targetPath)) { 11092 yield { role: role.name, terminating: role.terminating }; 11093 } 11094 } 11095 } 11096 else if (this.succinctRoles) { 11097 yield { 11098 role: this.succinctRoles.getRoleForTarget(targetPath), 11099 terminating: true, 11100 }; 11101 } 11102 } 11103 toJSON() { 11104 const json = { 11105 keys: keysToJSON(this.keys), 11106 ...this.unrecognizedFields, 11107 }; 11108 if (this.roles) { 11109 json.roles = rolesToJSON(this.roles); 11110 } 11111 else if (this.succinctRoles) { 11112 json.succinct_roles = this.succinctRoles.toJSON(); 11113 } 11114 return json; 11115 } 11116 static fromJSON(data) { 11117 const { keys, roles, succinct_roles, ...unrecognizedFields } = data; 11118 let succinctRoles; 11119 if (utils_1.guard.isObject(succinct_roles)) { 11120 succinctRoles = role_1.SuccinctRoles.fromJSON(succinct_roles); 11121 } 11122 return new Delegations({ 11123 keys: keysFromJSON(keys), 11124 roles: rolesFromJSON(roles), 11125 unrecognizedFields, 11126 succinctRoles, 11127 }); 11128 } 11129 } 11130 exports.Delegations = Delegations; 11131 function keysToJSON(keys) { 11132 return Object.entries(keys).reduce((acc, [keyId, key]) => ({ 11133 ...acc, 11134 [keyId]: key.toJSON(), 11135 }), {}); 11136 } 11137 function rolesToJSON(roles) { 11138 return Object.values(roles).map((role) => role.toJSON()); 11139 } 11140 function keysFromJSON(data) { 11141 if (!utils_1.guard.isObjectRecord(data)) { 11142 throw new TypeError('keys is malformed'); 11143 } 11144 return Object.entries(data).reduce((acc, [keyID, keyData]) => ({ 11145 ...acc, 11146 [keyID]: key_1.Key.fromJSON(keyID, keyData), 11147 }), {}); 11148 } 11149 function rolesFromJSON(data) { 11150 let roleMap; 11151 if (utils_1.guard.isDefined(data)) { 11152 if (!utils_1.guard.isObjectArray(data)) { 11153 throw new TypeError('roles is malformed'); 11154 } 11155 roleMap = data.reduce((acc, role) => { 11156 const delegatedRole = role_1.DelegatedRole.fromJSON(role); 11157 return { 11158 ...acc, 11159 [delegatedRole.name]: delegatedRole, 11160 }; 11161 }, {}); 11162 } 11163 return roleMap; 11164 } 11165 11166 11167 /***/ }), 11168 11169 /***/ 8448: 11170 /***/ ((__unused_webpack_module, exports) => { 11171 11172 "use strict"; 11173 11174 Object.defineProperty(exports, "__esModule", ({ value: true })); 11175 exports.UnsupportedAlgorithmError = exports.CryptoError = exports.LengthOrHashMismatchError = exports.UnsignedMetadataError = exports.RepositoryError = exports.ValueError = void 0; 11176 // An error about insufficient values 11177 class ValueError extends Error { 11178 } 11179 exports.ValueError = ValueError; 11180 // An error with a repository's state, such as a missing file. 11181 // It covers all exceptions that come from the repository side when 11182 // looking from the perspective of users of metadata API or ngclient. 11183 class RepositoryError extends Error { 11184 } 11185 exports.RepositoryError = RepositoryError; 11186 // An error about metadata object with insufficient threshold of signatures. 11187 class UnsignedMetadataError extends RepositoryError { 11188 } 11189 exports.UnsignedMetadataError = UnsignedMetadataError; 11190 // An error while checking the length and hash values of an object. 11191 class LengthOrHashMismatchError extends RepositoryError { 11192 } 11193 exports.LengthOrHashMismatchError = LengthOrHashMismatchError; 11194 class CryptoError extends Error { 11195 } 11196 exports.CryptoError = CryptoError; 11197 class UnsupportedAlgorithmError extends CryptoError { 11198 } 11199 exports.UnsupportedAlgorithmError = UnsupportedAlgorithmError; 11200 11201 11202 /***/ }), 11203 11204 /***/ 1923: 11205 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11206 11207 "use strict"; 11208 11209 var __importDefault = (this && this.__importDefault) || function (mod) { 11210 return (mod && mod.__esModule) ? mod : { "default": mod }; 11211 }; 11212 Object.defineProperty(exports, "__esModule", ({ value: true })); 11213 exports.TargetFile = exports.MetaFile = void 0; 11214 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 11215 const util_1 = __importDefault(__nccwpck_require__(3837)); 11216 const error_1 = __nccwpck_require__(8448); 11217 const utils_1 = __nccwpck_require__(5688); 11218 // A container with information about a particular metadata file. 11219 // 11220 // This class is used for Timestamp and Snapshot metadata. 11221 class MetaFile { 11222 constructor(opts) { 11223 if (opts.version <= 0) { 11224 throw new error_1.ValueError('Metafile version must be at least 1'); 11225 } 11226 if (opts.length !== undefined) { 11227 validateLength(opts.length); 11228 } 11229 this.version = opts.version; 11230 this.length = opts.length; 11231 this.hashes = opts.hashes; 11232 this.unrecognizedFields = opts.unrecognizedFields || {}; 11233 } 11234 equals(other) { 11235 if (!(other instanceof MetaFile)) { 11236 return false; 11237 } 11238 return (this.version === other.version && 11239 this.length === other.length && 11240 util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && 11241 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11242 } 11243 verify(data) { 11244 // Verifies that the given data matches the expected length. 11245 if (this.length !== undefined) { 11246 if (data.length !== this.length) { 11247 throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${data.length}`); 11248 } 11249 } 11250 // Verifies that the given data matches the supplied hashes. 11251 if (this.hashes) { 11252 Object.entries(this.hashes).forEach(([key, value]) => { 11253 let hash; 11254 try { 11255 hash = crypto_1.default.createHash(key); 11256 } 11257 catch (e) { 11258 throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); 11259 } 11260 const observedHash = hash.update(data).digest('hex'); 11261 if (observedHash !== value) { 11262 throw new error_1.LengthOrHashMismatchError(`Expected hash ${value} but got ${observedHash}`); 11263 } 11264 }); 11265 } 11266 } 11267 toJSON() { 11268 const json = { 11269 version: this.version, 11270 ...this.unrecognizedFields, 11271 }; 11272 if (this.length !== undefined) { 11273 json.length = this.length; 11274 } 11275 if (this.hashes) { 11276 json.hashes = this.hashes; 11277 } 11278 return json; 11279 } 11280 static fromJSON(data) { 11281 const { version, length, hashes, ...rest } = data; 11282 if (typeof version !== 'number') { 11283 throw new TypeError('version must be a number'); 11284 } 11285 if (utils_1.guard.isDefined(length) && typeof length !== 'number') { 11286 throw new TypeError('length must be a number'); 11287 } 11288 if (utils_1.guard.isDefined(hashes) && !utils_1.guard.isStringRecord(hashes)) { 11289 throw new TypeError('hashes must be string keys and values'); 11290 } 11291 return new MetaFile({ 11292 version, 11293 length, 11294 hashes, 11295 unrecognizedFields: rest, 11296 }); 11297 } 11298 } 11299 exports.MetaFile = MetaFile; 11300 // Container for info about a particular target file. 11301 // 11302 // This class is used for Target metadata. 11303 class TargetFile { 11304 constructor(opts) { 11305 validateLength(opts.length); 11306 this.length = opts.length; 11307 this.path = opts.path; 11308 this.hashes = opts.hashes; 11309 this.unrecognizedFields = opts.unrecognizedFields || {}; 11310 } 11311 get custom() { 11312 const custom = this.unrecognizedFields['custom']; 11313 if (!custom || Array.isArray(custom) || !(typeof custom === 'object')) { 11314 return {}; 11315 } 11316 return custom; 11317 } 11318 equals(other) { 11319 if (!(other instanceof TargetFile)) { 11320 return false; 11321 } 11322 return (this.length === other.length && 11323 this.path === other.path && 11324 util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && 11325 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11326 } 11327 async verify(stream) { 11328 let observedLength = 0; 11329 // Create a digest for each hash algorithm 11330 const digests = Object.keys(this.hashes).reduce((acc, key) => { 11331 try { 11332 acc[key] = crypto_1.default.createHash(key); 11333 } 11334 catch (e) { 11335 throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); 11336 } 11337 return acc; 11338 }, {}); 11339 // Read stream chunk by chunk 11340 for await (const chunk of stream) { 11341 // Keep running tally of stream length 11342 observedLength += chunk.length; 11343 // Append chunk to each digest 11344 Object.values(digests).forEach((digest) => { 11345 digest.update(chunk); 11346 }); 11347 } 11348 // Verify length matches expected value 11349 if (observedLength !== this.length) { 11350 throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${observedLength}`); 11351 } 11352 // Verify each digest matches expected value 11353 Object.entries(digests).forEach(([key, value]) => { 11354 const expected = this.hashes[key]; 11355 const actual = value.digest('hex'); 11356 if (actual !== expected) { 11357 throw new error_1.LengthOrHashMismatchError(`Expected hash ${expected} but got ${actual}`); 11358 } 11359 }); 11360 } 11361 toJSON() { 11362 return { 11363 length: this.length, 11364 hashes: this.hashes, 11365 ...this.unrecognizedFields, 11366 }; 11367 } 11368 static fromJSON(path, data) { 11369 const { length, hashes, ...rest } = data; 11370 if (typeof length !== 'number') { 11371 throw new TypeError('length must be a number'); 11372 } 11373 if (!utils_1.guard.isStringRecord(hashes)) { 11374 throw new TypeError('hashes must have string keys and values'); 11375 } 11376 return new TargetFile({ 11377 length, 11378 path, 11379 hashes, 11380 unrecognizedFields: rest, 11381 }); 11382 } 11383 } 11384 exports.TargetFile = TargetFile; 11385 // Check that supplied length if valid 11386 function validateLength(length) { 11387 if (length < 0) { 11388 throw new error_1.ValueError('Length must be at least 0'); 11389 } 11390 } 11391 11392 11393 /***/ }), 11394 11395 /***/ 5833: 11396 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 11397 11398 "use strict"; 11399 11400 Object.defineProperty(exports, "__esModule", ({ value: true })); 11401 exports.Timestamp = exports.Targets = exports.Snapshot = exports.Signature = exports.Root = exports.Metadata = exports.Key = exports.TargetFile = exports.MetaFile = exports.ValueError = exports.MetadataKind = void 0; 11402 var base_1 = __nccwpck_require__(159); 11403 Object.defineProperty(exports, "MetadataKind", ({ enumerable: true, get: function () { return base_1.MetadataKind; } })); 11404 var error_1 = __nccwpck_require__(8448); 11405 Object.defineProperty(exports, "ValueError", ({ enumerable: true, get: function () { return error_1.ValueError; } })); 11406 var file_1 = __nccwpck_require__(1923); 11407 Object.defineProperty(exports, "MetaFile", ({ enumerable: true, get: function () { return file_1.MetaFile; } })); 11408 Object.defineProperty(exports, "TargetFile", ({ enumerable: true, get: function () { return file_1.TargetFile; } })); 11409 var key_1 = __nccwpck_require__(6697); 11410 Object.defineProperty(exports, "Key", ({ enumerable: true, get: function () { return key_1.Key; } })); 11411 var metadata_1 = __nccwpck_require__(1593); 11412 Object.defineProperty(exports, "Metadata", ({ enumerable: true, get: function () { return metadata_1.Metadata; } })); 11413 var root_1 = __nccwpck_require__(9392); 11414 Object.defineProperty(exports, "Root", ({ enumerable: true, get: function () { return root_1.Root; } })); 11415 var signature_1 = __nccwpck_require__(4222); 11416 Object.defineProperty(exports, "Signature", ({ enumerable: true, get: function () { return signature_1.Signature; } })); 11417 var snapshot_1 = __nccwpck_require__(2326); 11418 Object.defineProperty(exports, "Snapshot", ({ enumerable: true, get: function () { return snapshot_1.Snapshot; } })); 11419 var targets_1 = __nccwpck_require__(5799); 11420 Object.defineProperty(exports, "Targets", ({ enumerable: true, get: function () { return targets_1.Targets; } })); 11421 var timestamp_1 = __nccwpck_require__(4042); 11422 Object.defineProperty(exports, "Timestamp", ({ enumerable: true, get: function () { return timestamp_1.Timestamp; } })); 11423 11424 11425 /***/ }), 11426 11427 /***/ 6697: 11428 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11429 11430 "use strict"; 11431 11432 var __importDefault = (this && this.__importDefault) || function (mod) { 11433 return (mod && mod.__esModule) ? mod : { "default": mod }; 11434 }; 11435 Object.defineProperty(exports, "__esModule", ({ value: true })); 11436 exports.Key = void 0; 11437 const util_1 = __importDefault(__nccwpck_require__(3837)); 11438 const error_1 = __nccwpck_require__(8448); 11439 const utils_1 = __nccwpck_require__(5688); 11440 const key_1 = __nccwpck_require__(8725); 11441 // A container class representing the public portion of a Key. 11442 class Key { 11443 constructor(options) { 11444 const { keyID, keyType, scheme, keyVal, unrecognizedFields } = options; 11445 this.keyID = keyID; 11446 this.keyType = keyType; 11447 this.scheme = scheme; 11448 this.keyVal = keyVal; 11449 this.unrecognizedFields = unrecognizedFields || {}; 11450 } 11451 // Verifies the that the metadata.signatures contains a signature made with 11452 // this key and is correctly signed. 11453 verifySignature(metadata) { 11454 const signature = metadata.signatures[this.keyID]; 11455 if (!signature) 11456 throw new error_1.UnsignedMetadataError('no signature for key found in metadata'); 11457 if (!this.keyVal.public) 11458 throw new error_1.UnsignedMetadataError('no public key found'); 11459 const publicKey = (0, key_1.getPublicKey)({ 11460 keyType: this.keyType, 11461 scheme: this.scheme, 11462 keyVal: this.keyVal.public, 11463 }); 11464 const signedData = metadata.signed.toJSON(); 11465 try { 11466 if (!utils_1.crypto.verifySignature(signedData, publicKey, signature.sig)) { 11467 throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); 11468 } 11469 } 11470 catch (error) { 11471 if (error instanceof error_1.UnsignedMetadataError) { 11472 throw error; 11473 } 11474 throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); 11475 } 11476 } 11477 equals(other) { 11478 if (!(other instanceof Key)) { 11479 return false; 11480 } 11481 return (this.keyID === other.keyID && 11482 this.keyType === other.keyType && 11483 this.scheme === other.scheme && 11484 util_1.default.isDeepStrictEqual(this.keyVal, other.keyVal) && 11485 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11486 } 11487 toJSON() { 11488 return { 11489 keytype: this.keyType, 11490 scheme: this.scheme, 11491 keyval: this.keyVal, 11492 ...this.unrecognizedFields, 11493 }; 11494 } 11495 static fromJSON(keyID, data) { 11496 const { keytype, scheme, keyval, ...rest } = data; 11497 if (typeof keytype !== 'string') { 11498 throw new TypeError('keytype must be a string'); 11499 } 11500 if (typeof scheme !== 'string') { 11501 throw new TypeError('scheme must be a string'); 11502 } 11503 if (!utils_1.guard.isStringRecord(keyval)) { 11504 throw new TypeError('keyval must be a string record'); 11505 } 11506 return new Key({ 11507 keyID, 11508 keyType: keytype, 11509 scheme, 11510 keyVal: keyval, 11511 unrecognizedFields: rest, 11512 }); 11513 } 11514 } 11515 exports.Key = Key; 11516 11517 11518 /***/ }), 11519 11520 /***/ 1593: 11521 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11522 11523 "use strict"; 11524 11525 var __importDefault = (this && this.__importDefault) || function (mod) { 11526 return (mod && mod.__esModule) ? mod : { "default": mod }; 11527 }; 11528 Object.defineProperty(exports, "__esModule", ({ value: true })); 11529 exports.Metadata = void 0; 11530 const canonical_json_1 = __nccwpck_require__(9652); 11531 const util_1 = __importDefault(__nccwpck_require__(3837)); 11532 const base_1 = __nccwpck_require__(159); 11533 const error_1 = __nccwpck_require__(8448); 11534 const root_1 = __nccwpck_require__(9392); 11535 const signature_1 = __nccwpck_require__(4222); 11536 const snapshot_1 = __nccwpck_require__(2326); 11537 const targets_1 = __nccwpck_require__(5799); 11538 const timestamp_1 = __nccwpck_require__(4042); 11539 const utils_1 = __nccwpck_require__(5688); 11540 /*** 11541 * A container for signed TUF metadata. 11542 * 11543 * Provides methods to convert to and from json, read and write to and 11544 * from JSON and to create and verify metadata signatures. 11545 * 11546 * ``Metadata[T]`` is a generic container type where T can be any one type of 11547 * [``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this 11548 * is to allow static type checking of the signed attribute in code using 11549 * Metadata:: 11550 * 11551 * root_md = Metadata[Root].fromJSON("root.json") 11552 * # root_md type is now Metadata[Root]. This means signed and its 11553 * # attributes like consistent_snapshot are now statically typed and the 11554 * # types can be verified by static type checkers and shown by IDEs 11555 * 11556 * Using a type constraint is not required but not doing so means T is not a 11557 * specific type so static typing cannot happen. Note that the type constraint 11558 * ``[Root]`` is not validated at runtime (as pure annotations are not available 11559 * then). 11560 * 11561 * Apart from ``expires`` all of the arguments to the inner constructors have 11562 * reasonable default values for new metadata. 11563 */ 11564 class Metadata { 11565 constructor(signed, signatures, unrecognizedFields) { 11566 this.signed = signed; 11567 this.signatures = signatures || {}; 11568 this.unrecognizedFields = unrecognizedFields || {}; 11569 } 11570 sign(signer, append = true) { 11571 const bytes = Buffer.from((0, canonical_json_1.canonicalize)(this.signed.toJSON())); 11572 const signature = signer(bytes); 11573 if (!append) { 11574 this.signatures = {}; 11575 } 11576 this.signatures[signature.keyID] = signature; 11577 } 11578 verifyDelegate(delegatedRole, delegatedMetadata) { 11579 let role; 11580 let keys = {}; 11581 switch (this.signed.type) { 11582 case base_1.MetadataKind.Root: 11583 keys = this.signed.keys; 11584 role = this.signed.roles[delegatedRole]; 11585 break; 11586 case base_1.MetadataKind.Targets: 11587 if (!this.signed.delegations) { 11588 throw new error_1.ValueError(`No delegations found for ${delegatedRole}`); 11589 } 11590 keys = this.signed.delegations.keys; 11591 if (this.signed.delegations.roles) { 11592 role = this.signed.delegations.roles[delegatedRole]; 11593 } 11594 else if (this.signed.delegations.succinctRoles) { 11595 if (this.signed.delegations.succinctRoles.isDelegatedRole(delegatedRole)) { 11596 role = this.signed.delegations.succinctRoles; 11597 } 11598 } 11599 break; 11600 default: 11601 throw new TypeError('invalid metadata type'); 11602 } 11603 if (!role) { 11604 throw new error_1.ValueError(`no delegation found for ${delegatedRole}`); 11605 } 11606 const signingKeys = new Set(); 11607 role.keyIDs.forEach((keyID) => { 11608 const key = keys[keyID]; 11609 // If we dont' have the key, continue checking other keys 11610 if (!key) { 11611 return; 11612 } 11613 try { 11614 key.verifySignature(delegatedMetadata); 11615 signingKeys.add(key.keyID); 11616 } 11617 catch (error) { 11618 // continue 11619 } 11620 }); 11621 if (signingKeys.size < role.threshold) { 11622 throw new error_1.UnsignedMetadataError(`${delegatedRole} was signed by ${signingKeys.size}/${role.threshold} keys`); 11623 } 11624 } 11625 equals(other) { 11626 if (!(other instanceof Metadata)) { 11627 return false; 11628 } 11629 return (this.signed.equals(other.signed) && 11630 util_1.default.isDeepStrictEqual(this.signatures, other.signatures) && 11631 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11632 } 11633 toJSON() { 11634 const signatures = Object.values(this.signatures).map((signature) => { 11635 return signature.toJSON(); 11636 }); 11637 return { 11638 signatures, 11639 signed: this.signed.toJSON(), 11640 ...this.unrecognizedFields, 11641 }; 11642 } 11643 static fromJSON(type, data) { 11644 const { signed, signatures, ...rest } = data; 11645 if (!utils_1.guard.isDefined(signed) || !utils_1.guard.isObject(signed)) { 11646 throw new TypeError('signed is not defined'); 11647 } 11648 if (type !== signed._type) { 11649 throw new error_1.ValueError(`expected '${type}', got ${signed['_type']}`); 11650 } 11651 let signedObj; 11652 switch (type) { 11653 case base_1.MetadataKind.Root: 11654 signedObj = root_1.Root.fromJSON(signed); 11655 break; 11656 case base_1.MetadataKind.Timestamp: 11657 signedObj = timestamp_1.Timestamp.fromJSON(signed); 11658 break; 11659 case base_1.MetadataKind.Snapshot: 11660 signedObj = snapshot_1.Snapshot.fromJSON(signed); 11661 break; 11662 case base_1.MetadataKind.Targets: 11663 signedObj = targets_1.Targets.fromJSON(signed); 11664 break; 11665 default: 11666 throw new TypeError('invalid metadata type'); 11667 } 11668 const sigMap = signaturesFromJSON(signatures); 11669 return new Metadata(signedObj, sigMap, rest); 11670 } 11671 } 11672 exports.Metadata = Metadata; 11673 function signaturesFromJSON(data) { 11674 if (!utils_1.guard.isObjectArray(data)) { 11675 throw new TypeError('signatures is not an array'); 11676 } 11677 return data.reduce((acc, sigData) => { 11678 const signature = signature_1.Signature.fromJSON(sigData); 11679 return { ...acc, [signature.keyID]: signature }; 11680 }, {}); 11681 } 11682 11683 11684 /***/ }), 11685 11686 /***/ 9393: 11687 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11688 11689 "use strict"; 11690 11691 var __importDefault = (this && this.__importDefault) || function (mod) { 11692 return (mod && mod.__esModule) ? mod : { "default": mod }; 11693 }; 11694 Object.defineProperty(exports, "__esModule", ({ value: true })); 11695 exports.SuccinctRoles = exports.DelegatedRole = exports.Role = exports.TOP_LEVEL_ROLE_NAMES = void 0; 11696 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 11697 const minimatch_1 = __nccwpck_require__(4878); 11698 const util_1 = __importDefault(__nccwpck_require__(3837)); 11699 const error_1 = __nccwpck_require__(8448); 11700 const utils_1 = __nccwpck_require__(5688); 11701 exports.TOP_LEVEL_ROLE_NAMES = [ 11702 'root', 11703 'targets', 11704 'snapshot', 11705 'timestamp', 11706 ]; 11707 /** 11708 * Container that defines which keys are required to sign roles metadata. 11709 * 11710 * Role defines how many keys are required to successfully sign the roles 11711 * metadata, and which keys are accepted. 11712 */ 11713 class Role { 11714 constructor(options) { 11715 const { keyIDs, threshold, unrecognizedFields } = options; 11716 if (hasDuplicates(keyIDs)) { 11717 throw new error_1.ValueError('duplicate key IDs found'); 11718 } 11719 if (threshold < 1) { 11720 throw new error_1.ValueError('threshold must be at least 1'); 11721 } 11722 this.keyIDs = keyIDs; 11723 this.threshold = threshold; 11724 this.unrecognizedFields = unrecognizedFields || {}; 11725 } 11726 equals(other) { 11727 if (!(other instanceof Role)) { 11728 return false; 11729 } 11730 return (this.threshold === other.threshold && 11731 util_1.default.isDeepStrictEqual(this.keyIDs, other.keyIDs) && 11732 util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); 11733 } 11734 toJSON() { 11735 return { 11736 keyids: this.keyIDs, 11737 threshold: this.threshold, 11738 ...this.unrecognizedFields, 11739 }; 11740 } 11741 static fromJSON(data) { 11742 const { keyids, threshold, ...rest } = data; 11743 if (!utils_1.guard.isStringArray(keyids)) { 11744 throw new TypeError('keyids must be an array'); 11745 } 11746 if (typeof threshold !== 'number') { 11747 throw new TypeError('threshold must be a number'); 11748 } 11749 return new Role({ 11750 keyIDs: keyids, 11751 threshold, 11752 unrecognizedFields: rest, 11753 }); 11754 } 11755 } 11756 exports.Role = Role; 11757 function hasDuplicates(array) { 11758 return new Set(array).size !== array.length; 11759 } 11760 /** 11761 * A container with information about a delegated role. 11762 * 11763 * A delegation can happen in two ways: 11764 * - ``paths`` is set: delegates targets matching any path pattern in ``paths`` 11765 * - ``pathHashPrefixes`` is set: delegates targets whose target path hash 11766 * starts with any of the prefixes in ``pathHashPrefixes`` 11767 * 11768 * ``paths`` and ``pathHashPrefixes`` are mutually exclusive: both cannot be 11769 * set, at least one of them must be set. 11770 */ 11771 class DelegatedRole extends Role { 11772 constructor(opts) { 11773 super(opts); 11774 const { name, terminating, paths, pathHashPrefixes } = opts; 11775 this.name = name; 11776 this.terminating = terminating; 11777 if (opts.paths && opts.pathHashPrefixes) { 11778 throw new error_1.ValueError('paths and pathHashPrefixes are mutually exclusive'); 11779 } 11780 this.paths = paths; 11781 this.pathHashPrefixes = pathHashPrefixes; 11782 } 11783 equals(other) { 11784 if (!(other instanceof DelegatedRole)) { 11785 return false; 11786 } 11787 return (super.equals(other) && 11788 this.name === other.name && 11789 this.terminating === other.terminating && 11790 util_1.default.isDeepStrictEqual(this.paths, other.paths) && 11791 util_1.default.isDeepStrictEqual(this.pathHashPrefixes, other.pathHashPrefixes)); 11792 } 11793 isDelegatedPath(targetFilepath) { 11794 if (this.paths) { 11795 return this.paths.some((pathPattern) => isTargetInPathPattern(targetFilepath, pathPattern)); 11796 } 11797 if (this.pathHashPrefixes) { 11798 const hasher = crypto_1.default.createHash('sha256'); 11799 const pathHash = hasher.update(targetFilepath).digest('hex'); 11800 return this.pathHashPrefixes.some((pathHashPrefix) => pathHash.startsWith(pathHashPrefix)); 11801 } 11802 return false; 11803 } 11804 toJSON() { 11805 const json = { 11806 ...super.toJSON(), 11807 name: this.name, 11808 terminating: this.terminating, 11809 }; 11810 if (this.paths) { 11811 json.paths = this.paths; 11812 } 11813 if (this.pathHashPrefixes) { 11814 json.path_hash_prefixes = this.pathHashPrefixes; 11815 } 11816 return json; 11817 } 11818 static fromJSON(data) { 11819 const { keyids, threshold, name, terminating, paths, path_hash_prefixes, ...rest } = data; 11820 if (!utils_1.guard.isStringArray(keyids)) { 11821 throw new TypeError('keyids must be an array of strings'); 11822 } 11823 if (typeof threshold !== 'number') { 11824 throw new TypeError('threshold must be a number'); 11825 } 11826 if (typeof name !== 'string') { 11827 throw new TypeError('name must be a string'); 11828 } 11829 if (typeof terminating !== 'boolean') { 11830 throw new TypeError('terminating must be a boolean'); 11831 } 11832 if (utils_1.guard.isDefined(paths) && !utils_1.guard.isStringArray(paths)) { 11833 throw new TypeError('paths must be an array of strings'); 11834 } 11835 if (utils_1.guard.isDefined(path_hash_prefixes) && 11836 !utils_1.guard.isStringArray(path_hash_prefixes)) { 11837 throw new TypeError('path_hash_prefixes must be an array of strings'); 11838 } 11839 return new DelegatedRole({ 11840 keyIDs: keyids, 11841 threshold, 11842 name, 11843 terminating, 11844 paths, 11845 pathHashPrefixes: path_hash_prefixes, 11846 unrecognizedFields: rest, 11847 }); 11848 } 11849 } 11850 exports.DelegatedRole = DelegatedRole; 11851 // JS version of Ruby's Array#zip 11852 const zip = (a, b) => a.map((k, i) => [k, b[i]]); 11853 function isTargetInPathPattern(target, pattern) { 11854 const targetParts = target.split('/'); 11855 const patternParts = pattern.split('/'); 11856 if (patternParts.length != targetParts.length) { 11857 return false; 11858 } 11859 return zip(targetParts, patternParts).every(([targetPart, patternPart]) => (0, minimatch_1.minimatch)(targetPart, patternPart)); 11860 } 11861 /** 11862 * Succinctly defines a hash bin delegation graph. 11863 * 11864 * A ``SuccinctRoles`` object describes a delegation graph that covers all 11865 * targets, distributing them uniformly over the delegated roles (i.e. bins) 11866 * in the graph. 11867 * 11868 * The total number of bins is 2 to the power of the passed ``bit_length``. 11869 * 11870 * Bin names are the concatenation of the passed ``name_prefix`` and a 11871 * zero-padded hex representation of the bin index separated by a hyphen. 11872 * 11873 * The passed ``keyids`` and ``threshold`` is used for each bin, and each bin 11874 * is 'terminating'. 11875 * 11876 * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md 11877 */ 11878 class SuccinctRoles extends Role { 11879 constructor(opts) { 11880 super(opts); 11881 const { bitLength, namePrefix } = opts; 11882 if (bitLength <= 0 || bitLength > 32) { 11883 throw new error_1.ValueError('bitLength must be between 1 and 32'); 11884 } 11885 this.bitLength = bitLength; 11886 this.namePrefix = namePrefix; 11887 // Calculate the suffix_len value based on the total number of bins in 11888 // hex. If bit_length = 10 then number_of_bins = 1024 or bin names will 11889 // have a suffix between "000" and "3ff" in hex and suffix_len will be 3 11890 // meaning the third bin will have a suffix of "003". 11891 this.numberOfBins = Math.pow(2, bitLength); 11892 // suffix_len is calculated based on "number_of_bins - 1" as the name 11893 // of the last bin contains the number "number_of_bins -1" as a suffix. 11894 this.suffixLen = (this.numberOfBins - 1).toString(16).length; 11895 } 11896 equals(other) { 11897 if (!(other instanceof SuccinctRoles)) { 11898 return false; 11899 } 11900 return (super.equals(other) && 11901 this.bitLength === other.bitLength && 11902 this.namePrefix === other.namePrefix); 11903 } 11904 /*** 11905 * Calculates the name of the delegated role responsible for 'target_filepath'. 11906 * 11907 * The target at path ''target_filepath' is assigned to a bin by casting 11908 * the left-most 'bit_length' of bits of the file path hash digest to 11909 * int, using it as bin index between 0 and '2**bit_length - 1'. 11910 * 11911 * Args: 11912 * target_filepath: URL path to a target file, relative to a base 11913 * targets URL. 11914 */ 11915 getRoleForTarget(targetFilepath) { 11916 const hasher = crypto_1.default.createHash('sha256'); 11917 const hasherBuffer = hasher.update(targetFilepath).digest(); 11918 // can't ever need more than 4 bytes (32 bits). 11919 const hashBytes = hasherBuffer.subarray(0, 4); 11920 // Right shift hash bytes, so that we only have the leftmost 11921 // bit_length bits that we care about. 11922 const shiftValue = 32 - this.bitLength; 11923 const binNumber = hashBytes.readUInt32BE() >>> shiftValue; 11924 // Add zero padding if necessary and cast to hex the suffix. 11925 const suffix = binNumber.toString(16).padStart(this.suffixLen, '0'); 11926 return `${this.namePrefix}-${suffix}`; 11927 } 11928 *getRoles() { 11929 for (let i = 0; i < this.numberOfBins; i++) { 11930 const suffix = i.toString(16).padStart(this.suffixLen, '0'); 11931 yield `${this.namePrefix}-${suffix}`; 11932 } 11933 } 11934 /*** 11935 * Determines whether the given ``role_name`` is in one of 11936 * the delegated roles that ``SuccinctRoles`` represents. 11937 * 11938 * Args: 11939 * role_name: The name of the role to check against. 11940 */ 11941 isDelegatedRole(roleName) { 11942 const desiredPrefix = this.namePrefix + '-'; 11943 if (!roleName.startsWith(desiredPrefix)) { 11944 return false; 11945 } 11946 const suffix = roleName.slice(desiredPrefix.length, roleName.length); 11947 if (suffix.length != this.suffixLen) { 11948 return false; 11949 } 11950 // make sure the suffix is a hex string 11951 if (!suffix.match(/^[0-9a-fA-F]+$/)) { 11952 return false; 11953 } 11954 const num = parseInt(suffix, 16); 11955 return 0 <= num && num < this.numberOfBins; 11956 } 11957 toJSON() { 11958 const json = { 11959 ...super.toJSON(), 11960 bit_length: this.bitLength, 11961 name_prefix: this.namePrefix, 11962 }; 11963 return json; 11964 } 11965 static fromJSON(data) { 11966 const { keyids, threshold, bit_length, name_prefix, ...rest } = data; 11967 if (!utils_1.guard.isStringArray(keyids)) { 11968 throw new TypeError('keyids must be an array of strings'); 11969 } 11970 if (typeof threshold !== 'number') { 11971 throw new TypeError('threshold must be a number'); 11972 } 11973 if (typeof bit_length !== 'number') { 11974 throw new TypeError('bit_length must be a number'); 11975 } 11976 if (typeof name_prefix !== 'string') { 11977 throw new TypeError('name_prefix must be a string'); 11978 } 11979 return new SuccinctRoles({ 11980 keyIDs: keyids, 11981 threshold, 11982 bitLength: bit_length, 11983 namePrefix: name_prefix, 11984 unrecognizedFields: rest, 11985 }); 11986 } 11987 } 11988 exports.SuccinctRoles = SuccinctRoles; 11989 11990 11991 /***/ }), 11992 11993 /***/ 9392: 11994 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 11995 11996 "use strict"; 11997 11998 var __importDefault = (this && this.__importDefault) || function (mod) { 11999 return (mod && mod.__esModule) ? mod : { "default": mod }; 12000 }; 12001 Object.defineProperty(exports, "__esModule", ({ value: true })); 12002 exports.Root = void 0; 12003 const util_1 = __importDefault(__nccwpck_require__(3837)); 12004 const base_1 = __nccwpck_require__(159); 12005 const error_1 = __nccwpck_require__(8448); 12006 const key_1 = __nccwpck_require__(6697); 12007 const role_1 = __nccwpck_require__(9393); 12008 const utils_1 = __nccwpck_require__(5688); 12009 /** 12010 * A container for the signed part of root metadata. 12011 * 12012 * The top-level role and metadata file signed by the root keys. 12013 * This role specifies trusted keys for all other top-level roles, which may further delegate trust. 12014 */ 12015 class Root extends base_1.Signed { 12016 constructor(options) { 12017 super(options); 12018 this.type = base_1.MetadataKind.Root; 12019 this.keys = options.keys || {}; 12020 this.consistentSnapshot = options.consistentSnapshot ?? true; 12021 if (!options.roles) { 12022 this.roles = role_1.TOP_LEVEL_ROLE_NAMES.reduce((acc, role) => ({ 12023 ...acc, 12024 [role]: new role_1.Role({ keyIDs: [], threshold: 1 }), 12025 }), {}); 12026 } 12027 else { 12028 const roleNames = new Set(Object.keys(options.roles)); 12029 if (!role_1.TOP_LEVEL_ROLE_NAMES.every((role) => roleNames.has(role))) { 12030 throw new error_1.ValueError('missing top-level role'); 12031 } 12032 this.roles = options.roles; 12033 } 12034 } 12035 addKey(key, role) { 12036 if (!this.roles[role]) { 12037 throw new error_1.ValueError(`role ${role} does not exist`); 12038 } 12039 if (!this.roles[role].keyIDs.includes(key.keyID)) { 12040 this.roles[role].keyIDs.push(key.keyID); 12041 } 12042 this.keys[key.keyID] = key; 12043 } 12044 equals(other) { 12045 if (!(other instanceof Root)) { 12046 return false; 12047 } 12048 return (super.equals(other) && 12049 this.consistentSnapshot === other.consistentSnapshot && 12050 util_1.default.isDeepStrictEqual(this.keys, other.keys) && 12051 util_1.default.isDeepStrictEqual(this.roles, other.roles)); 12052 } 12053 toJSON() { 12054 return { 12055 _type: this.type, 12056 spec_version: this.specVersion, 12057 version: this.version, 12058 expires: this.expires, 12059 keys: keysToJSON(this.keys), 12060 roles: rolesToJSON(this.roles), 12061 consistent_snapshot: this.consistentSnapshot, 12062 ...this.unrecognizedFields, 12063 }; 12064 } 12065 static fromJSON(data) { 12066 const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); 12067 const { keys, roles, consistent_snapshot, ...rest } = unrecognizedFields; 12068 if (typeof consistent_snapshot !== 'boolean') { 12069 throw new TypeError('consistent_snapshot must be a boolean'); 12070 } 12071 return new Root({ 12072 ...commonFields, 12073 keys: keysFromJSON(keys), 12074 roles: rolesFromJSON(roles), 12075 consistentSnapshot: consistent_snapshot, 12076 unrecognizedFields: rest, 12077 }); 12078 } 12079 } 12080 exports.Root = Root; 12081 function keysToJSON(keys) { 12082 return Object.entries(keys).reduce((acc, [keyID, key]) => ({ ...acc, [keyID]: key.toJSON() }), {}); 12083 } 12084 function rolesToJSON(roles) { 12085 return Object.entries(roles).reduce((acc, [roleName, role]) => ({ ...acc, [roleName]: role.toJSON() }), {}); 12086 } 12087 function keysFromJSON(data) { 12088 let keys; 12089 if (utils_1.guard.isDefined(data)) { 12090 if (!utils_1.guard.isObjectRecord(data)) { 12091 throw new TypeError('keys must be an object'); 12092 } 12093 keys = Object.entries(data).reduce((acc, [keyID, keyData]) => ({ 12094 ...acc, 12095 [keyID]: key_1.Key.fromJSON(keyID, keyData), 12096 }), {}); 12097 } 12098 return keys; 12099 } 12100 function rolesFromJSON(data) { 12101 let roles; 12102 if (utils_1.guard.isDefined(data)) { 12103 if (!utils_1.guard.isObjectRecord(data)) { 12104 throw new TypeError('roles must be an object'); 12105 } 12106 roles = Object.entries(data).reduce((acc, [roleName, roleData]) => ({ 12107 ...acc, 12108 [roleName]: role_1.Role.fromJSON(roleData), 12109 }), {}); 12110 } 12111 return roles; 12112 } 12113 12114 12115 /***/ }), 12116 12117 /***/ 4222: 12118 /***/ ((__unused_webpack_module, exports) => { 12119 12120 "use strict"; 12121 12122 Object.defineProperty(exports, "__esModule", ({ value: true })); 12123 exports.Signature = void 0; 12124 /** 12125 * A container class containing information about a signature. 12126 * 12127 * Contains a signature and the keyid uniquely identifying the key used 12128 * to generate the signature. 12129 * 12130 * Provide a `fromJSON` method to create a Signature from a JSON object. 12131 */ 12132 class Signature { 12133 constructor(options) { 12134 const { keyID, sig } = options; 12135 this.keyID = keyID; 12136 this.sig = sig; 12137 } 12138 toJSON() { 12139 return { 12140 keyid: this.keyID, 12141 sig: this.sig, 12142 }; 12143 } 12144 static fromJSON(data) { 12145 const { keyid, sig } = data; 12146 if (typeof keyid !== 'string') { 12147 throw new TypeError('keyid must be a string'); 12148 } 12149 if (typeof sig !== 'string') { 12150 throw new TypeError('sig must be a string'); 12151 } 12152 return new Signature({ 12153 keyID: keyid, 12154 sig: sig, 12155 }); 12156 } 12157 } 12158 exports.Signature = Signature; 12159 12160 12161 /***/ }), 12162 12163 /***/ 2326: 12164 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12165 12166 "use strict"; 12167 12168 var __importDefault = (this && this.__importDefault) || function (mod) { 12169 return (mod && mod.__esModule) ? mod : { "default": mod }; 12170 }; 12171 Object.defineProperty(exports, "__esModule", ({ value: true })); 12172 exports.Snapshot = void 0; 12173 const util_1 = __importDefault(__nccwpck_require__(3837)); 12174 const base_1 = __nccwpck_require__(159); 12175 const file_1 = __nccwpck_require__(1923); 12176 const utils_1 = __nccwpck_require__(5688); 12177 /** 12178 * A container for the signed part of snapshot metadata. 12179 * 12180 * Snapshot contains information about all target Metadata files. 12181 * A top-level role that specifies the latest versions of all targets metadata files, 12182 * and hence the latest versions of all targets (including any dependencies between them) on the repository. 12183 */ 12184 class Snapshot extends base_1.Signed { 12185 constructor(opts) { 12186 super(opts); 12187 this.type = base_1.MetadataKind.Snapshot; 12188 this.meta = opts.meta || { 'targets.json': new file_1.MetaFile({ version: 1 }) }; 12189 } 12190 equals(other) { 12191 if (!(other instanceof Snapshot)) { 12192 return false; 12193 } 12194 return super.equals(other) && util_1.default.isDeepStrictEqual(this.meta, other.meta); 12195 } 12196 toJSON() { 12197 return { 12198 _type: this.type, 12199 meta: metaToJSON(this.meta), 12200 spec_version: this.specVersion, 12201 version: this.version, 12202 expires: this.expires, 12203 ...this.unrecognizedFields, 12204 }; 12205 } 12206 static fromJSON(data) { 12207 const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); 12208 const { meta, ...rest } = unrecognizedFields; 12209 return new Snapshot({ 12210 ...commonFields, 12211 meta: metaFromJSON(meta), 12212 unrecognizedFields: rest, 12213 }); 12214 } 12215 } 12216 exports.Snapshot = Snapshot; 12217 function metaToJSON(meta) { 12218 return Object.entries(meta).reduce((acc, [path, metadata]) => ({ 12219 ...acc, 12220 [path]: metadata.toJSON(), 12221 }), {}); 12222 } 12223 function metaFromJSON(data) { 12224 let meta; 12225 if (utils_1.guard.isDefined(data)) { 12226 if (!utils_1.guard.isObjectRecord(data)) { 12227 throw new TypeError('meta field is malformed'); 12228 } 12229 else { 12230 meta = Object.entries(data).reduce((acc, [path, metadata]) => ({ 12231 ...acc, 12232 [path]: file_1.MetaFile.fromJSON(metadata), 12233 }), {}); 12234 } 12235 } 12236 return meta; 12237 } 12238 12239 12240 /***/ }), 12241 12242 /***/ 5799: 12243 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12244 12245 "use strict"; 12246 12247 var __importDefault = (this && this.__importDefault) || function (mod) { 12248 return (mod && mod.__esModule) ? mod : { "default": mod }; 12249 }; 12250 Object.defineProperty(exports, "__esModule", ({ value: true })); 12251 exports.Targets = void 0; 12252 const util_1 = __importDefault(__nccwpck_require__(3837)); 12253 const base_1 = __nccwpck_require__(159); 12254 const delegations_1 = __nccwpck_require__(1662); 12255 const file_1 = __nccwpck_require__(1923); 12256 const utils_1 = __nccwpck_require__(5688); 12257 // Container for the signed part of targets metadata. 12258 // 12259 // Targets contains verifying information about target files and also delegates 12260 // responsible to other Targets roles. 12261 class Targets extends base_1.Signed { 12262 constructor(options) { 12263 super(options); 12264 this.type = base_1.MetadataKind.Targets; 12265 this.targets = options.targets || {}; 12266 this.delegations = options.delegations; 12267 } 12268 addTarget(target) { 12269 this.targets[target.path] = target; 12270 } 12271 equals(other) { 12272 if (!(other instanceof Targets)) { 12273 return false; 12274 } 12275 return (super.equals(other) && 12276 util_1.default.isDeepStrictEqual(this.targets, other.targets) && 12277 util_1.default.isDeepStrictEqual(this.delegations, other.delegations)); 12278 } 12279 toJSON() { 12280 const json = { 12281 _type: this.type, 12282 spec_version: this.specVersion, 12283 version: this.version, 12284 expires: this.expires, 12285 targets: targetsToJSON(this.targets), 12286 ...this.unrecognizedFields, 12287 }; 12288 if (this.delegations) { 12289 json.delegations = this.delegations.toJSON(); 12290 } 12291 return json; 12292 } 12293 static fromJSON(data) { 12294 const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); 12295 const { targets, delegations, ...rest } = unrecognizedFields; 12296 return new Targets({ 12297 ...commonFields, 12298 targets: targetsFromJSON(targets), 12299 delegations: delegationsFromJSON(delegations), 12300 unrecognizedFields: rest, 12301 }); 12302 } 12303 } 12304 exports.Targets = Targets; 12305 function targetsToJSON(targets) { 12306 return Object.entries(targets).reduce((acc, [path, target]) => ({ 12307 ...acc, 12308 [path]: target.toJSON(), 12309 }), {}); 12310 } 12311 function targetsFromJSON(data) { 12312 let targets; 12313 if (utils_1.guard.isDefined(data)) { 12314 if (!utils_1.guard.isObjectRecord(data)) { 12315 throw new TypeError('targets must be an object'); 12316 } 12317 else { 12318 targets = Object.entries(data).reduce((acc, [path, target]) => ({ 12319 ...acc, 12320 [path]: file_1.TargetFile.fromJSON(path, target), 12321 }), {}); 12322 } 12323 } 12324 return targets; 12325 } 12326 function delegationsFromJSON(data) { 12327 let delegations; 12328 if (utils_1.guard.isDefined(data)) { 12329 if (!utils_1.guard.isObject(data)) { 12330 throw new TypeError('delegations must be an object'); 12331 } 12332 else { 12333 delegations = delegations_1.Delegations.fromJSON(data); 12334 } 12335 } 12336 return delegations; 12337 } 12338 12339 12340 /***/ }), 12341 12342 /***/ 4042: 12343 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 12344 12345 "use strict"; 12346 12347 Object.defineProperty(exports, "__esModule", ({ value: true })); 12348 exports.Timestamp = void 0; 12349 const base_1 = __nccwpck_require__(159); 12350 const file_1 = __nccwpck_require__(1923); 12351 const utils_1 = __nccwpck_require__(5688); 12352 /** 12353 * A container for the signed part of timestamp metadata. 12354 * 12355 * A top-level that specifies the latest version of the snapshot role metadata file, 12356 * and hence the latest versions of all metadata and targets on the repository. 12357 */ 12358 class Timestamp extends base_1.Signed { 12359 constructor(options) { 12360 super(options); 12361 this.type = base_1.MetadataKind.Timestamp; 12362 this.snapshotMeta = options.snapshotMeta || new file_1.MetaFile({ version: 1 }); 12363 } 12364 equals(other) { 12365 if (!(other instanceof Timestamp)) { 12366 return false; 12367 } 12368 return super.equals(other) && this.snapshotMeta.equals(other.snapshotMeta); 12369 } 12370 toJSON() { 12371 return { 12372 _type: this.type, 12373 spec_version: this.specVersion, 12374 version: this.version, 12375 expires: this.expires, 12376 meta: { 'snapshot.json': this.snapshotMeta.toJSON() }, 12377 ...this.unrecognizedFields, 12378 }; 12379 } 12380 static fromJSON(data) { 12381 const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); 12382 const { meta, ...rest } = unrecognizedFields; 12383 return new Timestamp({ 12384 ...commonFields, 12385 snapshotMeta: snapshotMetaFromJSON(meta), 12386 unrecognizedFields: rest, 12387 }); 12388 } 12389 } 12390 exports.Timestamp = Timestamp; 12391 function snapshotMetaFromJSON(data) { 12392 let snapshotMeta; 12393 if (utils_1.guard.isDefined(data)) { 12394 const snapshotData = data['snapshot.json']; 12395 if (!utils_1.guard.isDefined(snapshotData) || !utils_1.guard.isObject(snapshotData)) { 12396 throw new TypeError('missing snapshot.json in meta'); 12397 } 12398 else { 12399 snapshotMeta = file_1.MetaFile.fromJSON(snapshotData); 12400 } 12401 } 12402 return snapshotMeta; 12403 } 12404 12405 12406 /***/ }), 12407 12408 /***/ 7106: 12409 /***/ ((__unused_webpack_module, exports) => { 12410 12411 "use strict"; 12412 12413 Object.defineProperty(exports, "__esModule", ({ value: true })); 12414 exports.isObjectRecord = exports.isStringRecord = exports.isObjectArray = exports.isStringArray = exports.isObject = exports.isDefined = void 0; 12415 function isDefined(val) { 12416 return val !== undefined; 12417 } 12418 exports.isDefined = isDefined; 12419 function isObject(value) { 12420 return typeof value === 'object' && value !== null; 12421 } 12422 exports.isObject = isObject; 12423 function isStringArray(value) { 12424 return Array.isArray(value) && value.every((v) => typeof v === 'string'); 12425 } 12426 exports.isStringArray = isStringArray; 12427 function isObjectArray(value) { 12428 return Array.isArray(value) && value.every(isObject); 12429 } 12430 exports.isObjectArray = isObjectArray; 12431 function isStringRecord(value) { 12432 return (typeof value === 'object' && 12433 value !== null && 12434 Object.keys(value).every((k) => typeof k === 'string') && 12435 Object.values(value).every((v) => typeof v === 'string')); 12436 } 12437 exports.isStringRecord = isStringRecord; 12438 function isObjectRecord(value) { 12439 return (typeof value === 'object' && 12440 value !== null && 12441 Object.keys(value).every((k) => typeof k === 'string') && 12442 Object.values(value).every((v) => typeof v === 'object' && v !== null)); 12443 } 12444 exports.isObjectRecord = isObjectRecord; 12445 12446 12447 /***/ }), 12448 12449 /***/ 5688: 12450 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12451 12452 "use strict"; 12453 12454 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 12455 if (k2 === undefined) k2 = k; 12456 var desc = Object.getOwnPropertyDescriptor(m, k); 12457 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 12458 desc = { enumerable: true, get: function() { return m[k]; } }; 12459 } 12460 Object.defineProperty(o, k2, desc); 12461 }) : (function(o, m, k, k2) { 12462 if (k2 === undefined) k2 = k; 12463 o[k2] = m[k]; 12464 })); 12465 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 12466 Object.defineProperty(o, "default", { enumerable: true, value: v }); 12467 }) : function(o, v) { 12468 o["default"] = v; 12469 }); 12470 var __importStar = (this && this.__importStar) || function (mod) { 12471 if (mod && mod.__esModule) return mod; 12472 var result = {}; 12473 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 12474 __setModuleDefault(result, mod); 12475 return result; 12476 }; 12477 Object.defineProperty(exports, "__esModule", ({ value: true })); 12478 exports.crypto = exports.guard = void 0; 12479 exports.guard = __importStar(__nccwpck_require__(7106)); 12480 exports.crypto = __importStar(__nccwpck_require__(8430)); 12481 12482 12483 /***/ }), 12484 12485 /***/ 8725: 12486 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12487 12488 "use strict"; 12489 12490 var __importDefault = (this && this.__importDefault) || function (mod) { 12491 return (mod && mod.__esModule) ? mod : { "default": mod }; 12492 }; 12493 Object.defineProperty(exports, "__esModule", ({ value: true })); 12494 exports.getPublicKey = void 0; 12495 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 12496 const error_1 = __nccwpck_require__(8448); 12497 const oid_1 = __nccwpck_require__(8680); 12498 const ASN1_TAG_SEQUENCE = 0x30; 12499 const ANS1_TAG_BIT_STRING = 0x03; 12500 const NULL_BYTE = 0x00; 12501 const OID_EDDSA = '1.3.101.112'; 12502 const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1'; 12503 const OID_EC_CURVE_P256V1 = '1.2.840.10045.3.1.7'; 12504 const PEM_HEADER = '-----BEGIN PUBLIC KEY-----'; 12505 function getPublicKey(keyInfo) { 12506 switch (keyInfo.keyType) { 12507 case 'rsa': 12508 return getRSAPublicKey(keyInfo); 12509 case 'ed25519': 12510 return getED25519PublicKey(keyInfo); 12511 case 'ecdsa': 12512 case 'ecdsa-sha2-nistp256': 12513 case 'ecdsa-sha2-nistp384': 12514 return getECDCSAPublicKey(keyInfo); 12515 default: 12516 throw new error_1.UnsupportedAlgorithmError(`Unsupported key type: ${keyInfo.keyType}`); 12517 } 12518 } 12519 exports.getPublicKey = getPublicKey; 12520 function getRSAPublicKey(keyInfo) { 12521 // Only support PEM-encoded RSA keys 12522 if (!keyInfo.keyVal.startsWith(PEM_HEADER)) { 12523 throw new error_1.CryptoError('Invalid key format'); 12524 } 12525 const key = crypto_1.default.createPublicKey(keyInfo.keyVal); 12526 switch (keyInfo.scheme) { 12527 case 'rsassa-pss-sha256': 12528 return { 12529 key: key, 12530 padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING, 12531 }; 12532 default: 12533 throw new error_1.UnsupportedAlgorithmError(`Unsupported RSA scheme: ${keyInfo.scheme}`); 12534 } 12535 } 12536 function getED25519PublicKey(keyInfo) { 12537 let key; 12538 // If key is already PEM-encoded we can just parse it 12539 if (keyInfo.keyVal.startsWith(PEM_HEADER)) { 12540 key = crypto_1.default.createPublicKey(keyInfo.keyVal); 12541 } 12542 else { 12543 // If key is not PEM-encoded it had better be hex 12544 if (!isHex(keyInfo.keyVal)) { 12545 throw new error_1.CryptoError('Invalid key format'); 12546 } 12547 key = crypto_1.default.createPublicKey({ 12548 key: ed25519.hexToDER(keyInfo.keyVal), 12549 format: 'der', 12550 type: 'spki', 12551 }); 12552 } 12553 return { key }; 12554 } 12555 function getECDCSAPublicKey(keyInfo) { 12556 let key; 12557 // If key is already PEM-encoded we can just parse it 12558 if (keyInfo.keyVal.startsWith(PEM_HEADER)) { 12559 key = crypto_1.default.createPublicKey(keyInfo.keyVal); 12560 } 12561 else { 12562 // If key is not PEM-encoded it had better be hex 12563 if (!isHex(keyInfo.keyVal)) { 12564 throw new error_1.CryptoError('Invalid key format'); 12565 } 12566 key = crypto_1.default.createPublicKey({ 12567 key: ecdsa.hexToDER(keyInfo.keyVal), 12568 format: 'der', 12569 type: 'spki', 12570 }); 12571 } 12572 return { key }; 12573 } 12574 const ed25519 = { 12575 // Translates a hex key into a crypto KeyObject 12576 // https://keygen.sh/blog/how-to-use-hexadecimal-ed25519-keys-in-node/ 12577 hexToDER: (hex) => { 12578 const key = Buffer.from(hex, 'hex'); 12579 const oid = (0, oid_1.encodeOIDString)(OID_EDDSA); 12580 // Create a byte sequence containing the OID and key 12581 const elements = Buffer.concat([ 12582 Buffer.concat([ 12583 Buffer.from([ASN1_TAG_SEQUENCE]), 12584 Buffer.from([oid.length]), 12585 oid, 12586 ]), 12587 Buffer.concat([ 12588 Buffer.from([ANS1_TAG_BIT_STRING]), 12589 Buffer.from([key.length + 1]), 12590 Buffer.from([NULL_BYTE]), 12591 key, 12592 ]), 12593 ]); 12594 // Wrap up by creating a sequence of elements 12595 const der = Buffer.concat([ 12596 Buffer.from([ASN1_TAG_SEQUENCE]), 12597 Buffer.from([elements.length]), 12598 elements, 12599 ]); 12600 return der; 12601 }, 12602 }; 12603 const ecdsa = { 12604 hexToDER: (hex) => { 12605 const key = Buffer.from(hex, 'hex'); 12606 const bitString = Buffer.concat([ 12607 Buffer.from([ANS1_TAG_BIT_STRING]), 12608 Buffer.from([key.length + 1]), 12609 Buffer.from([NULL_BYTE]), 12610 key, 12611 ]); 12612 const oids = Buffer.concat([ 12613 (0, oid_1.encodeOIDString)(OID_EC_PUBLIC_KEY), 12614 (0, oid_1.encodeOIDString)(OID_EC_CURVE_P256V1), 12615 ]); 12616 const oidSequence = Buffer.concat([ 12617 Buffer.from([ASN1_TAG_SEQUENCE]), 12618 Buffer.from([oids.length]), 12619 oids, 12620 ]); 12621 // Wrap up by creating a sequence of elements 12622 const der = Buffer.concat([ 12623 Buffer.from([ASN1_TAG_SEQUENCE]), 12624 Buffer.from([oidSequence.length + bitString.length]), 12625 oidSequence, 12626 bitString, 12627 ]); 12628 return der; 12629 }, 12630 }; 12631 const isHex = (key) => /^[0-9a-fA-F]+$/.test(key); 12632 12633 12634 /***/ }), 12635 12636 /***/ 8680: 12637 /***/ ((__unused_webpack_module, exports) => { 12638 12639 "use strict"; 12640 12641 Object.defineProperty(exports, "__esModule", ({ value: true })); 12642 exports.encodeOIDString = void 0; 12643 const ANS1_TAG_OID = 0x06; 12644 function encodeOIDString(oid) { 12645 const parts = oid.split('.'); 12646 // The first two subidentifiers are encoded into the first byte 12647 const first = parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10); 12648 const rest = []; 12649 parts.slice(2).forEach((part) => { 12650 const bytes = encodeVariableLengthInteger(parseInt(part, 10)); 12651 rest.push(...bytes); 12652 }); 12653 const der = Buffer.from([first, ...rest]); 12654 return Buffer.from([ANS1_TAG_OID, der.length, ...der]); 12655 } 12656 exports.encodeOIDString = encodeOIDString; 12657 function encodeVariableLengthInteger(value) { 12658 const bytes = []; 12659 let mask = 0x00; 12660 while (value > 0) { 12661 bytes.unshift((value & 0x7f) | mask); 12662 value >>= 7; 12663 mask = 0x80; 12664 } 12665 return bytes; 12666 } 12667 12668 12669 /***/ }), 12670 12671 /***/ 8430: 12672 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12673 12674 "use strict"; 12675 12676 var __importDefault = (this && this.__importDefault) || function (mod) { 12677 return (mod && mod.__esModule) ? mod : { "default": mod }; 12678 }; 12679 Object.defineProperty(exports, "__esModule", ({ value: true })); 12680 exports.verifySignature = void 0; 12681 const canonical_json_1 = __nccwpck_require__(9652); 12682 const crypto_1 = __importDefault(__nccwpck_require__(6113)); 12683 const verifySignature = (metaDataSignedData, key, signature) => { 12684 const canonicalData = Buffer.from((0, canonical_json_1.canonicalize)(metaDataSignedData)); 12685 return crypto_1.default.verify(undefined, canonicalData, key, Buffer.from(signature, 'hex')); 12686 }; 12687 exports.verifySignature = verifySignature; 12688 12689 12690 /***/ }), 12691 12692 /***/ 4515: 12693 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 12694 12695 var balanced = __nccwpck_require__(9417); 12696 12697 module.exports = expandTop; 12698 12699 var escSlash = '\0SLASH'+Math.random()+'\0'; 12700 var escOpen = '\0OPEN'+Math.random()+'\0'; 12701 var escClose = '\0CLOSE'+Math.random()+'\0'; 12702 var escComma = '\0COMMA'+Math.random()+'\0'; 12703 var escPeriod = '\0PERIOD'+Math.random()+'\0'; 12704 12705 function numeric(str) { 12706 return parseInt(str, 10) == str 12707 ? parseInt(str, 10) 12708 : str.charCodeAt(0); 12709 } 12710 12711 function escapeBraces(str) { 12712 return str.split('\\\\').join(escSlash) 12713 .split('\\{').join(escOpen) 12714 .split('\\}').join(escClose) 12715 .split('\\,').join(escComma) 12716 .split('\\.').join(escPeriod); 12717 } 12718 12719 function unescapeBraces(str) { 12720 return str.split(escSlash).join('\\') 12721 .split(escOpen).join('{') 12722 .split(escClose).join('}') 12723 .split(escComma).join(',') 12724 .split(escPeriod).join('.'); 12725 } 12726 12727 12728 // Basically just str.split(","), but handling cases 12729 // where we have nested braced sections, which should be 12730 // treated as individual members, like {a,{b,c},d} 12731 function parseCommaParts(str) { 12732 if (!str) 12733 return ['']; 12734 12735 var parts = []; 12736 var m = balanced('{', '}', str); 12737 12738 if (!m) 12739 return str.split(','); 12740 12741 var pre = m.pre; 12742 var body = m.body; 12743 var post = m.post; 12744 var p = pre.split(','); 12745 12746 p[p.length-1] += '{' + body + '}'; 12747 var postParts = parseCommaParts(post); 12748 if (post.length) { 12749 p[p.length-1] += postParts.shift(); 12750 p.push.apply(p, postParts); 12751 } 12752 12753 parts.push.apply(parts, p); 12754 12755 return parts; 12756 } 12757 12758 function expandTop(str) { 12759 if (!str) 12760 return []; 12761 12762 // I don't know why Bash 4.3 does this, but it does. 12763 // Anything starting with {} will have the first two bytes preserved 12764 // but *only* at the top level, so {},a}b will not expand to anything, 12765 // but a{},b}c will be expanded to [a}c,abc]. 12766 // One could argue that this is a bug in Bash, but since the goal of 12767 // this module is to match Bash's rules, we escape a leading {} 12768 if (str.substr(0, 2) === '{}') { 12769 str = '\\{\\}' + str.substr(2); 12770 } 12771 12772 return expand(escapeBraces(str), true).map(unescapeBraces); 12773 } 12774 12775 function embrace(str) { 12776 return '{' + str + '}'; 12777 } 12778 function isPadded(el) { 12779 return /^-?0\d/.test(el); 12780 } 12781 12782 function lte(i, y) { 12783 return i <= y; 12784 } 12785 function gte(i, y) { 12786 return i >= y; 12787 } 12788 12789 function expand(str, isTop) { 12790 var expansions = []; 12791 12792 var m = balanced('{', '}', str); 12793 if (!m) return [str]; 12794 12795 // no need to expand pre, since it is guaranteed to be free of brace-sets 12796 var pre = m.pre; 12797 var post = m.post.length 12798 ? expand(m.post, false) 12799 : ['']; 12800 12801 if (/\$$/.test(m.pre)) { 12802 for (var k = 0; k < post.length; k++) { 12803 var expansion = pre+ '{' + m.body + '}' + post[k]; 12804 expansions.push(expansion); 12805 } 12806 } else { 12807 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); 12808 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); 12809 var isSequence = isNumericSequence || isAlphaSequence; 12810 var isOptions = m.body.indexOf(',') >= 0; 12811 if (!isSequence && !isOptions) { 12812 // {a},b} 12813 if (m.post.match(/,.*\}/)) { 12814 str = m.pre + '{' + m.body + escClose + m.post; 12815 return expand(str); 12816 } 12817 return [str]; 12818 } 12819 12820 var n; 12821 if (isSequence) { 12822 n = m.body.split(/\.\./); 12823 } else { 12824 n = parseCommaParts(m.body); 12825 if (n.length === 1) { 12826 // x{{a,b}}y ==> x{a}y x{b}y 12827 n = expand(n[0], false).map(embrace); 12828 if (n.length === 1) { 12829 return post.map(function(p) { 12830 return m.pre + n[0] + p; 12831 }); 12832 } 12833 } 12834 } 12835 12836 // at this point, n is the parts, and we know it's not a comma set 12837 // with a single entry. 12838 var N; 12839 12840 if (isSequence) { 12841 var x = numeric(n[0]); 12842 var y = numeric(n[1]); 12843 var width = Math.max(n[0].length, n[1].length) 12844 var incr = n.length == 3 12845 ? Math.abs(numeric(n[2])) 12846 : 1; 12847 var test = lte; 12848 var reverse = y < x; 12849 if (reverse) { 12850 incr *= -1; 12851 test = gte; 12852 } 12853 var pad = n.some(isPadded); 12854 12855 N = []; 12856 12857 for (var i = x; test(i, y); i += incr) { 12858 var c; 12859 if (isAlphaSequence) { 12860 c = String.fromCharCode(i); 12861 if (c === '\\') 12862 c = ''; 12863 } else { 12864 c = String(i); 12865 if (pad) { 12866 var need = width - c.length; 12867 if (need > 0) { 12868 var z = new Array(need + 1).join('0'); 12869 if (i < 0) 12870 c = '-' + z + c.slice(1); 12871 else 12872 c = z + c; 12873 } 12874 } 12875 } 12876 N.push(c); 12877 } 12878 } else { 12879 N = []; 12880 12881 for (var j = 0; j < n.length; j++) { 12882 N.push.apply(N, expand(n[j], false)); 12883 } 12884 } 12885 12886 for (var j = 0; j < N.length; j++) { 12887 for (var k = 0; k < post.length; k++) { 12888 var expansion = pre + N[j] + post[k]; 12889 if (!isTop || isSequence || expansion) 12890 expansions.push(expansion); 12891 } 12892 } 12893 } 12894 12895 return expansions; 12896 } 12897 12898 12899 12900 /***/ }), 12901 12902 /***/ 8348: 12903 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12904 12905 "use strict"; 12906 12907 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 12908 if (k2 === undefined) k2 = k; 12909 var desc = Object.getOwnPropertyDescriptor(m, k); 12910 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 12911 desc = { enumerable: true, get: function() { return m[k]; } }; 12912 } 12913 Object.defineProperty(o, k2, desc); 12914 }) : (function(o, m, k, k2) { 12915 if (k2 === undefined) k2 = k; 12916 o[k2] = m[k]; 12917 })); 12918 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 12919 Object.defineProperty(o, "default", { enumerable: true, value: v }); 12920 }) : function(o, v) { 12921 o["default"] = v; 12922 }); 12923 var __importStar = (this && this.__importStar) || function (mod) { 12924 if (mod && mod.__esModule) return mod; 12925 var result = {}; 12926 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 12927 __setModuleDefault(result, mod); 12928 return result; 12929 }; 12930 Object.defineProperty(exports, "__esModule", ({ value: true })); 12931 exports.req = exports.json = exports.toBuffer = void 0; 12932 const http = __importStar(__nccwpck_require__(3685)); 12933 const https = __importStar(__nccwpck_require__(5687)); 12934 async function toBuffer(stream) { 12935 let length = 0; 12936 const chunks = []; 12937 for await (const chunk of stream) { 12938 length += chunk.length; 12939 chunks.push(chunk); 12940 } 12941 return Buffer.concat(chunks, length); 12942 } 12943 exports.toBuffer = toBuffer; 12944 // eslint-disable-next-line @typescript-eslint/no-explicit-any 12945 async function json(stream) { 12946 const buf = await toBuffer(stream); 12947 const str = buf.toString('utf8'); 12948 try { 12949 return JSON.parse(str); 12950 } 12951 catch (_err) { 12952 const err = _err; 12953 err.message += ` (input: ${str})`; 12954 throw err; 12955 } 12956 } 12957 exports.json = json; 12958 function req(url, opts = {}) { 12959 const href = typeof url === 'string' ? url : url.href; 12960 const req = (href.startsWith('https:') ? https : http).request(url, opts); 12961 const promise = new Promise((resolve, reject) => { 12962 req 12963 .once('response', resolve) 12964 .once('error', reject) 12965 .end(); 12966 }); 12967 req.then = promise.then.bind(promise); 12968 return req; 12969 } 12970 exports.req = req; 12971 //# sourceMappingURL=helpers.js.map 12972 12973 /***/ }), 12974 12975 /***/ 694: 12976 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 12977 12978 "use strict"; 12979 12980 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 12981 if (k2 === undefined) k2 = k; 12982 var desc = Object.getOwnPropertyDescriptor(m, k); 12983 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 12984 desc = { enumerable: true, get: function() { return m[k]; } }; 12985 } 12986 Object.defineProperty(o, k2, desc); 12987 }) : (function(o, m, k, k2) { 12988 if (k2 === undefined) k2 = k; 12989 o[k2] = m[k]; 12990 })); 12991 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 12992 Object.defineProperty(o, "default", { enumerable: true, value: v }); 12993 }) : function(o, v) { 12994 o["default"] = v; 12995 }); 12996 var __importStar = (this && this.__importStar) || function (mod) { 12997 if (mod && mod.__esModule) return mod; 12998 var result = {}; 12999 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 13000 __setModuleDefault(result, mod); 13001 return result; 13002 }; 13003 var __exportStar = (this && this.__exportStar) || function(m, exports) { 13004 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); 13005 }; 13006 Object.defineProperty(exports, "__esModule", ({ value: true })); 13007 exports.Agent = void 0; 13008 const http = __importStar(__nccwpck_require__(3685)); 13009 __exportStar(__nccwpck_require__(8348), exports); 13010 const INTERNAL = Symbol('AgentBaseInternalState'); 13011 class Agent extends http.Agent { 13012 constructor(opts) { 13013 super(opts); 13014 this[INTERNAL] = {}; 13015 } 13016 /** 13017 * Determine whether this is an `http` or `https` request. 13018 */ 13019 isSecureEndpoint(options) { 13020 if (options) { 13021 // First check the `secureEndpoint` property explicitly, since this 13022 // means that a parent `Agent` is "passing through" to this instance. 13023 // eslint-disable-next-line @typescript-eslint/no-explicit-any 13024 if (typeof options.secureEndpoint === 'boolean') { 13025 return options.secureEndpoint; 13026 } 13027 // If no explicit `secure` endpoint, check if `protocol` property is 13028 // set. This will usually be the case since using a full string URL 13029 // or `URL` instance should be the most common usage. 13030 if (typeof options.protocol === 'string') { 13031 return options.protocol === 'https:'; 13032 } 13033 } 13034 // Finally, if no `protocol` property was set, then fall back to 13035 // checking the stack trace of the current call stack, and try to 13036 // detect the "https" module. 13037 const { stack } = new Error(); 13038 if (typeof stack !== 'string') 13039 return false; 13040 return stack 13041 .split('\n') 13042 .some((l) => l.indexOf('(https.js:') !== -1 || 13043 l.indexOf('node:https:') !== -1); 13044 } 13045 createSocket(req, options, cb) { 13046 const connectOpts = { 13047 ...options, 13048 secureEndpoint: this.isSecureEndpoint(options), 13049 }; 13050 Promise.resolve() 13051 .then(() => this.connect(req, connectOpts)) 13052 .then((socket) => { 13053 if (socket instanceof http.Agent) { 13054 // @ts-expect-error `addRequest()` isn't defined in `@types/node` 13055 return socket.addRequest(req, connectOpts); 13056 } 13057 this[INTERNAL].currentSocket = socket; 13058 // @ts-expect-error `createSocket()` isn't defined in `@types/node` 13059 super.createSocket(req, options, cb); 13060 }, cb); 13061 } 13062 createConnection() { 13063 const socket = this[INTERNAL].currentSocket; 13064 this[INTERNAL].currentSocket = undefined; 13065 if (!socket) { 13066 throw new Error('No socket was returned in the `connect()` function'); 13067 } 13068 return socket; 13069 } 13070 get defaultPort() { 13071 return (this[INTERNAL].defaultPort ?? 13072 (this.protocol === 'https:' ? 443 : 80)); 13073 } 13074 set defaultPort(v) { 13075 if (this[INTERNAL]) { 13076 this[INTERNAL].defaultPort = v; 13077 } 13078 } 13079 get protocol() { 13080 return (this[INTERNAL].protocol ?? 13081 (this.isSecureEndpoint() ? 'https:' : 'http:')); 13082 } 13083 set protocol(v) { 13084 if (this[INTERNAL]) { 13085 this[INTERNAL].protocol = v; 13086 } 13087 } 13088 } 13089 exports.Agent = Agent; 13090 //# sourceMappingURL=index.js.map 13091 13092 /***/ }), 13093 13094 /***/ 1231: 13095 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13096 13097 "use strict"; 13098 13099 const indentString = __nccwpck_require__(8043); 13100 const cleanStack = __nccwpck_require__(7972); 13101 13102 const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); 13103 13104 class AggregateError extends Error { 13105 constructor(errors) { 13106 if (!Array.isArray(errors)) { 13107 throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); 13108 } 13109 13110 errors = [...errors].map(error => { 13111 if (error instanceof Error) { 13112 return error; 13113 } 13114 13115 if (error !== null && typeof error === 'object') { 13116 // Handle plain error objects with message property and/or possibly other metadata 13117 return Object.assign(new Error(error.message), error); 13118 } 13119 13120 return new Error(error); 13121 }); 13122 13123 let message = errors 13124 .map(error => { 13125 // The `stack` property is not standardized, so we can't assume it exists 13126 return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); 13127 }) 13128 .join('\n'); 13129 message = '\n' + indentString(message, 4); 13130 super(message); 13131 13132 this.name = 'AggregateError'; 13133 13134 Object.defineProperty(this, '_errors', {value: errors}); 13135 } 13136 13137 * [Symbol.iterator]() { 13138 for (const error of this._errors) { 13139 yield error; 13140 } 13141 } 13142 } 13143 13144 module.exports = AggregateError; 13145 13146 13147 /***/ }), 13148 13149 /***/ 9417: 13150 /***/ ((module) => { 13151 13152 "use strict"; 13153 13154 module.exports = balanced; 13155 function balanced(a, b, str) { 13156 if (a instanceof RegExp) a = maybeMatch(a, str); 13157 if (b instanceof RegExp) b = maybeMatch(b, str); 13158 13159 var r = range(a, b, str); 13160 13161 return r && { 13162 start: r[0], 13163 end: r[1], 13164 pre: str.slice(0, r[0]), 13165 body: str.slice(r[0] + a.length, r[1]), 13166 post: str.slice(r[1] + b.length) 13167 }; 13168 } 13169 13170 function maybeMatch(reg, str) { 13171 var m = str.match(reg); 13172 return m ? m[0] : null; 13173 } 13174 13175 balanced.range = range; 13176 function range(a, b, str) { 13177 var begs, beg, left, right, result; 13178 var ai = str.indexOf(a); 13179 var bi = str.indexOf(b, ai + 1); 13180 var i = ai; 13181 13182 if (ai >= 0 && bi > 0) { 13183 if(a===b) { 13184 return [ai, bi]; 13185 } 13186 begs = []; 13187 left = str.length; 13188 13189 while (i >= 0 && !result) { 13190 if (i == ai) { 13191 begs.push(i); 13192 ai = str.indexOf(a, i + 1); 13193 } else if (begs.length == 1) { 13194 result = [ begs.pop(), bi ]; 13195 } else { 13196 beg = begs.pop(); 13197 if (beg < left) { 13198 left = beg; 13199 right = bi; 13200 } 13201 13202 bi = str.indexOf(b, i + 1); 13203 } 13204 13205 i = ai < bi && ai >= 0 ? ai : bi; 13206 } 13207 13208 if (begs.length) { 13209 result = [ left, right ]; 13210 } 13211 } 13212 13213 return result; 13214 } 13215 13216 13217 /***/ }), 13218 13219 /***/ 3491: 13220 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13221 13222 "use strict"; 13223 13224 13225 const contentVer = (__nccwpck_require__(1526)/* ["cache-version"].content */ .Jw.k) 13226 const hashToSegments = __nccwpck_require__(2700) 13227 const path = __nccwpck_require__(1017) 13228 const ssri = __nccwpck_require__(4406) 13229 13230 // Current format of content file path: 13231 // 13232 // sha512-BaSE64Hex= -> 13233 // ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee 13234 // 13235 module.exports = contentPath 13236 13237 function contentPath (cache, integrity) { 13238 const sri = ssri.parse(integrity, { single: true }) 13239 // contentPath is the *strongest* algo given 13240 return path.join( 13241 contentDir(cache), 13242 sri.algorithm, 13243 ...hashToSegments(sri.hexDigest()) 13244 ) 13245 } 13246 13247 module.exports.contentDir = contentDir 13248 13249 function contentDir (cache) { 13250 return path.join(cache, `content-v${contentVer}`) 13251 } 13252 13253 13254 /***/ }), 13255 13256 /***/ 9409: 13257 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13258 13259 "use strict"; 13260 13261 13262 const fs = __nccwpck_require__(3292) 13263 const fsm = __nccwpck_require__(968) 13264 const ssri = __nccwpck_require__(4406) 13265 const contentPath = __nccwpck_require__(3491) 13266 const Pipeline = __nccwpck_require__(9891) 13267 13268 module.exports = read 13269 13270 const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 13271 async function read (cache, integrity, opts = {}) { 13272 const { size } = opts 13273 const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { 13274 // get size 13275 const stat = size ? { size } : await fs.stat(cpath) 13276 return { stat, cpath, sri } 13277 }) 13278 13279 if (stat.size > MAX_SINGLE_READ_SIZE) { 13280 return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() 13281 } 13282 13283 const data = await fs.readFile(cpath, { encoding: null }) 13284 13285 if (stat.size !== data.length) { 13286 throw sizeError(stat.size, data.length) 13287 } 13288 13289 if (!ssri.checkData(data, sri)) { 13290 throw integrityError(sri, cpath) 13291 } 13292 13293 return data 13294 } 13295 13296 const readPipeline = (cpath, size, sri, stream) => { 13297 stream.push( 13298 new fsm.ReadStream(cpath, { 13299 size, 13300 readSize: MAX_SINGLE_READ_SIZE, 13301 }), 13302 ssri.integrityStream({ 13303 integrity: sri, 13304 size, 13305 }) 13306 ) 13307 return stream 13308 } 13309 13310 module.exports.stream = readStream 13311 module.exports.readStream = readStream 13312 13313 function readStream (cache, integrity, opts = {}) { 13314 const { size } = opts 13315 const stream = new Pipeline() 13316 // Set all this up to run on the stream and then just return the stream 13317 Promise.resolve().then(async () => { 13318 const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { 13319 // get size 13320 const stat = size ? { size } : await fs.stat(cpath) 13321 return { stat, cpath, sri } 13322 }) 13323 13324 return readPipeline(cpath, stat.size, sri, stream) 13325 }).catch(err => stream.emit('error', err)) 13326 13327 return stream 13328 } 13329 13330 module.exports.copy = copy 13331 13332 function copy (cache, integrity, dest) { 13333 return withContentSri(cache, integrity, (cpath, sri) => { 13334 return fs.copyFile(cpath, dest) 13335 }) 13336 } 13337 13338 module.exports.hasContent = hasContent 13339 13340 async function hasContent (cache, integrity) { 13341 if (!integrity) { 13342 return false 13343 } 13344 13345 try { 13346 return await withContentSri(cache, integrity, async (cpath, sri) => { 13347 const stat = await fs.stat(cpath) 13348 return { size: stat.size, sri, stat } 13349 }) 13350 } catch (err) { 13351 if (err.code === 'ENOENT') { 13352 return false 13353 } 13354 13355 if (err.code === 'EPERM') { 13356 /* istanbul ignore else */ 13357 if (process.platform !== 'win32') { 13358 throw err 13359 } else { 13360 return false 13361 } 13362 } 13363 } 13364 } 13365 13366 async function withContentSri (cache, integrity, fn) { 13367 const sri = ssri.parse(integrity) 13368 // If `integrity` has multiple entries, pick the first digest 13369 // with available local data. 13370 const algo = sri.pickAlgorithm() 13371 const digests = sri[algo] 13372 13373 if (digests.length <= 1) { 13374 const cpath = contentPath(cache, digests[0]) 13375 return fn(cpath, digests[0]) 13376 } else { 13377 // Can't use race here because a generic error can happen before 13378 // a ENOENT error, and can happen before a valid result 13379 const results = await Promise.all(digests.map(async (meta) => { 13380 try { 13381 return await withContentSri(cache, meta, fn) 13382 } catch (err) { 13383 if (err.code === 'ENOENT') { 13384 return Object.assign( 13385 new Error('No matching content found for ' + sri.toString()), 13386 { code: 'ENOENT' } 13387 ) 13388 } 13389 return err 13390 } 13391 })) 13392 // Return the first non error if it is found 13393 const result = results.find((r) => !(r instanceof Error)) 13394 if (result) { 13395 return result 13396 } 13397 13398 // Throw the No matching content found error 13399 const enoentError = results.find((r) => r.code === 'ENOENT') 13400 if (enoentError) { 13401 throw enoentError 13402 } 13403 13404 // Throw generic error 13405 throw results.find((r) => r instanceof Error) 13406 } 13407 } 13408 13409 function sizeError (expected, found) { 13410 /* eslint-disable-next-line max-len */ 13411 const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) 13412 err.expected = expected 13413 err.found = found 13414 err.code = 'EBADSIZE' 13415 return err 13416 } 13417 13418 function integrityError (sri, path) { 13419 const err = new Error(`Integrity verification failed for ${sri} (${path})`) 13420 err.code = 'EINTEGRITY' 13421 err.sri = sri 13422 err.path = path 13423 return err 13424 } 13425 13426 13427 /***/ }), 13428 13429 /***/ 1343: 13430 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13431 13432 "use strict"; 13433 13434 13435 const fs = __nccwpck_require__(3292) 13436 const contentPath = __nccwpck_require__(3491) 13437 const { hasContent } = __nccwpck_require__(9409) 13438 13439 module.exports = rm 13440 13441 async function rm (cache, integrity) { 13442 const content = await hasContent(cache, integrity) 13443 // ~pretty~ sure we can't end up with a content lacking sri, but be safe 13444 if (content && content.sri) { 13445 await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) 13446 return true 13447 } else { 13448 return false 13449 } 13450 } 13451 13452 13453 /***/ }), 13454 13455 /***/ 3729: 13456 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13457 13458 "use strict"; 13459 13460 13461 const events = __nccwpck_require__(2361) 13462 13463 const contentPath = __nccwpck_require__(3491) 13464 const fs = __nccwpck_require__(3292) 13465 const { moveFile } = __nccwpck_require__(575) 13466 const { Minipass } = __nccwpck_require__(4968) 13467 const Pipeline = __nccwpck_require__(9891) 13468 const Flush = __nccwpck_require__(4181) 13469 const path = __nccwpck_require__(1017) 13470 const ssri = __nccwpck_require__(4406) 13471 const uniqueFilename = __nccwpck_require__(1747) 13472 const fsm = __nccwpck_require__(968) 13473 13474 module.exports = write 13475 13476 // Cache of move operations in process so we don't duplicate 13477 const moveOperations = new Map() 13478 13479 async function write (cache, data, opts = {}) { 13480 const { algorithms, size, integrity } = opts 13481 13482 if (typeof size === 'number' && data.length !== size) { 13483 throw sizeError(size, data.length) 13484 } 13485 13486 const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) 13487 if (integrity && !ssri.checkData(data, integrity, opts)) { 13488 throw checksumError(integrity, sri) 13489 } 13490 13491 for (const algo in sri) { 13492 const tmp = await makeTmp(cache, opts) 13493 const hash = sri[algo].toString() 13494 try { 13495 await fs.writeFile(tmp.target, data, { flag: 'wx' }) 13496 await moveToDestination(tmp, cache, hash, opts) 13497 } finally { 13498 if (!tmp.moved) { 13499 await fs.rm(tmp.target, { recursive: true, force: true }) 13500 } 13501 } 13502 } 13503 return { integrity: sri, size: data.length } 13504 } 13505 13506 module.exports.stream = writeStream 13507 13508 // writes proxied to the 'inputStream' that is passed to the Promise 13509 // 'end' is deferred until content is handled. 13510 class CacacheWriteStream extends Flush { 13511 constructor (cache, opts) { 13512 super() 13513 this.opts = opts 13514 this.cache = cache 13515 this.inputStream = new Minipass() 13516 this.inputStream.on('error', er => this.emit('error', er)) 13517 this.inputStream.on('drain', () => this.emit('drain')) 13518 this.handleContentP = null 13519 } 13520 13521 write (chunk, encoding, cb) { 13522 if (!this.handleContentP) { 13523 this.handleContentP = handleContent( 13524 this.inputStream, 13525 this.cache, 13526 this.opts 13527 ) 13528 this.handleContentP.catch(error => this.emit('error', error)) 13529 } 13530 return this.inputStream.write(chunk, encoding, cb) 13531 } 13532 13533 flush (cb) { 13534 this.inputStream.end(() => { 13535 if (!this.handleContentP) { 13536 const e = new Error('Cache input stream was empty') 13537 e.code = 'ENODATA' 13538 // empty streams are probably emitting end right away. 13539 // defer this one tick by rejecting a promise on it. 13540 return Promise.reject(e).catch(cb) 13541 } 13542 // eslint-disable-next-line promise/catch-or-return 13543 this.handleContentP.then( 13544 (res) => { 13545 res.integrity && this.emit('integrity', res.integrity) 13546 // eslint-disable-next-line promise/always-return 13547 res.size !== null && this.emit('size', res.size) 13548 cb() 13549 }, 13550 (er) => cb(er) 13551 ) 13552 }) 13553 } 13554 } 13555 13556 function writeStream (cache, opts = {}) { 13557 return new CacacheWriteStream(cache, opts) 13558 } 13559 13560 async function handleContent (inputStream, cache, opts) { 13561 const tmp = await makeTmp(cache, opts) 13562 try { 13563 const res = await pipeToTmp(inputStream, cache, tmp.target, opts) 13564 await moveToDestination( 13565 tmp, 13566 cache, 13567 res.integrity, 13568 opts 13569 ) 13570 return res 13571 } finally { 13572 if (!tmp.moved) { 13573 await fs.rm(tmp.target, { recursive: true, force: true }) 13574 } 13575 } 13576 } 13577 13578 async function pipeToTmp (inputStream, cache, tmpTarget, opts) { 13579 const outStream = new fsm.WriteStream(tmpTarget, { 13580 flags: 'wx', 13581 }) 13582 13583 if (opts.integrityEmitter) { 13584 // we need to create these all simultaneously since they can fire in any order 13585 const [integrity, size] = await Promise.all([ 13586 events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), 13587 events.once(opts.integrityEmitter, 'size').then(res => res[0]), 13588 new Pipeline(inputStream, outStream).promise(), 13589 ]) 13590 return { integrity, size } 13591 } 13592 13593 let integrity 13594 let size 13595 const hashStream = ssri.integrityStream({ 13596 integrity: opts.integrity, 13597 algorithms: opts.algorithms, 13598 size: opts.size, 13599 }) 13600 hashStream.on('integrity', i => { 13601 integrity = i 13602 }) 13603 hashStream.on('size', s => { 13604 size = s 13605 }) 13606 13607 const pipeline = new Pipeline(inputStream, hashStream, outStream) 13608 await pipeline.promise() 13609 return { integrity, size } 13610 } 13611 13612 async function makeTmp (cache, opts) { 13613 const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) 13614 await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) 13615 return { 13616 target: tmpTarget, 13617 moved: false, 13618 } 13619 } 13620 13621 async function moveToDestination (tmp, cache, sri, opts) { 13622 const destination = contentPath(cache, sri) 13623 const destDir = path.dirname(destination) 13624 if (moveOperations.has(destination)) { 13625 return moveOperations.get(destination) 13626 } 13627 moveOperations.set( 13628 destination, 13629 fs.mkdir(destDir, { recursive: true }) 13630 .then(async () => { 13631 await moveFile(tmp.target, destination, { overwrite: false }) 13632 tmp.moved = true 13633 return tmp.moved 13634 }) 13635 .catch(err => { 13636 if (!err.message.startsWith('The destination file exists')) { 13637 throw Object.assign(err, { code: 'EEXIST' }) 13638 } 13639 }).finally(() => { 13640 moveOperations.delete(destination) 13641 }) 13642 13643 ) 13644 return moveOperations.get(destination) 13645 } 13646 13647 function sizeError (expected, found) { 13648 /* eslint-disable-next-line max-len */ 13649 const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) 13650 err.expected = expected 13651 err.found = found 13652 err.code = 'EBADSIZE' 13653 return err 13654 } 13655 13656 function checksumError (expected, found) { 13657 const err = new Error(`Integrity check failed: 13658 Wanted: ${expected} 13659 Found: ${found}`) 13660 err.code = 'EINTEGRITY' 13661 err.expected = expected 13662 err.found = found 13663 return err 13664 } 13665 13666 13667 /***/ }), 13668 13669 /***/ 595: 13670 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 13671 13672 "use strict"; 13673 13674 13675 const crypto = __nccwpck_require__(6113) 13676 const { 13677 appendFile, 13678 mkdir, 13679 readFile, 13680 readdir, 13681 rm, 13682 writeFile, 13683 } = __nccwpck_require__(3292) 13684 const { Minipass } = __nccwpck_require__(4968) 13685 const path = __nccwpck_require__(1017) 13686 const ssri = __nccwpck_require__(4406) 13687 const uniqueFilename = __nccwpck_require__(1747) 13688 13689 const contentPath = __nccwpck_require__(3491) 13690 const hashToSegments = __nccwpck_require__(2700) 13691 const indexV = (__nccwpck_require__(1526)/* ["cache-version"].index */ .Jw.K) 13692 const { moveFile } = __nccwpck_require__(575) 13693 13694 module.exports.NotFoundError = class NotFoundError extends Error { 13695 constructor (cache, key) { 13696 super(`No cache entry for ${key} found in ${cache}`) 13697 this.code = 'ENOENT' 13698 this.cache = cache 13699 this.key = key 13700 } 13701 } 13702 13703 module.exports.compact = compact 13704 13705 async function compact (cache, key, matchFn, opts = {}) { 13706 const bucket = bucketPath(cache, key) 13707 const entries = await bucketEntries(bucket) 13708 const newEntries = [] 13709 // we loop backwards because the bottom-most result is the newest 13710 // since we add new entries with appendFile 13711 for (let i = entries.length - 1; i >= 0; --i) { 13712 const entry = entries[i] 13713 // a null integrity could mean either a delete was appended 13714 // or the user has simply stored an index that does not map 13715 // to any content. we determine if the user wants to keep the 13716 // null integrity based on the validateEntry function passed in options. 13717 // if the integrity is null and no validateEntry is provided, we break 13718 // as we consider the null integrity to be a deletion of everything 13719 // that came before it. 13720 if (entry.integrity === null && !opts.validateEntry) { 13721 break 13722 } 13723 13724 // if this entry is valid, and it is either the first entry or 13725 // the newEntries array doesn't already include an entry that 13726 // matches this one based on the provided matchFn, then we add 13727 // it to the beginning of our list 13728 if ((!opts.validateEntry || opts.validateEntry(entry) === true) && 13729 (newEntries.length === 0 || 13730 !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { 13731 newEntries.unshift(entry) 13732 } 13733 } 13734 13735 const newIndex = '\n' + newEntries.map((entry) => { 13736 const stringified = JSON.stringify(entry) 13737 const hash = hashEntry(stringified) 13738 return `${hash}\t${stringified}` 13739 }).join('\n') 13740 13741 const setup = async () => { 13742 const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) 13743 await mkdir(path.dirname(target), { recursive: true }) 13744 return { 13745 target, 13746 moved: false, 13747 } 13748 } 13749 13750 const teardown = async (tmp) => { 13751 if (!tmp.moved) { 13752 return rm(tmp.target, { recursive: true, force: true }) 13753 } 13754 } 13755 13756 const write = async (tmp) => { 13757 await writeFile(tmp.target, newIndex, { flag: 'wx' }) 13758 await mkdir(path.dirname(bucket), { recursive: true }) 13759 // we use @npmcli/move-file directly here because we 13760 // want to overwrite the existing file 13761 await moveFile(tmp.target, bucket) 13762 tmp.moved = true 13763 } 13764 13765 // write the file atomically 13766 const tmp = await setup() 13767 try { 13768 await write(tmp) 13769 } finally { 13770 await teardown(tmp) 13771 } 13772 13773 // we reverse the list we generated such that the newest 13774 // entries come first in order to make looping through them easier 13775 // the true passed to formatEntry tells it to keep null 13776 // integrity values, if they made it this far it's because 13777 // validateEntry returned true, and as such we should return it 13778 return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) 13779 } 13780 13781 module.exports.insert = insert 13782 13783 async function insert (cache, key, integrity, opts = {}) { 13784 const { metadata, size, time } = opts 13785 const bucket = bucketPath(cache, key) 13786 const entry = { 13787 key, 13788 integrity: integrity && ssri.stringify(integrity), 13789 time: time || Date.now(), 13790 size, 13791 metadata, 13792 } 13793 try { 13794 await mkdir(path.dirname(bucket), { recursive: true }) 13795 const stringified = JSON.stringify(entry) 13796 // NOTE - Cleverness ahoy! 13797 // 13798 // This works because it's tremendously unlikely for an entry to corrupt 13799 // another while still preserving the string length of the JSON in 13800 // question. So, we just slap the length in there and verify it on read. 13801 // 13802 // Thanks to @isaacs for the whiteboarding session that ended up with 13803 // this. 13804 await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) 13805 } catch (err) { 13806 if (err.code === 'ENOENT') { 13807 return undefined 13808 } 13809 13810 throw err 13811 } 13812 return formatEntry(cache, entry) 13813 } 13814 13815 module.exports.find = find 13816 13817 async function find (cache, key) { 13818 const bucket = bucketPath(cache, key) 13819 try { 13820 const entries = await bucketEntries(bucket) 13821 return entries.reduce((latest, next) => { 13822 if (next && next.key === key) { 13823 return formatEntry(cache, next) 13824 } else { 13825 return latest 13826 } 13827 }, null) 13828 } catch (err) { 13829 if (err.code === 'ENOENT') { 13830 return null 13831 } else { 13832 throw err 13833 } 13834 } 13835 } 13836 13837 module.exports["delete"] = del 13838 13839 function del (cache, key, opts = {}) { 13840 if (!opts.removeFully) { 13841 return insert(cache, key, null, opts) 13842 } 13843 13844 const bucket = bucketPath(cache, key) 13845 return rm(bucket, { recursive: true, force: true }) 13846 } 13847 13848 module.exports.lsStream = lsStream 13849 13850 function lsStream (cache) { 13851 const indexDir = bucketDir(cache) 13852 const stream = new Minipass({ objectMode: true }) 13853 13854 // Set all this up to run on the stream and then just return the stream 13855 Promise.resolve().then(async () => { 13856 const buckets = await readdirOrEmpty(indexDir) 13857 await Promise.all(buckets.map(async (bucket) => { 13858 const bucketPath = path.join(indexDir, bucket) 13859 const subbuckets = await readdirOrEmpty(bucketPath) 13860 await Promise.all(subbuckets.map(async (subbucket) => { 13861 const subbucketPath = path.join(bucketPath, subbucket) 13862 13863 // "/cachename/<bucket 0xFF>/<bucket 0xFF>./*" 13864 const subbucketEntries = await readdirOrEmpty(subbucketPath) 13865 await Promise.all(subbucketEntries.map(async (entry) => { 13866 const entryPath = path.join(subbucketPath, entry) 13867 try { 13868 const entries = await bucketEntries(entryPath) 13869 // using a Map here prevents duplicate keys from showing up 13870 // twice, I guess? 13871 const reduced = entries.reduce((acc, entry) => { 13872 acc.set(entry.key, entry) 13873 return acc 13874 }, new Map()) 13875 // reduced is a map of key => entry 13876 for (const entry of reduced.values()) { 13877 const formatted = formatEntry(cache, entry) 13878 if (formatted) { 13879 stream.write(formatted) 13880 } 13881 } 13882 } catch (err) { 13883 if (err.code === 'ENOENT') { 13884 return undefined 13885 } 13886 throw err 13887 } 13888 })) 13889 })) 13890 })) 13891 stream.end() 13892 return stream 13893 }).catch(err => stream.emit('error', err)) 13894 13895 return stream 13896 } 13897 13898 module.exports.ls = ls 13899 13900 async function ls (cache) { 13901 const entries = await lsStream(cache).collect() 13902 return entries.reduce((acc, xs) => { 13903 acc[xs.key] = xs 13904 return acc 13905 }, {}) 13906 } 13907 13908 module.exports.bucketEntries = bucketEntries 13909 13910 async function bucketEntries (bucket, filter) { 13911 const data = await readFile(bucket, 'utf8') 13912 return _bucketEntries(data, filter) 13913 } 13914 13915 function _bucketEntries (data, filter) { 13916 const entries = [] 13917 data.split('\n').forEach((entry) => { 13918 if (!entry) { 13919 return 13920 } 13921 13922 const pieces = entry.split('\t') 13923 if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { 13924 // Hash is no good! Corruption or malice? Doesn't matter! 13925 // EJECT EJECT 13926 return 13927 } 13928 let obj 13929 try { 13930 obj = JSON.parse(pieces[1]) 13931 } catch (_) { 13932 // eslint-ignore-next-line no-empty-block 13933 } 13934 // coverage disabled here, no need to test with an entry that parses to something falsey 13935 // istanbul ignore else 13936 if (obj) { 13937 entries.push(obj) 13938 } 13939 }) 13940 return entries 13941 } 13942 13943 module.exports.bucketDir = bucketDir 13944 13945 function bucketDir (cache) { 13946 return path.join(cache, `index-v${indexV}`) 13947 } 13948 13949 module.exports.bucketPath = bucketPath 13950 13951 function bucketPath (cache, key) { 13952 const hashed = hashKey(key) 13953 return path.join.apply( 13954 path, 13955 [bucketDir(cache)].concat(hashToSegments(hashed)) 13956 ) 13957 } 13958 13959 module.exports.hashKey = hashKey 13960 13961 function hashKey (key) { 13962 return hash(key, 'sha256') 13963 } 13964 13965 module.exports.hashEntry = hashEntry 13966 13967 function hashEntry (str) { 13968 return hash(str, 'sha1') 13969 } 13970 13971 function hash (str, digest) { 13972 return crypto 13973 .createHash(digest) 13974 .update(str) 13975 .digest('hex') 13976 } 13977 13978 function formatEntry (cache, entry, keepAll) { 13979 // Treat null digests as deletions. They'll shadow any previous entries. 13980 if (!entry.integrity && !keepAll) { 13981 return null 13982 } 13983 13984 return { 13985 key: entry.key, 13986 integrity: entry.integrity, 13987 path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, 13988 size: entry.size, 13989 time: entry.time, 13990 metadata: entry.metadata, 13991 } 13992 } 13993 13994 function readdirOrEmpty (dir) { 13995 return readdir(dir).catch((err) => { 13996 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { 13997 return [] 13998 } 13999 14000 throw err 14001 }) 14002 } 14003 14004 14005 /***/ }), 14006 14007 /***/ 408: 14008 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14009 14010 "use strict"; 14011 14012 14013 const Collect = __nccwpck_require__(4658) 14014 const { Minipass } = __nccwpck_require__(4968) 14015 const Pipeline = __nccwpck_require__(9891) 14016 14017 const index = __nccwpck_require__(595) 14018 const memo = __nccwpck_require__(5575) 14019 const read = __nccwpck_require__(9409) 14020 14021 async function getData (cache, key, opts = {}) { 14022 const { integrity, memoize, size } = opts 14023 const memoized = memo.get(cache, key, opts) 14024 if (memoized && memoize !== false) { 14025 return { 14026 metadata: memoized.entry.metadata, 14027 data: memoized.data, 14028 integrity: memoized.entry.integrity, 14029 size: memoized.entry.size, 14030 } 14031 } 14032 14033 const entry = await index.find(cache, key, opts) 14034 if (!entry) { 14035 throw new index.NotFoundError(cache, key) 14036 } 14037 const data = await read(cache, entry.integrity, { integrity, size }) 14038 if (memoize) { 14039 memo.put(cache, entry, data, opts) 14040 } 14041 14042 return { 14043 data, 14044 metadata: entry.metadata, 14045 size: entry.size, 14046 integrity: entry.integrity, 14047 } 14048 } 14049 module.exports = getData 14050 14051 async function getDataByDigest (cache, key, opts = {}) { 14052 const { integrity, memoize, size } = opts 14053 const memoized = memo.get.byDigest(cache, key, opts) 14054 if (memoized && memoize !== false) { 14055 return memoized 14056 } 14057 14058 const res = await read(cache, key, { integrity, size }) 14059 if (memoize) { 14060 memo.put.byDigest(cache, key, res, opts) 14061 } 14062 return res 14063 } 14064 module.exports.byDigest = getDataByDigest 14065 14066 const getMemoizedStream = (memoized) => { 14067 const stream = new Minipass() 14068 stream.on('newListener', function (ev, cb) { 14069 ev === 'metadata' && cb(memoized.entry.metadata) 14070 ev === 'integrity' && cb(memoized.entry.integrity) 14071 ev === 'size' && cb(memoized.entry.size) 14072 }) 14073 stream.end(memoized.data) 14074 return stream 14075 } 14076 14077 function getStream (cache, key, opts = {}) { 14078 const { memoize, size } = opts 14079 const memoized = memo.get(cache, key, opts) 14080 if (memoized && memoize !== false) { 14081 return getMemoizedStream(memoized) 14082 } 14083 14084 const stream = new Pipeline() 14085 // Set all this up to run on the stream and then just return the stream 14086 Promise.resolve().then(async () => { 14087 const entry = await index.find(cache, key) 14088 if (!entry) { 14089 throw new index.NotFoundError(cache, key) 14090 } 14091 14092 stream.emit('metadata', entry.metadata) 14093 stream.emit('integrity', entry.integrity) 14094 stream.emit('size', entry.size) 14095 stream.on('newListener', function (ev, cb) { 14096 ev === 'metadata' && cb(entry.metadata) 14097 ev === 'integrity' && cb(entry.integrity) 14098 ev === 'size' && cb(entry.size) 14099 }) 14100 14101 const src = read.readStream( 14102 cache, 14103 entry.integrity, 14104 { ...opts, size: typeof size !== 'number' ? entry.size : size } 14105 ) 14106 14107 if (memoize) { 14108 const memoStream = new Collect.PassThrough() 14109 memoStream.on('collect', data => memo.put(cache, entry, data, opts)) 14110 stream.unshift(memoStream) 14111 } 14112 stream.unshift(src) 14113 return stream 14114 }).catch((err) => stream.emit('error', err)) 14115 14116 return stream 14117 } 14118 14119 module.exports.stream = getStream 14120 14121 function getStreamDigest (cache, integrity, opts = {}) { 14122 const { memoize } = opts 14123 const memoized = memo.get.byDigest(cache, integrity, opts) 14124 if (memoized && memoize !== false) { 14125 const stream = new Minipass() 14126 stream.end(memoized) 14127 return stream 14128 } else { 14129 const stream = read.readStream(cache, integrity, opts) 14130 if (!memoize) { 14131 return stream 14132 } 14133 14134 const memoStream = new Collect.PassThrough() 14135 memoStream.on('collect', data => memo.put.byDigest( 14136 cache, 14137 integrity, 14138 data, 14139 opts 14140 )) 14141 return new Pipeline(stream, memoStream) 14142 } 14143 } 14144 14145 module.exports.stream.byDigest = getStreamDigest 14146 14147 function info (cache, key, opts = {}) { 14148 const { memoize } = opts 14149 const memoized = memo.get(cache, key, opts) 14150 if (memoized && memoize !== false) { 14151 return Promise.resolve(memoized.entry) 14152 } else { 14153 return index.find(cache, key) 14154 } 14155 } 14156 module.exports.info = info 14157 14158 async function copy (cache, key, dest, opts = {}) { 14159 const entry = await index.find(cache, key, opts) 14160 if (!entry) { 14161 throw new index.NotFoundError(cache, key) 14162 } 14163 await read.copy(cache, entry.integrity, dest, opts) 14164 return { 14165 metadata: entry.metadata, 14166 size: entry.size, 14167 integrity: entry.integrity, 14168 } 14169 } 14170 14171 module.exports.copy = copy 14172 14173 async function copyByDigest (cache, key, dest, opts = {}) { 14174 await read.copy(cache, key, dest, opts) 14175 return key 14176 } 14177 14178 module.exports.copy.byDigest = copyByDigest 14179 14180 module.exports.hasContent = read.hasContent 14181 14182 14183 /***/ }), 14184 14185 /***/ 5490: 14186 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14187 14188 "use strict"; 14189 14190 14191 const get = __nccwpck_require__(408) 14192 const put = __nccwpck_require__(178) 14193 const rm = __nccwpck_require__(123) 14194 const verify = __nccwpck_require__(584) 14195 const { clearMemoized } = __nccwpck_require__(5575) 14196 const tmp = __nccwpck_require__(644) 14197 const index = __nccwpck_require__(595) 14198 14199 module.exports.index = {} 14200 module.exports.index.compact = index.compact 14201 module.exports.index.insert = index.insert 14202 14203 module.exports.ls = index.ls 14204 module.exports.ls.stream = index.lsStream 14205 14206 module.exports.get = get 14207 module.exports.get.byDigest = get.byDigest 14208 module.exports.get.stream = get.stream 14209 module.exports.get.stream.byDigest = get.stream.byDigest 14210 module.exports.get.copy = get.copy 14211 module.exports.get.copy.byDigest = get.copy.byDigest 14212 module.exports.get.info = get.info 14213 module.exports.get.hasContent = get.hasContent 14214 14215 module.exports.put = put 14216 module.exports.put.stream = put.stream 14217 14218 module.exports.rm = rm.entry 14219 module.exports.rm.all = rm.all 14220 module.exports.rm.entry = module.exports.rm 14221 module.exports.rm.content = rm.content 14222 14223 module.exports.clearMemoized = clearMemoized 14224 14225 module.exports.tmp = {} 14226 module.exports.tmp.mkdir = tmp.mkdir 14227 module.exports.tmp.withTmp = tmp.withTmp 14228 14229 module.exports.verify = verify 14230 module.exports.verify.lastRun = verify.lastRun 14231 14232 14233 /***/ }), 14234 14235 /***/ 5575: 14236 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14237 14238 "use strict"; 14239 14240 14241 const { LRUCache } = __nccwpck_require__(6874) 14242 14243 const MEMOIZED = new LRUCache({ 14244 max: 500, 14245 maxSize: 50 * 1024 * 1024, // 50MB 14246 ttl: 3 * 60 * 1000, // 3 minutes 14247 sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, 14248 }) 14249 14250 module.exports.clearMemoized = clearMemoized 14251 14252 function clearMemoized () { 14253 const old = {} 14254 MEMOIZED.forEach((v, k) => { 14255 old[k] = v 14256 }) 14257 MEMOIZED.clear() 14258 return old 14259 } 14260 14261 module.exports.put = put 14262 14263 function put (cache, entry, data, opts) { 14264 pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) 14265 putDigest(cache, entry.integrity, data, opts) 14266 } 14267 14268 module.exports.put.byDigest = putDigest 14269 14270 function putDigest (cache, integrity, data, opts) { 14271 pickMem(opts).set(`digest:${cache}:${integrity}`, data) 14272 } 14273 14274 module.exports.get = get 14275 14276 function get (cache, key, opts) { 14277 return pickMem(opts).get(`key:${cache}:${key}`) 14278 } 14279 14280 module.exports.get.byDigest = getDigest 14281 14282 function getDigest (cache, integrity, opts) { 14283 return pickMem(opts).get(`digest:${cache}:${integrity}`) 14284 } 14285 14286 class ObjProxy { 14287 constructor (obj) { 14288 this.obj = obj 14289 } 14290 14291 get (key) { 14292 return this.obj[key] 14293 } 14294 14295 set (key, val) { 14296 this.obj[key] = val 14297 } 14298 } 14299 14300 function pickMem (opts) { 14301 if (!opts || !opts.memoize) { 14302 return MEMOIZED 14303 } else if (opts.memoize.get && opts.memoize.set) { 14304 return opts.memoize 14305 } else if (typeof opts.memoize === 'object') { 14306 return new ObjProxy(opts.memoize) 14307 } else { 14308 return MEMOIZED 14309 } 14310 } 14311 14312 14313 /***/ }), 14314 14315 /***/ 178: 14316 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14317 14318 "use strict"; 14319 14320 14321 const index = __nccwpck_require__(595) 14322 const memo = __nccwpck_require__(5575) 14323 const write = __nccwpck_require__(3729) 14324 const Flush = __nccwpck_require__(4181) 14325 const { PassThrough } = __nccwpck_require__(4658) 14326 const Pipeline = __nccwpck_require__(9891) 14327 14328 const putOpts = (opts) => ({ 14329 algorithms: ['sha512'], 14330 ...opts, 14331 }) 14332 14333 module.exports = putData 14334 14335 async function putData (cache, key, data, opts = {}) { 14336 const { memoize } = opts 14337 opts = putOpts(opts) 14338 const res = await write(cache, data, opts) 14339 const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) 14340 if (memoize) { 14341 memo.put(cache, entry, data, opts) 14342 } 14343 14344 return res.integrity 14345 } 14346 14347 module.exports.stream = putStream 14348 14349 function putStream (cache, key, opts = {}) { 14350 const { memoize } = opts 14351 opts = putOpts(opts) 14352 let integrity 14353 let size 14354 let error 14355 14356 let memoData 14357 const pipeline = new Pipeline() 14358 // first item in the pipeline is the memoizer, because we need 14359 // that to end first and get the collected data. 14360 if (memoize) { 14361 const memoizer = new PassThrough().on('collect', data => { 14362 memoData = data 14363 }) 14364 pipeline.push(memoizer) 14365 } 14366 14367 // contentStream is a write-only, not a passthrough 14368 // no data comes out of it. 14369 const contentStream = write.stream(cache, opts) 14370 .on('integrity', (int) => { 14371 integrity = int 14372 }) 14373 .on('size', (s) => { 14374 size = s 14375 }) 14376 .on('error', (err) => { 14377 error = err 14378 }) 14379 14380 pipeline.push(contentStream) 14381 14382 // last but not least, we write the index and emit hash and size, 14383 // and memoize if we're doing that 14384 pipeline.push(new Flush({ 14385 async flush () { 14386 if (!error) { 14387 const entry = await index.insert(cache, key, integrity, { ...opts, size }) 14388 if (memoize && memoData) { 14389 memo.put(cache, entry, memoData, opts) 14390 } 14391 pipeline.emit('integrity', integrity) 14392 pipeline.emit('size', size) 14393 } 14394 }, 14395 })) 14396 14397 return pipeline 14398 } 14399 14400 14401 /***/ }), 14402 14403 /***/ 123: 14404 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14405 14406 "use strict"; 14407 14408 14409 const { rm } = __nccwpck_require__(3292) 14410 const glob = __nccwpck_require__(8066) 14411 const index = __nccwpck_require__(595) 14412 const memo = __nccwpck_require__(5575) 14413 const path = __nccwpck_require__(1017) 14414 const rmContent = __nccwpck_require__(1343) 14415 14416 module.exports = entry 14417 module.exports.entry = entry 14418 14419 function entry (cache, key, opts) { 14420 memo.clearMemoized() 14421 return index.delete(cache, key, opts) 14422 } 14423 14424 module.exports.content = content 14425 14426 function content (cache, integrity) { 14427 memo.clearMemoized() 14428 return rmContent(cache, integrity) 14429 } 14430 14431 module.exports.all = all 14432 14433 async function all (cache) { 14434 memo.clearMemoized() 14435 const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) 14436 return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) 14437 } 14438 14439 14440 /***/ }), 14441 14442 /***/ 8066: 14443 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14444 14445 "use strict"; 14446 14447 14448 const { glob } = __nccwpck_require__(836) 14449 const path = __nccwpck_require__(1017) 14450 14451 const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) 14452 module.exports = (path, options) => glob(globify(path), options) 14453 14454 14455 /***/ }), 14456 14457 /***/ 2700: 14458 /***/ ((module) => { 14459 14460 "use strict"; 14461 14462 14463 module.exports = hashToSegments 14464 14465 function hashToSegments (hash) { 14466 return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] 14467 } 14468 14469 14470 /***/ }), 14471 14472 /***/ 644: 14473 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14474 14475 "use strict"; 14476 14477 14478 const { withTempDir } = __nccwpck_require__(575) 14479 const fs = __nccwpck_require__(3292) 14480 const path = __nccwpck_require__(1017) 14481 14482 module.exports.mkdir = mktmpdir 14483 14484 async function mktmpdir (cache, opts = {}) { 14485 const { tmpPrefix } = opts 14486 const tmpDir = path.join(cache, 'tmp') 14487 await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) 14488 // do not use path.join(), it drops the trailing / if tmpPrefix is unset 14489 const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` 14490 return fs.mkdtemp(target, { owner: 'inherit' }) 14491 } 14492 14493 module.exports.withTmp = withTmp 14494 14495 function withTmp (cache, opts, cb) { 14496 if (!cb) { 14497 cb = opts 14498 opts = {} 14499 } 14500 return withTempDir(path.join(cache, 'tmp'), cb, opts) 14501 } 14502 14503 14504 /***/ }), 14505 14506 /***/ 584: 14507 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14508 14509 "use strict"; 14510 14511 14512 const { 14513 mkdir, 14514 readFile, 14515 rm, 14516 stat, 14517 truncate, 14518 writeFile, 14519 } = __nccwpck_require__(3292) 14520 const pMap = __nccwpck_require__(1855) 14521 const contentPath = __nccwpck_require__(3491) 14522 const fsm = __nccwpck_require__(968) 14523 const glob = __nccwpck_require__(8066) 14524 const index = __nccwpck_require__(595) 14525 const path = __nccwpck_require__(1017) 14526 const ssri = __nccwpck_require__(4406) 14527 14528 const hasOwnProperty = (obj, key) => 14529 Object.prototype.hasOwnProperty.call(obj, key) 14530 14531 const verifyOpts = (opts) => ({ 14532 concurrency: 20, 14533 log: { silly () {} }, 14534 ...opts, 14535 }) 14536 14537 module.exports = verify 14538 14539 async function verify (cache, opts) { 14540 opts = verifyOpts(opts) 14541 opts.log.silly('verify', 'verifying cache at', cache) 14542 14543 const steps = [ 14544 markStartTime, 14545 fixPerms, 14546 garbageCollect, 14547 rebuildIndex, 14548 cleanTmp, 14549 writeVerifile, 14550 markEndTime, 14551 ] 14552 14553 const stats = {} 14554 for (const step of steps) { 14555 const label = step.name 14556 const start = new Date() 14557 const s = await step(cache, opts) 14558 if (s) { 14559 Object.keys(s).forEach((k) => { 14560 stats[k] = s[k] 14561 }) 14562 } 14563 const end = new Date() 14564 if (!stats.runTime) { 14565 stats.runTime = {} 14566 } 14567 stats.runTime[label] = end - start 14568 } 14569 stats.runTime.total = stats.endTime - stats.startTime 14570 opts.log.silly( 14571 'verify', 14572 'verification finished for', 14573 cache, 14574 'in', 14575 `${stats.runTime.total}ms` 14576 ) 14577 return stats 14578 } 14579 14580 async function markStartTime (cache, opts) { 14581 return { startTime: new Date() } 14582 } 14583 14584 async function markEndTime (cache, opts) { 14585 return { endTime: new Date() } 14586 } 14587 14588 async function fixPerms (cache, opts) { 14589 opts.log.silly('verify', 'fixing cache permissions') 14590 await mkdir(cache, { recursive: true }) 14591 return null 14592 } 14593 14594 // Implements a naive mark-and-sweep tracing garbage collector. 14595 // 14596 // The algorithm is basically as follows: 14597 // 1. Read (and filter) all index entries ("pointers") 14598 // 2. Mark each integrity value as "live" 14599 // 3. Read entire filesystem tree in `content-vX/` dir 14600 // 4. If content is live, verify its checksum and delete it if it fails 14601 // 5. If content is not marked as live, rm it. 14602 // 14603 async function garbageCollect (cache, opts) { 14604 opts.log.silly('verify', 'garbage collecting content') 14605 const indexStream = index.lsStream(cache) 14606 const liveContent = new Set() 14607 indexStream.on('data', (entry) => { 14608 if (opts.filter && !opts.filter(entry)) { 14609 return 14610 } 14611 14612 // integrity is stringified, re-parse it so we can get each hash 14613 const integrity = ssri.parse(entry.integrity) 14614 for (const algo in integrity) { 14615 liveContent.add(integrity[algo].toString()) 14616 } 14617 }) 14618 await new Promise((resolve, reject) => { 14619 indexStream.on('end', resolve).on('error', reject) 14620 }) 14621 const contentDir = contentPath.contentDir(cache) 14622 const files = await glob(path.join(contentDir, '**'), { 14623 follow: false, 14624 nodir: true, 14625 nosort: true, 14626 }) 14627 const stats = { 14628 verifiedContent: 0, 14629 reclaimedCount: 0, 14630 reclaimedSize: 0, 14631 badContentCount: 0, 14632 keptSize: 0, 14633 } 14634 await pMap( 14635 files, 14636 async (f) => { 14637 const split = f.split(/[/\\]/) 14638 const digest = split.slice(split.length - 3).join('') 14639 const algo = split[split.length - 4] 14640 const integrity = ssri.fromHex(digest, algo) 14641 if (liveContent.has(integrity.toString())) { 14642 const info = await verifyContent(f, integrity) 14643 if (!info.valid) { 14644 stats.reclaimedCount++ 14645 stats.badContentCount++ 14646 stats.reclaimedSize += info.size 14647 } else { 14648 stats.verifiedContent++ 14649 stats.keptSize += info.size 14650 } 14651 } else { 14652 // No entries refer to this content. We can delete. 14653 stats.reclaimedCount++ 14654 const s = await stat(f) 14655 await rm(f, { recursive: true, force: true }) 14656 stats.reclaimedSize += s.size 14657 } 14658 return stats 14659 }, 14660 { concurrency: opts.concurrency } 14661 ) 14662 return stats 14663 } 14664 14665 async function verifyContent (filepath, sri) { 14666 const contentInfo = {} 14667 try { 14668 const { size } = await stat(filepath) 14669 contentInfo.size = size 14670 contentInfo.valid = true 14671 await ssri.checkStream(new fsm.ReadStream(filepath), sri) 14672 } catch (err) { 14673 if (err.code === 'ENOENT') { 14674 return { size: 0, valid: false } 14675 } 14676 if (err.code !== 'EINTEGRITY') { 14677 throw err 14678 } 14679 14680 await rm(filepath, { recursive: true, force: true }) 14681 contentInfo.valid = false 14682 } 14683 return contentInfo 14684 } 14685 14686 async function rebuildIndex (cache, opts) { 14687 opts.log.silly('verify', 'rebuilding index') 14688 const entries = await index.ls(cache) 14689 const stats = { 14690 missingContent: 0, 14691 rejectedEntries: 0, 14692 totalEntries: 0, 14693 } 14694 const buckets = {} 14695 for (const k in entries) { 14696 /* istanbul ignore else */ 14697 if (hasOwnProperty(entries, k)) { 14698 const hashed = index.hashKey(k) 14699 const entry = entries[k] 14700 const excluded = opts.filter && !opts.filter(entry) 14701 excluded && stats.rejectedEntries++ 14702 if (buckets[hashed] && !excluded) { 14703 buckets[hashed].push(entry) 14704 } else if (buckets[hashed] && excluded) { 14705 // skip 14706 } else if (excluded) { 14707 buckets[hashed] = [] 14708 buckets[hashed]._path = index.bucketPath(cache, k) 14709 } else { 14710 buckets[hashed] = [entry] 14711 buckets[hashed]._path = index.bucketPath(cache, k) 14712 } 14713 } 14714 } 14715 await pMap( 14716 Object.keys(buckets), 14717 (key) => { 14718 return rebuildBucket(cache, buckets[key], stats, opts) 14719 }, 14720 { concurrency: opts.concurrency } 14721 ) 14722 return stats 14723 } 14724 14725 async function rebuildBucket (cache, bucket, stats, opts) { 14726 await truncate(bucket._path) 14727 // This needs to be serialized because cacache explicitly 14728 // lets very racy bucket conflicts clobber each other. 14729 for (const entry of bucket) { 14730 const content = contentPath(cache, entry.integrity) 14731 try { 14732 await stat(content) 14733 await index.insert(cache, entry.key, entry.integrity, { 14734 metadata: entry.metadata, 14735 size: entry.size, 14736 time: entry.time, 14737 }) 14738 stats.totalEntries++ 14739 } catch (err) { 14740 if (err.code === 'ENOENT') { 14741 stats.rejectedEntries++ 14742 stats.missingContent++ 14743 } else { 14744 throw err 14745 } 14746 } 14747 } 14748 } 14749 14750 function cleanTmp (cache, opts) { 14751 opts.log.silly('verify', 'cleaning tmp directory') 14752 return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) 14753 } 14754 14755 async function writeVerifile (cache, opts) { 14756 const verifile = path.join(cache, '_lastverified') 14757 opts.log.silly('verify', 'writing verifile to ' + verifile) 14758 return writeFile(verifile, `${Date.now()}`) 14759 } 14760 14761 module.exports.lastRun = lastRun 14762 14763 async function lastRun (cache) { 14764 const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) 14765 return new Date(+data) 14766 } 14767 14768 14769 /***/ }), 14770 14771 /***/ 2443: 14772 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14773 14774 var balanced = __nccwpck_require__(9417); 14775 14776 module.exports = expandTop; 14777 14778 var escSlash = '\0SLASH'+Math.random()+'\0'; 14779 var escOpen = '\0OPEN'+Math.random()+'\0'; 14780 var escClose = '\0CLOSE'+Math.random()+'\0'; 14781 var escComma = '\0COMMA'+Math.random()+'\0'; 14782 var escPeriod = '\0PERIOD'+Math.random()+'\0'; 14783 14784 function numeric(str) { 14785 return parseInt(str, 10) == str 14786 ? parseInt(str, 10) 14787 : str.charCodeAt(0); 14788 } 14789 14790 function escapeBraces(str) { 14791 return str.split('\\\\').join(escSlash) 14792 .split('\\{').join(escOpen) 14793 .split('\\}').join(escClose) 14794 .split('\\,').join(escComma) 14795 .split('\\.').join(escPeriod); 14796 } 14797 14798 function unescapeBraces(str) { 14799 return str.split(escSlash).join('\\') 14800 .split(escOpen).join('{') 14801 .split(escClose).join('}') 14802 .split(escComma).join(',') 14803 .split(escPeriod).join('.'); 14804 } 14805 14806 14807 // Basically just str.split(","), but handling cases 14808 // where we have nested braced sections, which should be 14809 // treated as individual members, like {a,{b,c},d} 14810 function parseCommaParts(str) { 14811 if (!str) 14812 return ['']; 14813 14814 var parts = []; 14815 var m = balanced('{', '}', str); 14816 14817 if (!m) 14818 return str.split(','); 14819 14820 var pre = m.pre; 14821 var body = m.body; 14822 var post = m.post; 14823 var p = pre.split(','); 14824 14825 p[p.length-1] += '{' + body + '}'; 14826 var postParts = parseCommaParts(post); 14827 if (post.length) { 14828 p[p.length-1] += postParts.shift(); 14829 p.push.apply(p, postParts); 14830 } 14831 14832 parts.push.apply(parts, p); 14833 14834 return parts; 14835 } 14836 14837 function expandTop(str) { 14838 if (!str) 14839 return []; 14840 14841 // I don't know why Bash 4.3 does this, but it does. 14842 // Anything starting with {} will have the first two bytes preserved 14843 // but *only* at the top level, so {},a}b will not expand to anything, 14844 // but a{},b}c will be expanded to [a}c,abc]. 14845 // One could argue that this is a bug in Bash, but since the goal of 14846 // this module is to match Bash's rules, we escape a leading {} 14847 if (str.substr(0, 2) === '{}') { 14848 str = '\\{\\}' + str.substr(2); 14849 } 14850 14851 return expand(escapeBraces(str), true).map(unescapeBraces); 14852 } 14853 14854 function embrace(str) { 14855 return '{' + str + '}'; 14856 } 14857 function isPadded(el) { 14858 return /^-?0\d/.test(el); 14859 } 14860 14861 function lte(i, y) { 14862 return i <= y; 14863 } 14864 function gte(i, y) { 14865 return i >= y; 14866 } 14867 14868 function expand(str, isTop) { 14869 var expansions = []; 14870 14871 var m = balanced('{', '}', str); 14872 if (!m) return [str]; 14873 14874 // no need to expand pre, since it is guaranteed to be free of brace-sets 14875 var pre = m.pre; 14876 var post = m.post.length 14877 ? expand(m.post, false) 14878 : ['']; 14879 14880 if (/\$$/.test(m.pre)) { 14881 for (var k = 0; k < post.length; k++) { 14882 var expansion = pre+ '{' + m.body + '}' + post[k]; 14883 expansions.push(expansion); 14884 } 14885 } else { 14886 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); 14887 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); 14888 var isSequence = isNumericSequence || isAlphaSequence; 14889 var isOptions = m.body.indexOf(',') >= 0; 14890 if (!isSequence && !isOptions) { 14891 // {a},b} 14892 if (m.post.match(/,.*\}/)) { 14893 str = m.pre + '{' + m.body + escClose + m.post; 14894 return expand(str); 14895 } 14896 return [str]; 14897 } 14898 14899 var n; 14900 if (isSequence) { 14901 n = m.body.split(/\.\./); 14902 } else { 14903 n = parseCommaParts(m.body); 14904 if (n.length === 1) { 14905 // x{{a,b}}y ==> x{a}y x{b}y 14906 n = expand(n[0], false).map(embrace); 14907 if (n.length === 1) { 14908 return post.map(function(p) { 14909 return m.pre + n[0] + p; 14910 }); 14911 } 14912 } 14913 } 14914 14915 // at this point, n is the parts, and we know it's not a comma set 14916 // with a single entry. 14917 var N; 14918 14919 if (isSequence) { 14920 var x = numeric(n[0]); 14921 var y = numeric(n[1]); 14922 var width = Math.max(n[0].length, n[1].length) 14923 var incr = n.length == 3 14924 ? Math.abs(numeric(n[2])) 14925 : 1; 14926 var test = lte; 14927 var reverse = y < x; 14928 if (reverse) { 14929 incr *= -1; 14930 test = gte; 14931 } 14932 var pad = n.some(isPadded); 14933 14934 N = []; 14935 14936 for (var i = x; test(i, y); i += incr) { 14937 var c; 14938 if (isAlphaSequence) { 14939 c = String.fromCharCode(i); 14940 if (c === '\\') 14941 c = ''; 14942 } else { 14943 c = String(i); 14944 if (pad) { 14945 var need = width - c.length; 14946 if (need > 0) { 14947 var z = new Array(need + 1).join('0'); 14948 if (i < 0) 14949 c = '-' + z + c.slice(1); 14950 else 14951 c = z + c; 14952 } 14953 } 14954 } 14955 N.push(c); 14956 } 14957 } else { 14958 N = []; 14959 14960 for (var j = 0; j < n.length; j++) { 14961 N.push.apply(N, expand(n[j], false)); 14962 } 14963 } 14964 14965 for (var j = 0; j < N.length; j++) { 14966 for (var k = 0; k < post.length; k++) { 14967 var expansion = pre + N[j] + post[k]; 14968 if (!isTop || isSequence || expansion) 14969 expansions.push(expansion); 14970 } 14971 } 14972 } 14973 14974 return expansions; 14975 } 14976 14977 14978 14979 /***/ }), 14980 14981 /***/ 7972: 14982 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 14983 14984 "use strict"; 14985 14986 const os = __nccwpck_require__(2037); 14987 14988 const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; 14989 const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; 14990 const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); 14991 14992 module.exports = (stack, options) => { 14993 options = Object.assign({pretty: false}, options); 14994 14995 return stack.replace(/\\/g, '/') 14996 .split('\n') 14997 .filter(line => { 14998 const pathMatches = line.match(extractPathRegex); 14999 if (pathMatches === null || !pathMatches[1]) { 15000 return true; 15001 } 15002 15003 const match = pathMatches[1]; 15004 15005 // Electron 15006 if ( 15007 match.includes('.app/Contents/Resources/electron.asar') || 15008 match.includes('.app/Contents/Resources/default_app.asar') 15009 ) { 15010 return false; 15011 } 15012 15013 return !pathRegex.test(match); 15014 }) 15015 .filter(line => line.trim() !== '') 15016 .map(line => { 15017 if (options.pretty) { 15018 return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); 15019 } 15020 15021 return line; 15022 }) 15023 .join('\n'); 15024 }; 15025 15026 15027 /***/ }), 15028 15029 /***/ 8222: 15030 /***/ ((module, exports, __nccwpck_require__) => { 15031 15032 /* eslint-env browser */ 15033 15034 /** 15035 * This is the web browser implementation of `debug()`. 15036 */ 15037 15038 exports.formatArgs = formatArgs; 15039 exports.save = save; 15040 exports.load = load; 15041 exports.useColors = useColors; 15042 exports.storage = localstorage(); 15043 exports.destroy = (() => { 15044 let warned = false; 15045 15046 return () => { 15047 if (!warned) { 15048 warned = true; 15049 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); 15050 } 15051 }; 15052 })(); 15053 15054 /** 15055 * Colors. 15056 */ 15057 15058 exports.colors = [ 15059 '#0000CC', 15060 '#0000FF', 15061 '#0033CC', 15062 '#0033FF', 15063 '#0066CC', 15064 '#0066FF', 15065 '#0099CC', 15066 '#0099FF', 15067 '#00CC00', 15068 '#00CC33', 15069 '#00CC66', 15070 '#00CC99', 15071 '#00CCCC', 15072 '#00CCFF', 15073 '#3300CC', 15074 '#3300FF', 15075 '#3333CC', 15076 '#3333FF', 15077 '#3366CC', 15078 '#3366FF', 15079 '#3399CC', 15080 '#3399FF', 15081 '#33CC00', 15082 '#33CC33', 15083 '#33CC66', 15084 '#33CC99', 15085 '#33CCCC', 15086 '#33CCFF', 15087 '#6600CC', 15088 '#6600FF', 15089 '#6633CC', 15090 '#6633FF', 15091 '#66CC00', 15092 '#66CC33', 15093 '#9900CC', 15094 '#9900FF', 15095 '#9933CC', 15096 '#9933FF', 15097 '#99CC00', 15098 '#99CC33', 15099 '#CC0000', 15100 '#CC0033', 15101 '#CC0066', 15102 '#CC0099', 15103 '#CC00CC', 15104 '#CC00FF', 15105 '#CC3300', 15106 '#CC3333', 15107 '#CC3366', 15108 '#CC3399', 15109 '#CC33CC', 15110 '#CC33FF', 15111 '#CC6600', 15112 '#CC6633', 15113 '#CC9900', 15114 '#CC9933', 15115 '#CCCC00', 15116 '#CCCC33', 15117 '#FF0000', 15118 '#FF0033', 15119 '#FF0066', 15120 '#FF0099', 15121 '#FF00CC', 15122 '#FF00FF', 15123 '#FF3300', 15124 '#FF3333', 15125 '#FF3366', 15126 '#FF3399', 15127 '#FF33CC', 15128 '#FF33FF', 15129 '#FF6600', 15130 '#FF6633', 15131 '#FF9900', 15132 '#FF9933', 15133 '#FFCC00', 15134 '#FFCC33' 15135 ]; 15136 15137 /** 15138 * Currently only WebKit-based Web Inspectors, Firefox >= v31, 15139 * and the Firebug extension (any Firefox version) are known 15140 * to support "%c" CSS customizations. 15141 * 15142 * TODO: add a `localStorage` variable to explicitly enable/disable colors 15143 */ 15144 15145 // eslint-disable-next-line complexity 15146 function useColors() { 15147 // NB: In an Electron preload script, document will be defined but not fully 15148 // initialized. Since we know we're in Chrome, we'll just detect this case 15149 // explicitly 15150 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { 15151 return true; 15152 } 15153 15154 // Internet Explorer and Edge do not support colors. 15155 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { 15156 return false; 15157 } 15158 15159 // Is webkit? http://stackoverflow.com/a/16459606/376773 15160 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 15161 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || 15162 // Is firebug? http://stackoverflow.com/a/398120/376773 15163 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || 15164 // Is firefox >= v31? 15165 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages 15166 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || 15167 // Double check webkit in userAgent just in case we are in a worker 15168 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); 15169 } 15170 15171 /** 15172 * Colorize log arguments if enabled. 15173 * 15174 * @api public 15175 */ 15176 15177 function formatArgs(args) { 15178 args[0] = (this.useColors ? '%c' : '') + 15179 this.namespace + 15180 (this.useColors ? ' %c' : ' ') + 15181 args[0] + 15182 (this.useColors ? '%c ' : ' ') + 15183 '+' + module.exports.humanize(this.diff); 15184 15185 if (!this.useColors) { 15186 return; 15187 } 15188 15189 const c = 'color: ' + this.color; 15190 args.splice(1, 0, c, 'color: inherit'); 15191 15192 // The final "%c" is somewhat tricky, because there could be other 15193 // arguments passed either before or after the %c, so we need to 15194 // figure out the correct index to insert the CSS into 15195 let index = 0; 15196 let lastC = 0; 15197 args[0].replace(/%[a-zA-Z%]/g, match => { 15198 if (match === '%%') { 15199 return; 15200 } 15201 index++; 15202 if (match === '%c') { 15203 // We only are interested in the *last* %c 15204 // (the user may have provided their own) 15205 lastC = index; 15206 } 15207 }); 15208 15209 args.splice(lastC, 0, c); 15210 } 15211 15212 /** 15213 * Invokes `console.debug()` when available. 15214 * No-op when `console.debug` is not a "function". 15215 * If `console.debug` is not available, falls back 15216 * to `console.log`. 15217 * 15218 * @api public 15219 */ 15220 exports.log = console.debug || console.log || (() => {}); 15221 15222 /** 15223 * Save `namespaces`. 15224 * 15225 * @param {String} namespaces 15226 * @api private 15227 */ 15228 function save(namespaces) { 15229 try { 15230 if (namespaces) { 15231 exports.storage.setItem('debug', namespaces); 15232 } else { 15233 exports.storage.removeItem('debug'); 15234 } 15235 } catch (error) { 15236 // Swallow 15237 // XXX (@Qix-) should we be logging these? 15238 } 15239 } 15240 15241 /** 15242 * Load `namespaces`. 15243 * 15244 * @return {String} returns the previously persisted debug modes 15245 * @api private 15246 */ 15247 function load() { 15248 let r; 15249 try { 15250 r = exports.storage.getItem('debug'); 15251 } catch (error) { 15252 // Swallow 15253 // XXX (@Qix-) should we be logging these? 15254 } 15255 15256 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG 15257 if (!r && typeof process !== 'undefined' && 'env' in process) { 15258 r = process.env.DEBUG; 15259 } 15260 15261 return r; 15262 } 15263 15264 /** 15265 * Localstorage attempts to return the localstorage. 15266 * 15267 * This is necessary because safari throws 15268 * when a user disables cookies/localstorage 15269 * and you attempt to access it. 15270 * 15271 * @return {LocalStorage} 15272 * @api private 15273 */ 15274 15275 function localstorage() { 15276 try { 15277 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context 15278 // The Browser also has localStorage in the global context. 15279 return localStorage; 15280 } catch (error) { 15281 // Swallow 15282 // XXX (@Qix-) should we be logging these? 15283 } 15284 } 15285 15286 module.exports = __nccwpck_require__(6243)(exports); 15287 15288 const {formatters} = module.exports; 15289 15290 /** 15291 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. 15292 */ 15293 15294 formatters.j = function (v) { 15295 try { 15296 return JSON.stringify(v); 15297 } catch (error) { 15298 return '[UnexpectedJSONParseError]: ' + error.message; 15299 } 15300 }; 15301 15302 15303 /***/ }), 15304 15305 /***/ 6243: 15306 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 15307 15308 15309 /** 15310 * This is the common logic for both the Node.js and web browser 15311 * implementations of `debug()`. 15312 */ 15313 15314 function setup(env) { 15315 createDebug.debug = createDebug; 15316 createDebug.default = createDebug; 15317 createDebug.coerce = coerce; 15318 createDebug.disable = disable; 15319 createDebug.enable = enable; 15320 createDebug.enabled = enabled; 15321 createDebug.humanize = __nccwpck_require__(9992); 15322 createDebug.destroy = destroy; 15323 15324 Object.keys(env).forEach(key => { 15325 createDebug[key] = env[key]; 15326 }); 15327 15328 /** 15329 * The currently active debug mode names, and names to skip. 15330 */ 15331 15332 createDebug.names = []; 15333 createDebug.skips = []; 15334 15335 /** 15336 * Map of special "%n" handling functions, for the debug "format" argument. 15337 * 15338 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". 15339 */ 15340 createDebug.formatters = {}; 15341 15342 /** 15343 * Selects a color for a debug namespace 15344 * @param {String} namespace The namespace string for the debug instance to be colored 15345 * @return {Number|String} An ANSI color code for the given namespace 15346 * @api private 15347 */ 15348 function selectColor(namespace) { 15349 let hash = 0; 15350 15351 for (let i = 0; i < namespace.length; i++) { 15352 hash = ((hash << 5) - hash) + namespace.charCodeAt(i); 15353 hash |= 0; // Convert to 32bit integer 15354 } 15355 15356 return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; 15357 } 15358 createDebug.selectColor = selectColor; 15359 15360 /** 15361 * Create a debugger with the given `namespace`. 15362 * 15363 * @param {String} namespace 15364 * @return {Function} 15365 * @api public 15366 */ 15367 function createDebug(namespace) { 15368 let prevTime; 15369 let enableOverride = null; 15370 let namespacesCache; 15371 let enabledCache; 15372 15373 function debug(...args) { 15374 // Disabled? 15375 if (!debug.enabled) { 15376 return; 15377 } 15378 15379 const self = debug; 15380 15381 // Set `diff` timestamp 15382 const curr = Number(new Date()); 15383 const ms = curr - (prevTime || curr); 15384 self.diff = ms; 15385 self.prev = prevTime; 15386 self.curr = curr; 15387 prevTime = curr; 15388 15389 args[0] = createDebug.coerce(args[0]); 15390 15391 if (typeof args[0] !== 'string') { 15392 // Anything else let's inspect with %O 15393 args.unshift('%O'); 15394 } 15395 15396 // Apply any `formatters` transformations 15397 let index = 0; 15398 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { 15399 // If we encounter an escaped % then don't increase the array index 15400 if (match === '%%') { 15401 return '%'; 15402 } 15403 index++; 15404 const formatter = createDebug.formatters[format]; 15405 if (typeof formatter === 'function') { 15406 const val = args[index]; 15407 match = formatter.call(self, val); 15408 15409 // Now we need to remove `args[index]` since it's inlined in the `format` 15410 args.splice(index, 1); 15411 index--; 15412 } 15413 return match; 15414 }); 15415 15416 // Apply env-specific formatting (colors, etc.) 15417 createDebug.formatArgs.call(self, args); 15418 15419 const logFn = self.log || createDebug.log; 15420 logFn.apply(self, args); 15421 } 15422 15423 debug.namespace = namespace; 15424 debug.useColors = createDebug.useColors(); 15425 debug.color = createDebug.selectColor(namespace); 15426 debug.extend = extend; 15427 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. 15428 15429 Object.defineProperty(debug, 'enabled', { 15430 enumerable: true, 15431 configurable: false, 15432 get: () => { 15433 if (enableOverride !== null) { 15434 return enableOverride; 15435 } 15436 if (namespacesCache !== createDebug.namespaces) { 15437 namespacesCache = createDebug.namespaces; 15438 enabledCache = createDebug.enabled(namespace); 15439 } 15440 15441 return enabledCache; 15442 }, 15443 set: v => { 15444 enableOverride = v; 15445 } 15446 }); 15447 15448 // Env-specific initialization logic for debug instances 15449 if (typeof createDebug.init === 'function') { 15450 createDebug.init(debug); 15451 } 15452 15453 return debug; 15454 } 15455 15456 function extend(namespace, delimiter) { 15457 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); 15458 newDebug.log = this.log; 15459 return newDebug; 15460 } 15461 15462 /** 15463 * Enables a debug mode by namespaces. This can include modes 15464 * separated by a colon and wildcards. 15465 * 15466 * @param {String} namespaces 15467 * @api public 15468 */ 15469 function enable(namespaces) { 15470 createDebug.save(namespaces); 15471 createDebug.namespaces = namespaces; 15472 15473 createDebug.names = []; 15474 createDebug.skips = []; 15475 15476 let i; 15477 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); 15478 const len = split.length; 15479 15480 for (i = 0; i < len; i++) { 15481 if (!split[i]) { 15482 // ignore empty strings 15483 continue; 15484 } 15485 15486 namespaces = split[i].replace(/\*/g, '.*?'); 15487 15488 if (namespaces[0] === '-') { 15489 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); 15490 } else { 15491 createDebug.names.push(new RegExp('^' + namespaces + '$')); 15492 } 15493 } 15494 } 15495 15496 /** 15497 * Disable debug output. 15498 * 15499 * @return {String} namespaces 15500 * @api public 15501 */ 15502 function disable() { 15503 const namespaces = [ 15504 ...createDebug.names.map(toNamespace), 15505 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) 15506 ].join(','); 15507 createDebug.enable(''); 15508 return namespaces; 15509 } 15510 15511 /** 15512 * Returns true if the given mode name is enabled, false otherwise. 15513 * 15514 * @param {String} name 15515 * @return {Boolean} 15516 * @api public 15517 */ 15518 function enabled(name) { 15519 if (name[name.length - 1] === '*') { 15520 return true; 15521 } 15522 15523 let i; 15524 let len; 15525 15526 for (i = 0, len = createDebug.skips.length; i < len; i++) { 15527 if (createDebug.skips[i].test(name)) { 15528 return false; 15529 } 15530 } 15531 15532 for (i = 0, len = createDebug.names.length; i < len; i++) { 15533 if (createDebug.names[i].test(name)) { 15534 return true; 15535 } 15536 } 15537 15538 return false; 15539 } 15540 15541 /** 15542 * Convert regexp to namespace 15543 * 15544 * @param {RegExp} regxep 15545 * @return {String} namespace 15546 * @api private 15547 */ 15548 function toNamespace(regexp) { 15549 return regexp.toString() 15550 .substring(2, regexp.toString().length - 2) 15551 .replace(/\.\*\?$/, '*'); 15552 } 15553 15554 /** 15555 * Coerce `val`. 15556 * 15557 * @param {Mixed} val 15558 * @return {Mixed} 15559 * @api private 15560 */ 15561 function coerce(val) { 15562 if (val instanceof Error) { 15563 return val.stack || val.message; 15564 } 15565 return val; 15566 } 15567 15568 /** 15569 * XXX DO NOT USE. This is a temporary stub function. 15570 * XXX It WILL be removed in the next major release. 15571 */ 15572 function destroy() { 15573 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); 15574 } 15575 15576 createDebug.enable(createDebug.load()); 15577 15578 return createDebug; 15579 } 15580 15581 module.exports = setup; 15582 15583 15584 /***/ }), 15585 15586 /***/ 8237: 15587 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 15588 15589 /** 15590 * Detect Electron renderer / nwjs process, which is node, but we should 15591 * treat as a browser. 15592 */ 15593 15594 if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { 15595 module.exports = __nccwpck_require__(8222); 15596 } else { 15597 module.exports = __nccwpck_require__(4874); 15598 } 15599 15600 15601 /***/ }), 15602 15603 /***/ 4874: 15604 /***/ ((module, exports, __nccwpck_require__) => { 15605 15606 /** 15607 * Module dependencies. 15608 */ 15609 15610 const tty = __nccwpck_require__(6224); 15611 const util = __nccwpck_require__(3837); 15612 15613 /** 15614 * This is the Node.js implementation of `debug()`. 15615 */ 15616 15617 exports.init = init; 15618 exports.log = log; 15619 exports.formatArgs = formatArgs; 15620 exports.save = save; 15621 exports.load = load; 15622 exports.useColors = useColors; 15623 exports.destroy = util.deprecate( 15624 () => {}, 15625 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' 15626 ); 15627 15628 /** 15629 * Colors. 15630 */ 15631 15632 exports.colors = [6, 2, 3, 4, 5, 1]; 15633 15634 try { 15635 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) 15636 // eslint-disable-next-line import/no-extraneous-dependencies 15637 const supportsColor = __nccwpck_require__(9318); 15638 15639 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { 15640 exports.colors = [ 15641 20, 15642 21, 15643 26, 15644 27, 15645 32, 15646 33, 15647 38, 15648 39, 15649 40, 15650 41, 15651 42, 15652 43, 15653 44, 15654 45, 15655 56, 15656 57, 15657 62, 15658 63, 15659 68, 15660 69, 15661 74, 15662 75, 15663 76, 15664 77, 15665 78, 15666 79, 15667 80, 15668 81, 15669 92, 15670 93, 15671 98, 15672 99, 15673 112, 15674 113, 15675 128, 15676 129, 15677 134, 15678 135, 15679 148, 15680 149, 15681 160, 15682 161, 15683 162, 15684 163, 15685 164, 15686 165, 15687 166, 15688 167, 15689 168, 15690 169, 15691 170, 15692 171, 15693 172, 15694 173, 15695 178, 15696 179, 15697 184, 15698 185, 15699 196, 15700 197, 15701 198, 15702 199, 15703 200, 15704 201, 15705 202, 15706 203, 15707 204, 15708 205, 15709 206, 15710 207, 15711 208, 15712 209, 15713 214, 15714 215, 15715 220, 15716 221 15717 ]; 15718 } 15719 } catch (error) { 15720 // Swallow - we only care if `supports-color` is available; it doesn't have to be. 15721 } 15722 15723 /** 15724 * Build up the default `inspectOpts` object from the environment variables. 15725 * 15726 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js 15727 */ 15728 15729 exports.inspectOpts = Object.keys(process.env).filter(key => { 15730 return /^debug_/i.test(key); 15731 }).reduce((obj, key) => { 15732 // Camel-case 15733 const prop = key 15734 .substring(6) 15735 .toLowerCase() 15736 .replace(/_([a-z])/g, (_, k) => { 15737 return k.toUpperCase(); 15738 }); 15739 15740 // Coerce string value into JS value 15741 let val = process.env[key]; 15742 if (/^(yes|on|true|enabled)$/i.test(val)) { 15743 val = true; 15744 } else if (/^(no|off|false|disabled)$/i.test(val)) { 15745 val = false; 15746 } else if (val === 'null') { 15747 val = null; 15748 } else { 15749 val = Number(val); 15750 } 15751 15752 obj[prop] = val; 15753 return obj; 15754 }, {}); 15755 15756 /** 15757 * Is stdout a TTY? Colored output is enabled when `true`. 15758 */ 15759 15760 function useColors() { 15761 return 'colors' in exports.inspectOpts ? 15762 Boolean(exports.inspectOpts.colors) : 15763 tty.isatty(process.stderr.fd); 15764 } 15765 15766 /** 15767 * Adds ANSI color escape codes if enabled. 15768 * 15769 * @api public 15770 */ 15771 15772 function formatArgs(args) { 15773 const {namespace: name, useColors} = this; 15774 15775 if (useColors) { 15776 const c = this.color; 15777 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); 15778 const prefix = ` ${colorCode};1m${name} \u001B[0m`; 15779 15780 args[0] = prefix + args[0].split('\n').join('\n' + prefix); 15781 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); 15782 } else { 15783 args[0] = getDate() + name + ' ' + args[0]; 15784 } 15785 } 15786 15787 function getDate() { 15788 if (exports.inspectOpts.hideDate) { 15789 return ''; 15790 } 15791 return new Date().toISOString() + ' '; 15792 } 15793 15794 /** 15795 * Invokes `util.format()` with the specified arguments and writes to stderr. 15796 */ 15797 15798 function log(...args) { 15799 return process.stderr.write(util.format(...args) + '\n'); 15800 } 15801 15802 /** 15803 * Save `namespaces`. 15804 * 15805 * @param {String} namespaces 15806 * @api private 15807 */ 15808 function save(namespaces) { 15809 if (namespaces) { 15810 process.env.DEBUG = namespaces; 15811 } else { 15812 // If you set a process.env field to null or undefined, it gets cast to the 15813 // string 'null' or 'undefined'. Just delete instead. 15814 delete process.env.DEBUG; 15815 } 15816 } 15817 15818 /** 15819 * Load `namespaces`. 15820 * 15821 * @return {String} returns the previously persisted debug modes 15822 * @api private 15823 */ 15824 15825 function load() { 15826 return process.env.DEBUG; 15827 } 15828 15829 /** 15830 * Init logic for `debug` instances. 15831 * 15832 * Create a new `inspectOpts` object in case `useColors` is set 15833 * differently for a particular `debug` instance. 15834 */ 15835 15836 function init(debug) { 15837 debug.inspectOpts = {}; 15838 15839 const keys = Object.keys(exports.inspectOpts); 15840 for (let i = 0; i < keys.length; i++) { 15841 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; 15842 } 15843 } 15844 15845 module.exports = __nccwpck_require__(6243)(exports); 15846 15847 const {formatters} = module.exports; 15848 15849 /** 15850 * Map %o to `util.inspect()`, all on a single line. 15851 */ 15852 15853 formatters.o = function (v) { 15854 this.inspectOpts.colors = this.useColors; 15855 return util.inspect(v, this.inspectOpts) 15856 .split('\n') 15857 .map(str => str.trim()) 15858 .join(' '); 15859 }; 15860 15861 /** 15862 * Map %O to `util.inspect()`, allowing multiple lines if needed. 15863 */ 15864 15865 formatters.O = function (v) { 15866 this.inspectOpts.colors = this.useColors; 15867 return util.inspect(v, this.inspectOpts); 15868 }; 15869 15870 15871 /***/ }), 15872 15873 /***/ 2997: 15874 /***/ ((module) => { 15875 15876 "use strict"; 15877 15878 15879 function assign(obj, props) { 15880 for (const key in props) { 15881 Object.defineProperty(obj, key, { 15882 value: props[key], 15883 enumerable: true, 15884 configurable: true, 15885 }); 15886 } 15887 15888 return obj; 15889 } 15890 15891 function createError(err, code, props) { 15892 if (!err || typeof err === 'string') { 15893 throw new TypeError('Please pass an Error to err-code'); 15894 } 15895 15896 if (!props) { 15897 props = {}; 15898 } 15899 15900 if (typeof code === 'object') { 15901 props = code; 15902 code = undefined; 15903 } 15904 15905 if (code != null) { 15906 props.code = code; 15907 } 15908 15909 try { 15910 return assign(err, props); 15911 } catch (_) { 15912 props.message = err.message; 15913 props.stack = err.stack; 15914 15915 const ErrClass = function () {}; 15916 15917 ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); 15918 15919 return assign(new ErrClass(), props); 15920 } 15921 } 15922 15923 module.exports = createError; 15924 15925 15926 /***/ }), 15927 15928 /***/ 968: 15929 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 15930 15931 "use strict"; 15932 15933 const { Minipass } = __nccwpck_require__(4968) 15934 const EE = (__nccwpck_require__(2361).EventEmitter) 15935 const fs = __nccwpck_require__(7147) 15936 15937 const writev = fs.writev 15938 15939 const _autoClose = Symbol('_autoClose') 15940 const _close = Symbol('_close') 15941 const _ended = Symbol('_ended') 15942 const _fd = Symbol('_fd') 15943 const _finished = Symbol('_finished') 15944 const _flags = Symbol('_flags') 15945 const _flush = Symbol('_flush') 15946 const _handleChunk = Symbol('_handleChunk') 15947 const _makeBuf = Symbol('_makeBuf') 15948 const _mode = Symbol('_mode') 15949 const _needDrain = Symbol('_needDrain') 15950 const _onerror = Symbol('_onerror') 15951 const _onopen = Symbol('_onopen') 15952 const _onread = Symbol('_onread') 15953 const _onwrite = Symbol('_onwrite') 15954 const _open = Symbol('_open') 15955 const _path = Symbol('_path') 15956 const _pos = Symbol('_pos') 15957 const _queue = Symbol('_queue') 15958 const _read = Symbol('_read') 15959 const _readSize = Symbol('_readSize') 15960 const _reading = Symbol('_reading') 15961 const _remain = Symbol('_remain') 15962 const _size = Symbol('_size') 15963 const _write = Symbol('_write') 15964 const _writing = Symbol('_writing') 15965 const _defaultFlag = Symbol('_defaultFlag') 15966 const _errored = Symbol('_errored') 15967 15968 class ReadStream extends Minipass { 15969 constructor (path, opt) { 15970 opt = opt || {} 15971 super(opt) 15972 15973 this.readable = true 15974 this.writable = false 15975 15976 if (typeof path !== 'string') { 15977 throw new TypeError('path must be a string') 15978 } 15979 15980 this[_errored] = false 15981 this[_fd] = typeof opt.fd === 'number' ? opt.fd : null 15982 this[_path] = path 15983 this[_readSize] = opt.readSize || 16 * 1024 * 1024 15984 this[_reading] = false 15985 this[_size] = typeof opt.size === 'number' ? opt.size : Infinity 15986 this[_remain] = this[_size] 15987 this[_autoClose] = typeof opt.autoClose === 'boolean' ? 15988 opt.autoClose : true 15989 15990 if (typeof this[_fd] === 'number') { 15991 this[_read]() 15992 } else { 15993 this[_open]() 15994 } 15995 } 15996 15997 get fd () { 15998 return this[_fd] 15999 } 16000 16001 get path () { 16002 return this[_path] 16003 } 16004 16005 write () { 16006 throw new TypeError('this is a readable stream') 16007 } 16008 16009 end () { 16010 throw new TypeError('this is a readable stream') 16011 } 16012 16013 [_open] () { 16014 fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) 16015 } 16016 16017 [_onopen] (er, fd) { 16018 if (er) { 16019 this[_onerror](er) 16020 } else { 16021 this[_fd] = fd 16022 this.emit('open', fd) 16023 this[_read]() 16024 } 16025 } 16026 16027 [_makeBuf] () { 16028 return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) 16029 } 16030 16031 [_read] () { 16032 if (!this[_reading]) { 16033 this[_reading] = true 16034 const buf = this[_makeBuf]() 16035 /* istanbul ignore if */ 16036 if (buf.length === 0) { 16037 return process.nextTick(() => this[_onread](null, 0, buf)) 16038 } 16039 fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => 16040 this[_onread](er, br, b)) 16041 } 16042 } 16043 16044 [_onread] (er, br, buf) { 16045 this[_reading] = false 16046 if (er) { 16047 this[_onerror](er) 16048 } else if (this[_handleChunk](br, buf)) { 16049 this[_read]() 16050 } 16051 } 16052 16053 [_close] () { 16054 if (this[_autoClose] && typeof this[_fd] === 'number') { 16055 const fd = this[_fd] 16056 this[_fd] = null 16057 fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) 16058 } 16059 } 16060 16061 [_onerror] (er) { 16062 this[_reading] = true 16063 this[_close]() 16064 this.emit('error', er) 16065 } 16066 16067 [_handleChunk] (br, buf) { 16068 let ret = false 16069 // no effect if infinite 16070 this[_remain] -= br 16071 if (br > 0) { 16072 ret = super.write(br < buf.length ? buf.slice(0, br) : buf) 16073 } 16074 16075 if (br === 0 || this[_remain] <= 0) { 16076 ret = false 16077 this[_close]() 16078 super.end() 16079 } 16080 16081 return ret 16082 } 16083 16084 emit (ev, data) { 16085 switch (ev) { 16086 case 'prefinish': 16087 case 'finish': 16088 break 16089 16090 case 'drain': 16091 if (typeof this[_fd] === 'number') { 16092 this[_read]() 16093 } 16094 break 16095 16096 case 'error': 16097 if (this[_errored]) { 16098 return 16099 } 16100 this[_errored] = true 16101 return super.emit(ev, data) 16102 16103 default: 16104 return super.emit(ev, data) 16105 } 16106 } 16107 } 16108 16109 class ReadStreamSync extends ReadStream { 16110 [_open] () { 16111 let threw = true 16112 try { 16113 this[_onopen](null, fs.openSync(this[_path], 'r')) 16114 threw = false 16115 } finally { 16116 if (threw) { 16117 this[_close]() 16118 } 16119 } 16120 } 16121 16122 [_read] () { 16123 let threw = true 16124 try { 16125 if (!this[_reading]) { 16126 this[_reading] = true 16127 do { 16128 const buf = this[_makeBuf]() 16129 /* istanbul ignore next */ 16130 const br = buf.length === 0 ? 0 16131 : fs.readSync(this[_fd], buf, 0, buf.length, null) 16132 if (!this[_handleChunk](br, buf)) { 16133 break 16134 } 16135 } while (true) 16136 this[_reading] = false 16137 } 16138 threw = false 16139 } finally { 16140 if (threw) { 16141 this[_close]() 16142 } 16143 } 16144 } 16145 16146 [_close] () { 16147 if (this[_autoClose] && typeof this[_fd] === 'number') { 16148 const fd = this[_fd] 16149 this[_fd] = null 16150 fs.closeSync(fd) 16151 this.emit('close') 16152 } 16153 } 16154 } 16155 16156 class WriteStream extends EE { 16157 constructor (path, opt) { 16158 opt = opt || {} 16159 super(opt) 16160 this.readable = false 16161 this.writable = true 16162 this[_errored] = false 16163 this[_writing] = false 16164 this[_ended] = false 16165 this[_needDrain] = false 16166 this[_queue] = [] 16167 this[_path] = path 16168 this[_fd] = typeof opt.fd === 'number' ? opt.fd : null 16169 this[_mode] = opt.mode === undefined ? 0o666 : opt.mode 16170 this[_pos] = typeof opt.start === 'number' ? opt.start : null 16171 this[_autoClose] = typeof opt.autoClose === 'boolean' ? 16172 opt.autoClose : true 16173 16174 // truncating makes no sense when writing into the middle 16175 const defaultFlag = this[_pos] !== null ? 'r+' : 'w' 16176 this[_defaultFlag] = opt.flags === undefined 16177 this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags 16178 16179 if (this[_fd] === null) { 16180 this[_open]() 16181 } 16182 } 16183 16184 emit (ev, data) { 16185 if (ev === 'error') { 16186 if (this[_errored]) { 16187 return 16188 } 16189 this[_errored] = true 16190 } 16191 return super.emit(ev, data) 16192 } 16193 16194 get fd () { 16195 return this[_fd] 16196 } 16197 16198 get path () { 16199 return this[_path] 16200 } 16201 16202 [_onerror] (er) { 16203 this[_close]() 16204 this[_writing] = true 16205 this.emit('error', er) 16206 } 16207 16208 [_open] () { 16209 fs.open(this[_path], this[_flags], this[_mode], 16210 (er, fd) => this[_onopen](er, fd)) 16211 } 16212 16213 [_onopen] (er, fd) { 16214 if (this[_defaultFlag] && 16215 this[_flags] === 'r+' && 16216 er && er.code === 'ENOENT') { 16217 this[_flags] = 'w' 16218 this[_open]() 16219 } else if (er) { 16220 this[_onerror](er) 16221 } else { 16222 this[_fd] = fd 16223 this.emit('open', fd) 16224 if (!this[_writing]) { 16225 this[_flush]() 16226 } 16227 } 16228 } 16229 16230 end (buf, enc) { 16231 if (buf) { 16232 this.write(buf, enc) 16233 } 16234 16235 this[_ended] = true 16236 16237 // synthetic after-write logic, where drain/finish live 16238 if (!this[_writing] && !this[_queue].length && 16239 typeof this[_fd] === 'number') { 16240 this[_onwrite](null, 0) 16241 } 16242 return this 16243 } 16244 16245 write (buf, enc) { 16246 if (typeof buf === 'string') { 16247 buf = Buffer.from(buf, enc) 16248 } 16249 16250 if (this[_ended]) { 16251 this.emit('error', new Error('write() after end()')) 16252 return false 16253 } 16254 16255 if (this[_fd] === null || this[_writing] || this[_queue].length) { 16256 this[_queue].push(buf) 16257 this[_needDrain] = true 16258 return false 16259 } 16260 16261 this[_writing] = true 16262 this[_write](buf) 16263 return true 16264 } 16265 16266 [_write] (buf) { 16267 fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => 16268 this[_onwrite](er, bw)) 16269 } 16270 16271 [_onwrite] (er, bw) { 16272 if (er) { 16273 this[_onerror](er) 16274 } else { 16275 if (this[_pos] !== null) { 16276 this[_pos] += bw 16277 } 16278 if (this[_queue].length) { 16279 this[_flush]() 16280 } else { 16281 this[_writing] = false 16282 16283 if (this[_ended] && !this[_finished]) { 16284 this[_finished] = true 16285 this[_close]() 16286 this.emit('finish') 16287 } else if (this[_needDrain]) { 16288 this[_needDrain] = false 16289 this.emit('drain') 16290 } 16291 } 16292 } 16293 } 16294 16295 [_flush] () { 16296 if (this[_queue].length === 0) { 16297 if (this[_ended]) { 16298 this[_onwrite](null, 0) 16299 } 16300 } else if (this[_queue].length === 1) { 16301 this[_write](this[_queue].pop()) 16302 } else { 16303 const iovec = this[_queue] 16304 this[_queue] = [] 16305 writev(this[_fd], iovec, this[_pos], 16306 (er, bw) => this[_onwrite](er, bw)) 16307 } 16308 } 16309 16310 [_close] () { 16311 if (this[_autoClose] && typeof this[_fd] === 'number') { 16312 const fd = this[_fd] 16313 this[_fd] = null 16314 fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) 16315 } 16316 } 16317 } 16318 16319 class WriteStreamSync extends WriteStream { 16320 [_open] () { 16321 let fd 16322 // only wrap in a try{} block if we know we'll retry, to avoid 16323 // the rethrow obscuring the error's source frame in most cases. 16324 if (this[_defaultFlag] && this[_flags] === 'r+') { 16325 try { 16326 fd = fs.openSync(this[_path], this[_flags], this[_mode]) 16327 } catch (er) { 16328 if (er.code === 'ENOENT') { 16329 this[_flags] = 'w' 16330 return this[_open]() 16331 } else { 16332 throw er 16333 } 16334 } 16335 } else { 16336 fd = fs.openSync(this[_path], this[_flags], this[_mode]) 16337 } 16338 16339 this[_onopen](null, fd) 16340 } 16341 16342 [_close] () { 16343 if (this[_autoClose] && typeof this[_fd] === 'number') { 16344 const fd = this[_fd] 16345 this[_fd] = null 16346 fs.closeSync(fd) 16347 this.emit('close') 16348 } 16349 } 16350 16351 [_write] (buf) { 16352 // throw the original, but try to close if it fails 16353 let threw = true 16354 try { 16355 this[_onwrite](null, 16356 fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) 16357 threw = false 16358 } finally { 16359 if (threw) { 16360 try { 16361 this[_close]() 16362 } catch { 16363 // ok error 16364 } 16365 } 16366 } 16367 } 16368 } 16369 16370 exports.ReadStream = ReadStream 16371 exports.ReadStreamSync = ReadStreamSync 16372 16373 exports.WriteStream = WriteStream 16374 exports.WriteStreamSync = WriteStreamSync 16375 16376 16377 /***/ }), 16378 16379 /***/ 1621: 16380 /***/ ((module) => { 16381 16382 "use strict"; 16383 16384 16385 module.exports = (flag, argv = process.argv) => { 16386 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); 16387 const position = argv.indexOf(prefix + flag); 16388 const terminatorPosition = argv.indexOf('--'); 16389 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); 16390 }; 16391 16392 16393 /***/ }), 16394 16395 /***/ 1002: 16396 /***/ ((module) => { 16397 16398 "use strict"; 16399 16400 // rfc7231 6.1 16401 const statusCodeCacheableByDefault = new Set([ 16402 200, 16403 203, 16404 204, 16405 206, 16406 300, 16407 301, 16408 308, 16409 404, 16410 405, 16411 410, 16412 414, 16413 501, 16414 ]); 16415 16416 // This implementation does not understand partial responses (206) 16417 const understoodStatuses = new Set([ 16418 200, 16419 203, 16420 204, 16421 300, 16422 301, 16423 302, 16424 303, 16425 307, 16426 308, 16427 404, 16428 405, 16429 410, 16430 414, 16431 501, 16432 ]); 16433 16434 const errorStatusCodes = new Set([ 16435 500, 16436 502, 16437 503, 16438 504, 16439 ]); 16440 16441 const hopByHopHeaders = { 16442 date: true, // included, because we add Age update Date 16443 connection: true, 16444 'keep-alive': true, 16445 'proxy-authenticate': true, 16446 'proxy-authorization': true, 16447 te: true, 16448 trailer: true, 16449 'transfer-encoding': true, 16450 upgrade: true, 16451 }; 16452 16453 const excludedFromRevalidationUpdate = { 16454 // Since the old body is reused, it doesn't make sense to change properties of the body 16455 'content-length': true, 16456 'content-encoding': true, 16457 'transfer-encoding': true, 16458 'content-range': true, 16459 }; 16460 16461 function toNumberOrZero(s) { 16462 const n = parseInt(s, 10); 16463 return isFinite(n) ? n : 0; 16464 } 16465 16466 // RFC 5861 16467 function isErrorResponse(response) { 16468 // consider undefined response as faulty 16469 if(!response) { 16470 return true 16471 } 16472 return errorStatusCodes.has(response.status); 16473 } 16474 16475 function parseCacheControl(header) { 16476 const cc = {}; 16477 if (!header) return cc; 16478 16479 // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), 16480 // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale 16481 const parts = header.trim().split(/,/); 16482 for (const part of parts) { 16483 const [k, v] = part.split(/=/, 2); 16484 cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); 16485 } 16486 16487 return cc; 16488 } 16489 16490 function formatCacheControl(cc) { 16491 let parts = []; 16492 for (const k in cc) { 16493 const v = cc[k]; 16494 parts.push(v === true ? k : k + '=' + v); 16495 } 16496 if (!parts.length) { 16497 return undefined; 16498 } 16499 return parts.join(', '); 16500 } 16501 16502 module.exports = class CachePolicy { 16503 constructor( 16504 req, 16505 res, 16506 { 16507 shared, 16508 cacheHeuristic, 16509 immutableMinTimeToLive, 16510 ignoreCargoCult, 16511 _fromObject, 16512 } = {} 16513 ) { 16514 if (_fromObject) { 16515 this._fromObject(_fromObject); 16516 return; 16517 } 16518 16519 if (!res || !res.headers) { 16520 throw Error('Response headers missing'); 16521 } 16522 this._assertRequestHasHeaders(req); 16523 16524 this._responseTime = this.now(); 16525 this._isShared = shared !== false; 16526 this._cacheHeuristic = 16527 undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE 16528 this._immutableMinTtl = 16529 undefined !== immutableMinTimeToLive 16530 ? immutableMinTimeToLive 16531 : 24 * 3600 * 1000; 16532 16533 this._status = 'status' in res ? res.status : 200; 16534 this._resHeaders = res.headers; 16535 this._rescc = parseCacheControl(res.headers['cache-control']); 16536 this._method = 'method' in req ? req.method : 'GET'; 16537 this._url = req.url; 16538 this._host = req.headers.host; 16539 this._noAuthorization = !req.headers.authorization; 16540 this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used 16541 this._reqcc = parseCacheControl(req.headers['cache-control']); 16542 16543 // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, 16544 // so there's no point stricly adhering to the blindly copy&pasted directives. 16545 if ( 16546 ignoreCargoCult && 16547 'pre-check' in this._rescc && 16548 'post-check' in this._rescc 16549 ) { 16550 delete this._rescc['pre-check']; 16551 delete this._rescc['post-check']; 16552 delete this._rescc['no-cache']; 16553 delete this._rescc['no-store']; 16554 delete this._rescc['must-revalidate']; 16555 this._resHeaders = Object.assign({}, this._resHeaders, { 16556 'cache-control': formatCacheControl(this._rescc), 16557 }); 16558 delete this._resHeaders.expires; 16559 delete this._resHeaders.pragma; 16560 } 16561 16562 // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive 16563 // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). 16564 if ( 16565 res.headers['cache-control'] == null && 16566 /no-cache/.test(res.headers.pragma) 16567 ) { 16568 this._rescc['no-cache'] = true; 16569 } 16570 } 16571 16572 now() { 16573 return Date.now(); 16574 } 16575 16576 storable() { 16577 // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. 16578 return !!( 16579 !this._reqcc['no-store'] && 16580 // A cache MUST NOT store a response to any request, unless: 16581 // The request method is understood by the cache and defined as being cacheable, and 16582 ('GET' === this._method || 16583 'HEAD' === this._method || 16584 ('POST' === this._method && this._hasExplicitExpiration())) && 16585 // the response status code is understood by the cache, and 16586 understoodStatuses.has(this._status) && 16587 // the "no-store" cache directive does not appear in request or response header fields, and 16588 !this._rescc['no-store'] && 16589 // the "private" response directive does not appear in the response, if the cache is shared, and 16590 (!this._isShared || !this._rescc.private) && 16591 // the Authorization header field does not appear in the request, if the cache is shared, 16592 (!this._isShared || 16593 this._noAuthorization || 16594 this._allowsStoringAuthenticated()) && 16595 // the response either: 16596 // contains an Expires header field, or 16597 (this._resHeaders.expires || 16598 // contains a max-age response directive, or 16599 // contains a s-maxage response directive and the cache is shared, or 16600 // contains a public response directive. 16601 this._rescc['max-age'] || 16602 (this._isShared && this._rescc['s-maxage']) || 16603 this._rescc.public || 16604 // has a status code that is defined as cacheable by default 16605 statusCodeCacheableByDefault.has(this._status)) 16606 ); 16607 } 16608 16609 _hasExplicitExpiration() { 16610 // 4.2.1 Calculating Freshness Lifetime 16611 return ( 16612 (this._isShared && this._rescc['s-maxage']) || 16613 this._rescc['max-age'] || 16614 this._resHeaders.expires 16615 ); 16616 } 16617 16618 _assertRequestHasHeaders(req) { 16619 if (!req || !req.headers) { 16620 throw Error('Request headers missing'); 16621 } 16622 } 16623 16624 satisfiesWithoutRevalidation(req) { 16625 this._assertRequestHasHeaders(req); 16626 16627 // When presented with a request, a cache MUST NOT reuse a stored response, unless: 16628 // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, 16629 // unless the stored response is successfully validated (Section 4.3), and 16630 const requestCC = parseCacheControl(req.headers['cache-control']); 16631 if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { 16632 return false; 16633 } 16634 16635 if (requestCC['max-age'] && this.age() > requestCC['max-age']) { 16636 return false; 16637 } 16638 16639 if ( 16640 requestCC['min-fresh'] && 16641 this.timeToLive() < 1000 * requestCC['min-fresh'] 16642 ) { 16643 return false; 16644 } 16645 16646 // the stored response is either: 16647 // fresh, or allowed to be served stale 16648 if (this.stale()) { 16649 const allowsStale = 16650 requestCC['max-stale'] && 16651 !this._rescc['must-revalidate'] && 16652 (true === requestCC['max-stale'] || 16653 requestCC['max-stale'] > this.age() - this.maxAge()); 16654 if (!allowsStale) { 16655 return false; 16656 } 16657 } 16658 16659 return this._requestMatches(req, false); 16660 } 16661 16662 _requestMatches(req, allowHeadMethod) { 16663 // The presented effective request URI and that of the stored response match, and 16664 return ( 16665 (!this._url || this._url === req.url) && 16666 this._host === req.headers.host && 16667 // the request method associated with the stored response allows it to be used for the presented request, and 16668 (!req.method || 16669 this._method === req.method || 16670 (allowHeadMethod && 'HEAD' === req.method)) && 16671 // selecting header fields nominated by the stored response (if any) match those presented, and 16672 this._varyMatches(req) 16673 ); 16674 } 16675 16676 _allowsStoringAuthenticated() { 16677 // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. 16678 return ( 16679 this._rescc['must-revalidate'] || 16680 this._rescc.public || 16681 this._rescc['s-maxage'] 16682 ); 16683 } 16684 16685 _varyMatches(req) { 16686 if (!this._resHeaders.vary) { 16687 return true; 16688 } 16689 16690 // A Vary header field-value of "*" always fails to match 16691 if (this._resHeaders.vary === '*') { 16692 return false; 16693 } 16694 16695 const fields = this._resHeaders.vary 16696 .trim() 16697 .toLowerCase() 16698 .split(/\s*,\s*/); 16699 for (const name of fields) { 16700 if (req.headers[name] !== this._reqHeaders[name]) return false; 16701 } 16702 return true; 16703 } 16704 16705 _copyWithoutHopByHopHeaders(inHeaders) { 16706 const headers = {}; 16707 for (const name in inHeaders) { 16708 if (hopByHopHeaders[name]) continue; 16709 headers[name] = inHeaders[name]; 16710 } 16711 // 9.1. Connection 16712 if (inHeaders.connection) { 16713 const tokens = inHeaders.connection.trim().split(/\s*,\s*/); 16714 for (const name of tokens) { 16715 delete headers[name]; 16716 } 16717 } 16718 if (headers.warning) { 16719 const warnings = headers.warning.split(/,/).filter(warning => { 16720 return !/^\s*1[0-9][0-9]/.test(warning); 16721 }); 16722 if (!warnings.length) { 16723 delete headers.warning; 16724 } else { 16725 headers.warning = warnings.join(',').trim(); 16726 } 16727 } 16728 return headers; 16729 } 16730 16731 responseHeaders() { 16732 const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); 16733 const age = this.age(); 16734 16735 // A cache SHOULD generate 113 warning if it heuristically chose a freshness 16736 // lifetime greater than 24 hours and the response's age is greater than 24 hours. 16737 if ( 16738 age > 3600 * 24 && 16739 !this._hasExplicitExpiration() && 16740 this.maxAge() > 3600 * 24 16741 ) { 16742 headers.warning = 16743 (headers.warning ? `${headers.warning}, ` : '') + 16744 '113 - "rfc7234 5.5.4"'; 16745 } 16746 headers.age = `${Math.round(age)}`; 16747 headers.date = new Date(this.now()).toUTCString(); 16748 return headers; 16749 } 16750 16751 /** 16752 * Value of the Date response header or current time if Date was invalid 16753 * @return timestamp 16754 */ 16755 date() { 16756 const serverDate = Date.parse(this._resHeaders.date); 16757 if (isFinite(serverDate)) { 16758 return serverDate; 16759 } 16760 return this._responseTime; 16761 } 16762 16763 /** 16764 * Value of the Age header, in seconds, updated for the current time. 16765 * May be fractional. 16766 * 16767 * @return Number 16768 */ 16769 age() { 16770 let age = this._ageValue(); 16771 16772 const residentTime = (this.now() - this._responseTime) / 1000; 16773 return age + residentTime; 16774 } 16775 16776 _ageValue() { 16777 return toNumberOrZero(this._resHeaders.age); 16778 } 16779 16780 /** 16781 * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. 16782 * 16783 * For an up-to-date value, see `timeToLive()`. 16784 * 16785 * @return Number 16786 */ 16787 maxAge() { 16788 if (!this.storable() || this._rescc['no-cache']) { 16789 return 0; 16790 } 16791 16792 // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default 16793 // so this implementation requires explicit opt-in via public header 16794 if ( 16795 this._isShared && 16796 (this._resHeaders['set-cookie'] && 16797 !this._rescc.public && 16798 !this._rescc.immutable) 16799 ) { 16800 return 0; 16801 } 16802 16803 if (this._resHeaders.vary === '*') { 16804 return 0; 16805 } 16806 16807 if (this._isShared) { 16808 if (this._rescc['proxy-revalidate']) { 16809 return 0; 16810 } 16811 // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. 16812 if (this._rescc['s-maxage']) { 16813 return toNumberOrZero(this._rescc['s-maxage']); 16814 } 16815 } 16816 16817 // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. 16818 if (this._rescc['max-age']) { 16819 return toNumberOrZero(this._rescc['max-age']); 16820 } 16821 16822 const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; 16823 16824 const serverDate = this.date(); 16825 if (this._resHeaders.expires) { 16826 const expires = Date.parse(this._resHeaders.expires); 16827 // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). 16828 if (Number.isNaN(expires) || expires < serverDate) { 16829 return 0; 16830 } 16831 return Math.max(defaultMinTtl, (expires - serverDate) / 1000); 16832 } 16833 16834 if (this._resHeaders['last-modified']) { 16835 const lastModified = Date.parse(this._resHeaders['last-modified']); 16836 if (isFinite(lastModified) && serverDate > lastModified) { 16837 return Math.max( 16838 defaultMinTtl, 16839 ((serverDate - lastModified) / 1000) * this._cacheHeuristic 16840 ); 16841 } 16842 } 16843 16844 return defaultMinTtl; 16845 } 16846 16847 timeToLive() { 16848 const age = this.maxAge() - this.age(); 16849 const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); 16850 const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); 16851 return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; 16852 } 16853 16854 stale() { 16855 return this.maxAge() <= this.age(); 16856 } 16857 16858 _useStaleIfError() { 16859 return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); 16860 } 16861 16862 useStaleWhileRevalidate() { 16863 return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); 16864 } 16865 16866 static fromObject(obj) { 16867 return new this(undefined, undefined, { _fromObject: obj }); 16868 } 16869 16870 _fromObject(obj) { 16871 if (this._responseTime) throw Error('Reinitialized'); 16872 if (!obj || obj.v !== 1) throw Error('Invalid serialization'); 16873 16874 this._responseTime = obj.t; 16875 this._isShared = obj.sh; 16876 this._cacheHeuristic = obj.ch; 16877 this._immutableMinTtl = 16878 obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; 16879 this._status = obj.st; 16880 this._resHeaders = obj.resh; 16881 this._rescc = obj.rescc; 16882 this._method = obj.m; 16883 this._url = obj.u; 16884 this._host = obj.h; 16885 this._noAuthorization = obj.a; 16886 this._reqHeaders = obj.reqh; 16887 this._reqcc = obj.reqcc; 16888 } 16889 16890 toObject() { 16891 return { 16892 v: 1, 16893 t: this._responseTime, 16894 sh: this._isShared, 16895 ch: this._cacheHeuristic, 16896 imm: this._immutableMinTtl, 16897 st: this._status, 16898 resh: this._resHeaders, 16899 rescc: this._rescc, 16900 m: this._method, 16901 u: this._url, 16902 h: this._host, 16903 a: this._noAuthorization, 16904 reqh: this._reqHeaders, 16905 reqcc: this._reqcc, 16906 }; 16907 } 16908 16909 /** 16910 * Headers for sending to the origin server to revalidate stale response. 16911 * Allows server to return 304 to allow reuse of the previous response. 16912 * 16913 * Hop by hop headers are always stripped. 16914 * Revalidation headers may be added or removed, depending on request. 16915 */ 16916 revalidationHeaders(incomingReq) { 16917 this._assertRequestHasHeaders(incomingReq); 16918 const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); 16919 16920 // This implementation does not understand range requests 16921 delete headers['if-range']; 16922 16923 if (!this._requestMatches(incomingReq, true) || !this.storable()) { 16924 // revalidation allowed via HEAD 16925 // not for the same resource, or wasn't allowed to be cached anyway 16926 delete headers['if-none-match']; 16927 delete headers['if-modified-since']; 16928 return headers; 16929 } 16930 16931 /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ 16932 if (this._resHeaders.etag) { 16933 headers['if-none-match'] = headers['if-none-match'] 16934 ? `${headers['if-none-match']}, ${this._resHeaders.etag}` 16935 : this._resHeaders.etag; 16936 } 16937 16938 // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. 16939 const forbidsWeakValidators = 16940 headers['accept-ranges'] || 16941 headers['if-match'] || 16942 headers['if-unmodified-since'] || 16943 (this._method && this._method != 'GET'); 16944 16945 /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. 16946 Note: This implementation does not understand partial responses (206) */ 16947 if (forbidsWeakValidators) { 16948 delete headers['if-modified-since']; 16949 16950 if (headers['if-none-match']) { 16951 const etags = headers['if-none-match'] 16952 .split(/,/) 16953 .filter(etag => { 16954 return !/^\s*W\//.test(etag); 16955 }); 16956 if (!etags.length) { 16957 delete headers['if-none-match']; 16958 } else { 16959 headers['if-none-match'] = etags.join(',').trim(); 16960 } 16961 } 16962 } else if ( 16963 this._resHeaders['last-modified'] && 16964 !headers['if-modified-since'] 16965 ) { 16966 headers['if-modified-since'] = this._resHeaders['last-modified']; 16967 } 16968 16969 return headers; 16970 } 16971 16972 /** 16973 * Creates new CachePolicy with information combined from the previews response, 16974 * and the new revalidation response. 16975 * 16976 * Returns {policy, modified} where modified is a boolean indicating 16977 * whether the response body has been modified, and old cached body can't be used. 16978 * 16979 * @return {Object} {policy: CachePolicy, modified: Boolean} 16980 */ 16981 revalidatedPolicy(request, response) { 16982 this._assertRequestHasHeaders(request); 16983 if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful 16984 return { 16985 modified: false, 16986 matches: false, 16987 policy: this, 16988 }; 16989 } 16990 if (!response || !response.headers) { 16991 throw Error('Response headers missing'); 16992 } 16993 16994 // These aren't going to be supported exactly, since one CachePolicy object 16995 // doesn't know about all the other cached objects. 16996 let matches = false; 16997 if (response.status !== undefined && response.status != 304) { 16998 matches = false; 16999 } else if ( 17000 response.headers.etag && 17001 !/^\s*W\//.test(response.headers.etag) 17002 ) { 17003 // "All of the stored responses with the same strong validator are selected. 17004 // If none of the stored responses contain the same strong validator, 17005 // then the cache MUST NOT use the new response to update any stored responses." 17006 matches = 17007 this._resHeaders.etag && 17008 this._resHeaders.etag.replace(/^\s*W\//, '') === 17009 response.headers.etag; 17010 } else if (this._resHeaders.etag && response.headers.etag) { 17011 // "If the new response contains a weak validator and that validator corresponds 17012 // to one of the cache's stored responses, 17013 // then the most recent of those matching stored responses is selected for update." 17014 matches = 17015 this._resHeaders.etag.replace(/^\s*W\//, '') === 17016 response.headers.etag.replace(/^\s*W\//, ''); 17017 } else if (this._resHeaders['last-modified']) { 17018 matches = 17019 this._resHeaders['last-modified'] === 17020 response.headers['last-modified']; 17021 } else { 17022 // If the new response does not include any form of validator (such as in the case where 17023 // a client generates an If-Modified-Since request from a source other than the Last-Modified 17024 // response header field), and there is only one stored response, and that stored response also 17025 // lacks a validator, then that stored response is selected for update. 17026 if ( 17027 !this._resHeaders.etag && 17028 !this._resHeaders['last-modified'] && 17029 !response.headers.etag && 17030 !response.headers['last-modified'] 17031 ) { 17032 matches = true; 17033 } 17034 } 17035 17036 if (!matches) { 17037 return { 17038 policy: new this.constructor(request, response), 17039 // Client receiving 304 without body, even if it's invalid/mismatched has no option 17040 // but to reuse a cached body. We don't have a good way to tell clients to do 17041 // error recovery in such case. 17042 modified: response.status != 304, 17043 matches: false, 17044 }; 17045 } 17046 17047 // use other header fields provided in the 304 (Not Modified) response to replace all instances 17048 // of the corresponding header fields in the stored response. 17049 const headers = {}; 17050 for (const k in this._resHeaders) { 17051 headers[k] = 17052 k in response.headers && !excludedFromRevalidationUpdate[k] 17053 ? response.headers[k] 17054 : this._resHeaders[k]; 17055 } 17056 17057 const newResponse = Object.assign({}, response, { 17058 status: this._status, 17059 method: this._method, 17060 headers, 17061 }); 17062 return { 17063 policy: new this.constructor(request, newResponse, { 17064 shared: this._isShared, 17065 cacheHeuristic: this._cacheHeuristic, 17066 immutableMinTimeToLive: this._immutableMinTtl, 17067 }), 17068 modified: false, 17069 matches: true, 17070 }; 17071 } 17072 }; 17073 17074 17075 /***/ }), 17076 17077 /***/ 3764: 17078 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 17079 17080 "use strict"; 17081 17082 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 17083 if (k2 === undefined) k2 = k; 17084 var desc = Object.getOwnPropertyDescriptor(m, k); 17085 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 17086 desc = { enumerable: true, get: function() { return m[k]; } }; 17087 } 17088 Object.defineProperty(o, k2, desc); 17089 }) : (function(o, m, k, k2) { 17090 if (k2 === undefined) k2 = k; 17091 o[k2] = m[k]; 17092 })); 17093 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 17094 Object.defineProperty(o, "default", { enumerable: true, value: v }); 17095 }) : function(o, v) { 17096 o["default"] = v; 17097 }); 17098 var __importStar = (this && this.__importStar) || function (mod) { 17099 if (mod && mod.__esModule) return mod; 17100 var result = {}; 17101 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 17102 __setModuleDefault(result, mod); 17103 return result; 17104 }; 17105 var __importDefault = (this && this.__importDefault) || function (mod) { 17106 return (mod && mod.__esModule) ? mod : { "default": mod }; 17107 }; 17108 Object.defineProperty(exports, "__esModule", ({ value: true })); 17109 exports.HttpProxyAgent = void 0; 17110 const net = __importStar(__nccwpck_require__(1808)); 17111 const tls = __importStar(__nccwpck_require__(4404)); 17112 const debug_1 = __importDefault(__nccwpck_require__(8237)); 17113 const events_1 = __nccwpck_require__(2361); 17114 const agent_base_1 = __nccwpck_require__(694); 17115 const url_1 = __nccwpck_require__(7310); 17116 const debug = (0, debug_1.default)('http-proxy-agent'); 17117 /** 17118 * The `HttpProxyAgent` implements an HTTP Agent subclass that connects 17119 * to the specified "HTTP proxy server" in order to proxy HTTP requests. 17120 */ 17121 class HttpProxyAgent extends agent_base_1.Agent { 17122 constructor(proxy, opts) { 17123 super(opts); 17124 this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; 17125 this.proxyHeaders = opts?.headers ?? {}; 17126 debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); 17127 // Trim off the brackets from IPv6 addresses 17128 const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); 17129 const port = this.proxy.port 17130 ? parseInt(this.proxy.port, 10) 17131 : this.proxy.protocol === 'https:' 17132 ? 443 17133 : 80; 17134 this.connectOpts = { 17135 ...(opts ? omit(opts, 'headers') : null), 17136 host, 17137 port, 17138 }; 17139 } 17140 addRequest(req, opts) { 17141 req._header = null; 17142 this.setRequestProps(req, opts); 17143 // @ts-expect-error `addRequest()` isn't defined in `@types/node` 17144 super.addRequest(req, opts); 17145 } 17146 setRequestProps(req, opts) { 17147 const { proxy } = this; 17148 const protocol = opts.secureEndpoint ? 'https:' : 'http:'; 17149 const hostname = req.getHeader('host') || 'localhost'; 17150 const base = `${protocol}//${hostname}`; 17151 const url = new url_1.URL(req.path, base); 17152 if (opts.port !== 80) { 17153 url.port = String(opts.port); 17154 } 17155 // Change the `http.ClientRequest` instance's "path" field 17156 // to the absolute path of the URL that will be requested. 17157 req.path = String(url); 17158 // Inject the `Proxy-Authorization` header if necessary. 17159 const headers = typeof this.proxyHeaders === 'function' 17160 ? this.proxyHeaders() 17161 : { ...this.proxyHeaders }; 17162 if (proxy.username || proxy.password) { 17163 const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; 17164 headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; 17165 } 17166 if (!headers['Proxy-Connection']) { 17167 headers['Proxy-Connection'] = this.keepAlive 17168 ? 'Keep-Alive' 17169 : 'close'; 17170 } 17171 for (const name of Object.keys(headers)) { 17172 const value = headers[name]; 17173 if (value) { 17174 req.setHeader(name, value); 17175 } 17176 } 17177 } 17178 async connect(req, opts) { 17179 req._header = null; 17180 if (!req.path.includes('://')) { 17181 this.setRequestProps(req, opts); 17182 } 17183 // At this point, the http ClientRequest's internal `_header` field 17184 // might have already been set. If this is the case then we'll need 17185 // to re-generate the string since we just changed the `req.path`. 17186 let first; 17187 let endOfHeaders; 17188 debug('Regenerating stored HTTP header string for request'); 17189 req._implicitHeader(); 17190 if (req.outputData && req.outputData.length > 0) { 17191 debug('Patching connection write() output buffer with updated header'); 17192 first = req.outputData[0].data; 17193 endOfHeaders = first.indexOf('\r\n\r\n') + 4; 17194 req.outputData[0].data = 17195 req._header + first.substring(endOfHeaders); 17196 debug('Output buffer: %o', req.outputData[0].data); 17197 } 17198 // Create a socket connection to the proxy server. 17199 let socket; 17200 if (this.proxy.protocol === 'https:') { 17201 debug('Creating `tls.Socket`: %o', this.connectOpts); 17202 socket = tls.connect(this.connectOpts); 17203 } 17204 else { 17205 debug('Creating `net.Socket`: %o', this.connectOpts); 17206 socket = net.connect(this.connectOpts); 17207 } 17208 // Wait for the socket's `connect` event, so that this `callback()` 17209 // function throws instead of the `http` request machinery. This is 17210 // important for i.e. `PacProxyAgent` which determines a failed proxy 17211 // connection via the `callback()` function throwing. 17212 await (0, events_1.once)(socket, 'connect'); 17213 return socket; 17214 } 17215 } 17216 HttpProxyAgent.protocols = ['http', 'https']; 17217 exports.HttpProxyAgent = HttpProxyAgent; 17218 function omit(obj, ...keys) { 17219 const ret = {}; 17220 let key; 17221 for (key in obj) { 17222 if (!keys.includes(key)) { 17223 ret[key] = obj[key]; 17224 } 17225 } 17226 return ret; 17227 } 17228 //# sourceMappingURL=index.js.map 17229 17230 /***/ }), 17231 17232 /***/ 7219: 17233 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 17234 17235 "use strict"; 17236 17237 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 17238 if (k2 === undefined) k2 = k; 17239 var desc = Object.getOwnPropertyDescriptor(m, k); 17240 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 17241 desc = { enumerable: true, get: function() { return m[k]; } }; 17242 } 17243 Object.defineProperty(o, k2, desc); 17244 }) : (function(o, m, k, k2) { 17245 if (k2 === undefined) k2 = k; 17246 o[k2] = m[k]; 17247 })); 17248 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 17249 Object.defineProperty(o, "default", { enumerable: true, value: v }); 17250 }) : function(o, v) { 17251 o["default"] = v; 17252 }); 17253 var __importStar = (this && this.__importStar) || function (mod) { 17254 if (mod && mod.__esModule) return mod; 17255 var result = {}; 17256 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 17257 __setModuleDefault(result, mod); 17258 return result; 17259 }; 17260 var __importDefault = (this && this.__importDefault) || function (mod) { 17261 return (mod && mod.__esModule) ? mod : { "default": mod }; 17262 }; 17263 Object.defineProperty(exports, "__esModule", ({ value: true })); 17264 exports.HttpsProxyAgent = void 0; 17265 const net = __importStar(__nccwpck_require__(1808)); 17266 const tls = __importStar(__nccwpck_require__(4404)); 17267 const assert_1 = __importDefault(__nccwpck_require__(9491)); 17268 const debug_1 = __importDefault(__nccwpck_require__(8237)); 17269 const agent_base_1 = __nccwpck_require__(694); 17270 const url_1 = __nccwpck_require__(7310); 17271 const parse_proxy_response_1 = __nccwpck_require__(5783); 17272 const debug = (0, debug_1.default)('https-proxy-agent'); 17273 /** 17274 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to 17275 * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. 17276 * 17277 * Outgoing HTTP requests are first tunneled through the proxy server using the 17278 * `CONNECT` HTTP request method to establish a connection to the proxy server, 17279 * and then the proxy server connects to the destination target and issues the 17280 * HTTP request from the proxy server. 17281 * 17282 * `https:` requests have their socket connection upgraded to TLS once 17283 * the connection to the proxy server has been established. 17284 */ 17285 class HttpsProxyAgent extends agent_base_1.Agent { 17286 constructor(proxy, opts) { 17287 super(opts); 17288 this.options = { path: undefined }; 17289 this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; 17290 this.proxyHeaders = opts?.headers ?? {}; 17291 debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); 17292 // Trim off the brackets from IPv6 addresses 17293 const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); 17294 const port = this.proxy.port 17295 ? parseInt(this.proxy.port, 10) 17296 : this.proxy.protocol === 'https:' 17297 ? 443 17298 : 80; 17299 this.connectOpts = { 17300 // Attempt to negotiate http/1.1 for proxy servers that support http/2 17301 ALPNProtocols: ['http/1.1'], 17302 ...(opts ? omit(opts, 'headers') : null), 17303 host, 17304 port, 17305 }; 17306 } 17307 /** 17308 * Called when the node-core HTTP client library is creating a 17309 * new HTTP request. 17310 */ 17311 async connect(req, opts) { 17312 const { proxy } = this; 17313 if (!opts.host) { 17314 throw new TypeError('No "host" provided'); 17315 } 17316 // Create a socket connection to the proxy server. 17317 let socket; 17318 if (proxy.protocol === 'https:') { 17319 debug('Creating `tls.Socket`: %o', this.connectOpts); 17320 const servername = this.connectOpts.servername || this.connectOpts.host; 17321 socket = tls.connect({ 17322 ...this.connectOpts, 17323 servername: servername && net.isIP(servername) ? undefined : servername, 17324 }); 17325 } 17326 else { 17327 debug('Creating `net.Socket`: %o', this.connectOpts); 17328 socket = net.connect(this.connectOpts); 17329 } 17330 const headers = typeof this.proxyHeaders === 'function' 17331 ? this.proxyHeaders() 17332 : { ...this.proxyHeaders }; 17333 const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; 17334 let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; 17335 // Inject the `Proxy-Authorization` header if necessary. 17336 if (proxy.username || proxy.password) { 17337 const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; 17338 headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; 17339 } 17340 headers.Host = `${host}:${opts.port}`; 17341 if (!headers['Proxy-Connection']) { 17342 headers['Proxy-Connection'] = this.keepAlive 17343 ? 'Keep-Alive' 17344 : 'close'; 17345 } 17346 for (const name of Object.keys(headers)) { 17347 payload += `${name}: ${headers[name]}\r\n`; 17348 } 17349 const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); 17350 socket.write(`${payload}\r\n`); 17351 const { connect, buffered } = await proxyResponsePromise; 17352 req.emit('proxyConnect', connect); 17353 this.emit('proxyConnect', connect, req); 17354 if (connect.statusCode === 200) { 17355 req.once('socket', resume); 17356 if (opts.secureEndpoint) { 17357 // The proxy is connecting to a TLS server, so upgrade 17358 // this socket connection to a TLS connection. 17359 debug('Upgrading socket connection to TLS'); 17360 const servername = opts.servername || opts.host; 17361 return tls.connect({ 17362 ...omit(opts, 'host', 'path', 'port'), 17363 socket, 17364 servername: net.isIP(servername) ? undefined : servername, 17365 }); 17366 } 17367 return socket; 17368 } 17369 // Some other status code that's not 200... need to re-play the HTTP 17370 // header "data" events onto the socket once the HTTP machinery is 17371 // attached so that the node core `http` can parse and handle the 17372 // error status code. 17373 // Close the original socket, and a new "fake" socket is returned 17374 // instead, so that the proxy doesn't get the HTTP request 17375 // written to it (which may contain `Authorization` headers or other 17376 // sensitive data). 17377 // 17378 // See: https://hackerone.com/reports/541502 17379 socket.destroy(); 17380 const fakeSocket = new net.Socket({ writable: false }); 17381 fakeSocket.readable = true; 17382 // Need to wait for the "socket" event to re-play the "data" events. 17383 req.once('socket', (s) => { 17384 debug('Replaying proxy buffer for failed request'); 17385 (0, assert_1.default)(s.listenerCount('data') > 0); 17386 // Replay the "buffered" Buffer onto the fake `socket`, since at 17387 // this point the HTTP module machinery has been hooked up for 17388 // the user. 17389 s.push(buffered); 17390 s.push(null); 17391 }); 17392 return fakeSocket; 17393 } 17394 } 17395 HttpsProxyAgent.protocols = ['http', 'https']; 17396 exports.HttpsProxyAgent = HttpsProxyAgent; 17397 function resume(socket) { 17398 socket.resume(); 17399 } 17400 function omit(obj, ...keys) { 17401 const ret = {}; 17402 let key; 17403 for (key in obj) { 17404 if (!keys.includes(key)) { 17405 ret[key] = obj[key]; 17406 } 17407 } 17408 return ret; 17409 } 17410 //# sourceMappingURL=index.js.map 17411 17412 /***/ }), 17413 17414 /***/ 5783: 17415 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 17416 17417 "use strict"; 17418 17419 var __importDefault = (this && this.__importDefault) || function (mod) { 17420 return (mod && mod.__esModule) ? mod : { "default": mod }; 17421 }; 17422 Object.defineProperty(exports, "__esModule", ({ value: true })); 17423 exports.parseProxyResponse = void 0; 17424 const debug_1 = __importDefault(__nccwpck_require__(8237)); 17425 const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); 17426 function parseProxyResponse(socket) { 17427 return new Promise((resolve, reject) => { 17428 // we need to buffer any HTTP traffic that happens with the proxy before we get 17429 // the CONNECT response, so that if the response is anything other than an "200" 17430 // response code, then we can re-play the "data" events on the socket once the 17431 // HTTP parser is hooked up... 17432 let buffersLength = 0; 17433 const buffers = []; 17434 function read() { 17435 const b = socket.read(); 17436 if (b) 17437 ondata(b); 17438 else 17439 socket.once('readable', read); 17440 } 17441 function cleanup() { 17442 socket.removeListener('end', onend); 17443 socket.removeListener('error', onerror); 17444 socket.removeListener('readable', read); 17445 } 17446 function onend() { 17447 cleanup(); 17448 debug('onend'); 17449 reject(new Error('Proxy connection ended before receiving CONNECT response')); 17450 } 17451 function onerror(err) { 17452 cleanup(); 17453 debug('onerror %o', err); 17454 reject(err); 17455 } 17456 function ondata(b) { 17457 buffers.push(b); 17458 buffersLength += b.length; 17459 const buffered = Buffer.concat(buffers, buffersLength); 17460 const endOfHeaders = buffered.indexOf('\r\n\r\n'); 17461 if (endOfHeaders === -1) { 17462 // keep buffering 17463 debug('have not received end of HTTP headers yet...'); 17464 read(); 17465 return; 17466 } 17467 const headerParts = buffered 17468 .slice(0, endOfHeaders) 17469 .toString('ascii') 17470 .split('\r\n'); 17471 const firstLine = headerParts.shift(); 17472 if (!firstLine) { 17473 socket.destroy(); 17474 return reject(new Error('No header received from proxy CONNECT response')); 17475 } 17476 const firstLineParts = firstLine.split(' '); 17477 const statusCode = +firstLineParts[1]; 17478 const statusText = firstLineParts.slice(2).join(' '); 17479 const headers = {}; 17480 for (const header of headerParts) { 17481 if (!header) 17482 continue; 17483 const firstColon = header.indexOf(':'); 17484 if (firstColon === -1) { 17485 socket.destroy(); 17486 return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); 17487 } 17488 const key = header.slice(0, firstColon).toLowerCase(); 17489 const value = header.slice(firstColon + 1).trimStart(); 17490 const current = headers[key]; 17491 if (typeof current === 'string') { 17492 headers[key] = [current, value]; 17493 } 17494 else if (Array.isArray(current)) { 17495 current.push(value); 17496 } 17497 else { 17498 headers[key] = value; 17499 } 17500 } 17501 debug('got proxy server response: %o %o', firstLine, headers); 17502 cleanup(); 17503 resolve({ 17504 connect: { 17505 statusCode, 17506 statusText, 17507 headers, 17508 }, 17509 buffered, 17510 }); 17511 } 17512 socket.on('error', onerror); 17513 socket.on('end', onend); 17514 read(); 17515 }); 17516 } 17517 exports.parseProxyResponse = parseProxyResponse; 17518 //# sourceMappingURL=parse-proxy-response.js.map 17519 17520 /***/ }), 17521 17522 /***/ 2527: 17523 /***/ ((module) => { 17524 17525 /** 17526 * @preserve 17527 * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) 17528 * 17529 * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a> 17530 * @see http://github.com/homebrewing/brauhaus-diff 17531 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> 17532 * @see http://github.com/garycourt/murmurhash-js 17533 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> 17534 * @see http://sites.google.com/site/murmurhash/ 17535 */ 17536 (function(){ 17537 var cache; 17538 17539 // Call this function without `new` to use the cached object (good for 17540 // single-threaded environments), or with `new` to create a new object. 17541 // 17542 // @param {string} key A UTF-16 or ASCII string 17543 // @param {number} seed An optional positive integer 17544 // @return {object} A MurmurHash3 object for incremental hashing 17545 function MurmurHash3(key, seed) { 17546 var m = this instanceof MurmurHash3 ? this : cache; 17547 m.reset(seed) 17548 if (typeof key === 'string' && key.length > 0) { 17549 m.hash(key); 17550 } 17551 17552 if (m !== this) { 17553 return m; 17554 } 17555 }; 17556 17557 // Incrementally add a string to this hash 17558 // 17559 // @param {string} key A UTF-16 or ASCII string 17560 // @return {object} this 17561 MurmurHash3.prototype.hash = function(key) { 17562 var h1, k1, i, top, len; 17563 17564 len = key.length; 17565 this.len += len; 17566 17567 k1 = this.k1; 17568 i = 0; 17569 switch (this.rem) { 17570 case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; 17571 case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; 17572 case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; 17573 case 3: 17574 k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; 17575 k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; 17576 } 17577 17578 this.rem = (len + this.rem) & 3; // & 3 is same as % 4 17579 len -= this.rem; 17580 if (len > 0) { 17581 h1 = this.h1; 17582 while (1) { 17583 k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; 17584 k1 = (k1 << 15) | (k1 >>> 17); 17585 k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; 17586 17587 h1 ^= k1; 17588 h1 = (h1 << 13) | (h1 >>> 19); 17589 h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; 17590 17591 if (i >= len) { 17592 break; 17593 } 17594 17595 k1 = ((key.charCodeAt(i++) & 0xffff)) ^ 17596 ((key.charCodeAt(i++) & 0xffff) << 8) ^ 17597 ((key.charCodeAt(i++) & 0xffff) << 16); 17598 top = key.charCodeAt(i++); 17599 k1 ^= ((top & 0xff) << 24) ^ 17600 ((top & 0xff00) >> 8); 17601 } 17602 17603 k1 = 0; 17604 switch (this.rem) { 17605 case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; 17606 case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; 17607 case 1: k1 ^= (key.charCodeAt(i) & 0xffff); 17608 } 17609 17610 this.h1 = h1; 17611 } 17612 17613 this.k1 = k1; 17614 return this; 17615 }; 17616 17617 // Get the result of this hash 17618 // 17619 // @return {number} The 32-bit hash 17620 MurmurHash3.prototype.result = function() { 17621 var k1, h1; 17622 17623 k1 = this.k1; 17624 h1 = this.h1; 17625 17626 if (k1 > 0) { 17627 k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; 17628 k1 = (k1 << 15) | (k1 >>> 17); 17629 k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; 17630 h1 ^= k1; 17631 } 17632 17633 h1 ^= this.len; 17634 17635 h1 ^= h1 >>> 16; 17636 h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; 17637 h1 ^= h1 >>> 13; 17638 h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; 17639 h1 ^= h1 >>> 16; 17640 17641 return h1 >>> 0; 17642 }; 17643 17644 // Reset the hash object for reuse 17645 // 17646 // @param {number} seed An optional positive integer 17647 MurmurHash3.prototype.reset = function(seed) { 17648 this.h1 = typeof seed === 'number' ? seed : 0; 17649 this.rem = this.k1 = this.len = 0; 17650 return this; 17651 }; 17652 17653 // A cached object to use. This can be safely used if you're in a single- 17654 // threaded environment, otherwise you need to create new hashes to use. 17655 cache = new MurmurHash3(); 17656 17657 if (true) { 17658 module.exports = MurmurHash3; 17659 } else {} 17660 }()); 17661 17662 17663 /***/ }), 17664 17665 /***/ 8043: 17666 /***/ ((module) => { 17667 17668 "use strict"; 17669 17670 17671 module.exports = (string, count = 1, options) => { 17672 options = { 17673 indent: ' ', 17674 includeEmptyLines: false, 17675 ...options 17676 }; 17677 17678 if (typeof string !== 'string') { 17679 throw new TypeError( 17680 `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` 17681 ); 17682 } 17683 17684 if (typeof count !== 'number') { 17685 throw new TypeError( 17686 `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` 17687 ); 17688 } 17689 17690 if (typeof options.indent !== 'string') { 17691 throw new TypeError( 17692 `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` 17693 ); 17694 } 17695 17696 if (count === 0) { 17697 return string; 17698 } 17699 17700 const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; 17701 17702 return string.replace(regex, options.indent.repeat(count)); 17703 }; 17704 17705 17706 /***/ }), 17707 17708 /***/ 903: 17709 /***/ ((__unused_webpack_module, exports) => { 17710 17711 "use strict"; 17712 17713 Object.defineProperty(exports, "__esModule", ({ value: true })); 17714 exports.AddressError = void 0; 17715 class AddressError extends Error { 17716 constructor(message, parseMessage) { 17717 super(message); 17718 this.name = 'AddressError'; 17719 if (parseMessage !== null) { 17720 this.parseMessage = parseMessage; 17721 } 17722 } 17723 } 17724 exports.AddressError = AddressError; 17725 //# sourceMappingURL=address-error.js.map 17726 17727 /***/ }), 17728 17729 /***/ 3233: 17730 /***/ ((__unused_webpack_module, exports) => { 17731 17732 "use strict"; 17733 17734 Object.defineProperty(exports, "__esModule", ({ value: true })); 17735 exports.isCorrect = exports.isInSubnet = void 0; 17736 function isInSubnet(address) { 17737 if (this.subnetMask < address.subnetMask) { 17738 return false; 17739 } 17740 if (this.mask(address.subnetMask) === address.mask()) { 17741 return true; 17742 } 17743 return false; 17744 } 17745 exports.isInSubnet = isInSubnet; 17746 function isCorrect(defaultBits) { 17747 return function () { 17748 if (this.addressMinusSuffix !== this.correctForm()) { 17749 return false; 17750 } 17751 if (this.subnetMask === defaultBits && !this.parsedSubnet) { 17752 return true; 17753 } 17754 return this.parsedSubnet === String(this.subnetMask); 17755 }; 17756 } 17757 exports.isCorrect = isCorrect; 17758 //# sourceMappingURL=common.js.map 17759 17760 /***/ }), 17761 17762 /***/ 8953: 17763 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 17764 17765 "use strict"; 17766 17767 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 17768 if (k2 === undefined) k2 = k; 17769 var desc = Object.getOwnPropertyDescriptor(m, k); 17770 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 17771 desc = { enumerable: true, get: function() { return m[k]; } }; 17772 } 17773 Object.defineProperty(o, k2, desc); 17774 }) : (function(o, m, k, k2) { 17775 if (k2 === undefined) k2 = k; 17776 o[k2] = m[k]; 17777 })); 17778 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 17779 Object.defineProperty(o, "default", { enumerable: true, value: v }); 17780 }) : function(o, v) { 17781 o["default"] = v; 17782 }); 17783 var __importStar = (this && this.__importStar) || function (mod) { 17784 if (mod && mod.__esModule) return mod; 17785 var result = {}; 17786 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 17787 __setModuleDefault(result, mod); 17788 return result; 17789 }; 17790 Object.defineProperty(exports, "__esModule", ({ value: true })); 17791 exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; 17792 const ipv4_1 = __nccwpck_require__(753); 17793 Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } })); 17794 const ipv6_1 = __nccwpck_require__(8292); 17795 Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } })); 17796 const address_error_1 = __nccwpck_require__(903); 17797 Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } })); 17798 const helpers = __importStar(__nccwpck_require__(945)); 17799 exports.v6 = { helpers }; 17800 //# sourceMappingURL=ip-address.js.map 17801 17802 /***/ }), 17803 17804 /***/ 753: 17805 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 17806 17807 "use strict"; 17808 17809 /* eslint-disable no-param-reassign */ 17810 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 17811 if (k2 === undefined) k2 = k; 17812 var desc = Object.getOwnPropertyDescriptor(m, k); 17813 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 17814 desc = { enumerable: true, get: function() { return m[k]; } }; 17815 } 17816 Object.defineProperty(o, k2, desc); 17817 }) : (function(o, m, k, k2) { 17818 if (k2 === undefined) k2 = k; 17819 o[k2] = m[k]; 17820 })); 17821 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 17822 Object.defineProperty(o, "default", { enumerable: true, value: v }); 17823 }) : function(o, v) { 17824 o["default"] = v; 17825 }); 17826 var __importStar = (this && this.__importStar) || function (mod) { 17827 if (mod && mod.__esModule) return mod; 17828 var result = {}; 17829 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 17830 __setModuleDefault(result, mod); 17831 return result; 17832 }; 17833 Object.defineProperty(exports, "__esModule", ({ value: true })); 17834 exports.Address4 = void 0; 17835 const common = __importStar(__nccwpck_require__(3233)); 17836 const constants = __importStar(__nccwpck_require__(3075)); 17837 const address_error_1 = __nccwpck_require__(903); 17838 const jsbn_1 = __nccwpck_require__(5587); 17839 const sprintf_js_1 = __nccwpck_require__(3988); 17840 /** 17841 * Represents an IPv4 address 17842 * @class Address4 17843 * @param {string} address - An IPv4 address string 17844 */ 17845 class Address4 { 17846 constructor(address) { 17847 this.groups = constants.GROUPS; 17848 this.parsedAddress = []; 17849 this.parsedSubnet = ''; 17850 this.subnet = '/32'; 17851 this.subnetMask = 32; 17852 this.v4 = true; 17853 /** 17854 * Returns true if the address is correct, false otherwise 17855 * @memberof Address4 17856 * @instance 17857 * @returns {Boolean} 17858 */ 17859 this.isCorrect = common.isCorrect(constants.BITS); 17860 /** 17861 * Returns true if the given address is in the subnet of the current address 17862 * @memberof Address4 17863 * @instance 17864 * @returns {boolean} 17865 */ 17866 this.isInSubnet = common.isInSubnet; 17867 this.address = address; 17868 const subnet = constants.RE_SUBNET_STRING.exec(address); 17869 if (subnet) { 17870 this.parsedSubnet = subnet[0].replace('/', ''); 17871 this.subnetMask = parseInt(this.parsedSubnet, 10); 17872 this.subnet = `/${this.subnetMask}`; 17873 if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { 17874 throw new address_error_1.AddressError('Invalid subnet mask.'); 17875 } 17876 address = address.replace(constants.RE_SUBNET_STRING, ''); 17877 } 17878 this.addressMinusSuffix = address; 17879 this.parsedAddress = this.parse(address); 17880 } 17881 static isValid(address) { 17882 try { 17883 // eslint-disable-next-line no-new 17884 new Address4(address); 17885 return true; 17886 } 17887 catch (e) { 17888 return false; 17889 } 17890 } 17891 /* 17892 * Parses a v4 address 17893 */ 17894 parse(address) { 17895 const groups = address.split('.'); 17896 if (!address.match(constants.RE_ADDRESS)) { 17897 throw new address_error_1.AddressError('Invalid IPv4 address.'); 17898 } 17899 return groups; 17900 } 17901 /** 17902 * Returns the correct form of an address 17903 * @memberof Address4 17904 * @instance 17905 * @returns {String} 17906 */ 17907 correctForm() { 17908 return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); 17909 } 17910 /** 17911 * Converts a hex string to an IPv4 address object 17912 * @memberof Address4 17913 * @static 17914 * @param {string} hex - a hex string to convert 17915 * @returns {Address4} 17916 */ 17917 static fromHex(hex) { 17918 const padded = hex.replace(/:/g, '').padStart(8, '0'); 17919 const groups = []; 17920 let i; 17921 for (i = 0; i < 8; i += 2) { 17922 const h = padded.slice(i, i + 2); 17923 groups.push(parseInt(h, 16)); 17924 } 17925 return new Address4(groups.join('.')); 17926 } 17927 /** 17928 * Converts an integer into a IPv4 address object 17929 * @memberof Address4 17930 * @static 17931 * @param {integer} integer - a number to convert 17932 * @returns {Address4} 17933 */ 17934 static fromInteger(integer) { 17935 return Address4.fromHex(integer.toString(16)); 17936 } 17937 /** 17938 * Return an address from in-addr.arpa form 17939 * @memberof Address4 17940 * @static 17941 * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address 17942 * @returns {Adress4} 17943 * @example 17944 * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) 17945 * address.correctForm(); // '192.0.2.42' 17946 */ 17947 static fromArpa(arpaFormAddress) { 17948 // remove ending ".in-addr.arpa." or just "." 17949 const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); 17950 const address = leader.split('.').reverse().join('.'); 17951 return new Address4(address); 17952 } 17953 /** 17954 * Converts an IPv4 address object to a hex string 17955 * @memberof Address4 17956 * @instance 17957 * @returns {String} 17958 */ 17959 toHex() { 17960 return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':'); 17961 } 17962 /** 17963 * Converts an IPv4 address object to an array of bytes 17964 * @memberof Address4 17965 * @instance 17966 * @returns {Array} 17967 */ 17968 toArray() { 17969 return this.parsedAddress.map((part) => parseInt(part, 10)); 17970 } 17971 /** 17972 * Converts an IPv4 address object to an IPv6 address group 17973 * @memberof Address4 17974 * @instance 17975 * @returns {String} 17976 */ 17977 toGroup6() { 17978 const output = []; 17979 let i; 17980 for (i = 0; i < constants.GROUPS; i += 2) { 17981 const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); 17982 output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16))); 17983 } 17984 return output.join(':'); 17985 } 17986 /** 17987 * Returns the address as a BigInteger 17988 * @memberof Address4 17989 * @instance 17990 * @returns {BigInteger} 17991 */ 17992 bigInteger() { 17993 return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); 17994 } 17995 /** 17996 * Helper function getting start address. 17997 * @memberof Address4 17998 * @instance 17999 * @returns {BigInteger} 18000 */ 18001 _startAddress() { 18002 return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); 18003 } 18004 /** 18005 * The first address in the range given by this address' subnet. 18006 * Often referred to as the Network Address. 18007 * @memberof Address4 18008 * @instance 18009 * @returns {Address4} 18010 */ 18011 startAddress() { 18012 return Address4.fromBigInteger(this._startAddress()); 18013 } 18014 /** 18015 * The first host address in the range given by this address's subnet ie 18016 * the first address after the Network Address 18017 * @memberof Address4 18018 * @instance 18019 * @returns {Address4} 18020 */ 18021 startAddressExclusive() { 18022 const adjust = new jsbn_1.BigInteger('1'); 18023 return Address4.fromBigInteger(this._startAddress().add(adjust)); 18024 } 18025 /** 18026 * Helper function getting end address. 18027 * @memberof Address4 18028 * @instance 18029 * @returns {BigInteger} 18030 */ 18031 _endAddress() { 18032 return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); 18033 } 18034 /** 18035 * The last address in the range given by this address' subnet 18036 * Often referred to as the Broadcast 18037 * @memberof Address4 18038 * @instance 18039 * @returns {Address4} 18040 */ 18041 endAddress() { 18042 return Address4.fromBigInteger(this._endAddress()); 18043 } 18044 /** 18045 * The last host address in the range given by this address's subnet ie 18046 * the last address prior to the Broadcast Address 18047 * @memberof Address4 18048 * @instance 18049 * @returns {Address4} 18050 */ 18051 endAddressExclusive() { 18052 const adjust = new jsbn_1.BigInteger('1'); 18053 return Address4.fromBigInteger(this._endAddress().subtract(adjust)); 18054 } 18055 /** 18056 * Converts a BigInteger to a v4 address object 18057 * @memberof Address4 18058 * @static 18059 * @param {BigInteger} bigInteger - a BigInteger to convert 18060 * @returns {Address4} 18061 */ 18062 static fromBigInteger(bigInteger) { 18063 return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); 18064 } 18065 /** 18066 * Returns the first n bits of the address, defaulting to the 18067 * subnet mask 18068 * @memberof Address4 18069 * @instance 18070 * @returns {String} 18071 */ 18072 mask(mask) { 18073 if (mask === undefined) { 18074 mask = this.subnetMask; 18075 } 18076 return this.getBitsBase2(0, mask); 18077 } 18078 /** 18079 * Returns the bits in the given range as a base-2 string 18080 * @memberof Address4 18081 * @instance 18082 * @returns {string} 18083 */ 18084 getBitsBase2(start, end) { 18085 return this.binaryZeroPad().slice(start, end); 18086 } 18087 /** 18088 * Return the reversed ip6.arpa form of the address 18089 * @memberof Address4 18090 * @param {Object} options 18091 * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix 18092 * @instance 18093 * @returns {String} 18094 */ 18095 reverseForm(options) { 18096 if (!options) { 18097 options = {}; 18098 } 18099 const reversed = this.correctForm().split('.').reverse().join('.'); 18100 if (options.omitSuffix) { 18101 return reversed; 18102 } 18103 return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); 18104 } 18105 /** 18106 * Returns true if the given address is a multicast address 18107 * @memberof Address4 18108 * @instance 18109 * @returns {boolean} 18110 */ 18111 isMulticast() { 18112 return this.isInSubnet(new Address4('224.0.0.0/4')); 18113 } 18114 /** 18115 * Returns a zero-padded base-2 string representation of the address 18116 * @memberof Address4 18117 * @instance 18118 * @returns {string} 18119 */ 18120 binaryZeroPad() { 18121 return this.bigInteger().toString(2).padStart(constants.BITS, '0'); 18122 } 18123 /** 18124 * Groups an IPv4 address for inclusion at the end of an IPv6 address 18125 * @returns {String} 18126 */ 18127 groupForV6() { 18128 const segments = this.parsedAddress; 18129 return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.'))); 18130 } 18131 } 18132 exports.Address4 = Address4; 18133 //# sourceMappingURL=ipv4.js.map 18134 18135 /***/ }), 18136 18137 /***/ 8292: 18138 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 18139 18140 "use strict"; 18141 18142 /* eslint-disable prefer-destructuring */ 18143 /* eslint-disable no-param-reassign */ 18144 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 18145 if (k2 === undefined) k2 = k; 18146 var desc = Object.getOwnPropertyDescriptor(m, k); 18147 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 18148 desc = { enumerable: true, get: function() { return m[k]; } }; 18149 } 18150 Object.defineProperty(o, k2, desc); 18151 }) : (function(o, m, k, k2) { 18152 if (k2 === undefined) k2 = k; 18153 o[k2] = m[k]; 18154 })); 18155 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 18156 Object.defineProperty(o, "default", { enumerable: true, value: v }); 18157 }) : function(o, v) { 18158 o["default"] = v; 18159 }); 18160 var __importStar = (this && this.__importStar) || function (mod) { 18161 if (mod && mod.__esModule) return mod; 18162 var result = {}; 18163 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 18164 __setModuleDefault(result, mod); 18165 return result; 18166 }; 18167 Object.defineProperty(exports, "__esModule", ({ value: true })); 18168 exports.Address6 = void 0; 18169 const common = __importStar(__nccwpck_require__(3233)); 18170 const constants4 = __importStar(__nccwpck_require__(3075)); 18171 const constants6 = __importStar(__nccwpck_require__(7674)); 18172 const helpers = __importStar(__nccwpck_require__(945)); 18173 const ipv4_1 = __nccwpck_require__(753); 18174 const regular_expressions_1 = __nccwpck_require__(6738); 18175 const address_error_1 = __nccwpck_require__(903); 18176 const jsbn_1 = __nccwpck_require__(5587); 18177 const sprintf_js_1 = __nccwpck_require__(3988); 18178 function assert(condition) { 18179 if (!condition) { 18180 throw new Error('Assertion failed.'); 18181 } 18182 } 18183 function addCommas(number) { 18184 const r = /(\d+)(\d{3})/; 18185 while (r.test(number)) { 18186 number = number.replace(r, '$1,$2'); 18187 } 18188 return number; 18189 } 18190 function spanLeadingZeroes4(n) { 18191 n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2'); 18192 n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2'); 18193 return n; 18194 } 18195 /* 18196 * A helper function to compact an array 18197 */ 18198 function compact(address, slice) { 18199 const s1 = []; 18200 const s2 = []; 18201 let i; 18202 for (i = 0; i < address.length; i++) { 18203 if (i < slice[0]) { 18204 s1.push(address[i]); 18205 } 18206 else if (i > slice[1]) { 18207 s2.push(address[i]); 18208 } 18209 } 18210 return s1.concat(['compact']).concat(s2); 18211 } 18212 function paddedHex(octet) { 18213 return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); 18214 } 18215 function unsignByte(b) { 18216 // eslint-disable-next-line no-bitwise 18217 return b & 0xff; 18218 } 18219 /** 18220 * Represents an IPv6 address 18221 * @class Address6 18222 * @param {string} address - An IPv6 address string 18223 * @param {number} [groups=8] - How many octets to parse 18224 * @example 18225 * var address = new Address6('2001::/32'); 18226 */ 18227 class Address6 { 18228 constructor(address, optionalGroups) { 18229 this.addressMinusSuffix = ''; 18230 this.parsedSubnet = ''; 18231 this.subnet = '/128'; 18232 this.subnetMask = 128; 18233 this.v4 = false; 18234 this.zone = ''; 18235 // #region Attributes 18236 /** 18237 * Returns true if the given address is in the subnet of the current address 18238 * @memberof Address6 18239 * @instance 18240 * @returns {boolean} 18241 */ 18242 this.isInSubnet = common.isInSubnet; 18243 /** 18244 * Returns true if the address is correct, false otherwise 18245 * @memberof Address6 18246 * @instance 18247 * @returns {boolean} 18248 */ 18249 this.isCorrect = common.isCorrect(constants6.BITS); 18250 if (optionalGroups === undefined) { 18251 this.groups = constants6.GROUPS; 18252 } 18253 else { 18254 this.groups = optionalGroups; 18255 } 18256 this.address = address; 18257 const subnet = constants6.RE_SUBNET_STRING.exec(address); 18258 if (subnet) { 18259 this.parsedSubnet = subnet[0].replace('/', ''); 18260 this.subnetMask = parseInt(this.parsedSubnet, 10); 18261 this.subnet = `/${this.subnetMask}`; 18262 if (Number.isNaN(this.subnetMask) || 18263 this.subnetMask < 0 || 18264 this.subnetMask > constants6.BITS) { 18265 throw new address_error_1.AddressError('Invalid subnet mask.'); 18266 } 18267 address = address.replace(constants6.RE_SUBNET_STRING, ''); 18268 } 18269 else if (/\//.test(address)) { 18270 throw new address_error_1.AddressError('Invalid subnet mask.'); 18271 } 18272 const zone = constants6.RE_ZONE_STRING.exec(address); 18273 if (zone) { 18274 this.zone = zone[0]; 18275 address = address.replace(constants6.RE_ZONE_STRING, ''); 18276 } 18277 this.addressMinusSuffix = address; 18278 this.parsedAddress = this.parse(this.addressMinusSuffix); 18279 } 18280 static isValid(address) { 18281 try { 18282 // eslint-disable-next-line no-new 18283 new Address6(address); 18284 return true; 18285 } 18286 catch (e) { 18287 return false; 18288 } 18289 } 18290 /** 18291 * Convert a BigInteger to a v6 address object 18292 * @memberof Address6 18293 * @static 18294 * @param {BigInteger} bigInteger - a BigInteger to convert 18295 * @returns {Address6} 18296 * @example 18297 * var bigInteger = new BigInteger('1000000000000'); 18298 * var address = Address6.fromBigInteger(bigInteger); 18299 * address.correctForm(); // '::e8:d4a5:1000' 18300 */ 18301 static fromBigInteger(bigInteger) { 18302 const hex = bigInteger.toString(16).padStart(32, '0'); 18303 const groups = []; 18304 let i; 18305 for (i = 0; i < constants6.GROUPS; i++) { 18306 groups.push(hex.slice(i * 4, (i + 1) * 4)); 18307 } 18308 return new Address6(groups.join(':')); 18309 } 18310 /** 18311 * Convert a URL (with optional port number) to an address object 18312 * @memberof Address6 18313 * @static 18314 * @param {string} url - a URL with optional port number 18315 * @example 18316 * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); 18317 * addressAndPort.address.correctForm(); // 'ffff::' 18318 * addressAndPort.port; // 8080 18319 */ 18320 static fromURL(url) { 18321 let host; 18322 let port = null; 18323 let result; 18324 // If we have brackets parse them and find a port 18325 if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { 18326 result = constants6.RE_URL_WITH_PORT.exec(url); 18327 if (result === null) { 18328 return { 18329 error: 'failed to parse address with port', 18330 address: null, 18331 port: null, 18332 }; 18333 } 18334 host = result[1]; 18335 port = result[2]; 18336 // If there's a URL extract the address 18337 } 18338 else if (url.indexOf('/') !== -1) { 18339 // Remove the protocol prefix 18340 url = url.replace(/^[a-z0-9]+:\/\//, ''); 18341 // Parse the address 18342 result = constants6.RE_URL.exec(url); 18343 if (result === null) { 18344 return { 18345 error: 'failed to parse address from URL', 18346 address: null, 18347 port: null, 18348 }; 18349 } 18350 host = result[1]; 18351 // Otherwise just assign the URL to the host and let the library parse it 18352 } 18353 else { 18354 host = url; 18355 } 18356 // If there's a port convert it to an integer 18357 if (port) { 18358 port = parseInt(port, 10); 18359 // squelch out of range ports 18360 if (port < 0 || port > 65536) { 18361 port = null; 18362 } 18363 } 18364 else { 18365 // Standardize `undefined` to `null` 18366 port = null; 18367 } 18368 return { 18369 address: new Address6(host), 18370 port, 18371 }; 18372 } 18373 /** 18374 * Create an IPv6-mapped address given an IPv4 address 18375 * @memberof Address6 18376 * @static 18377 * @param {string} address - An IPv4 address string 18378 * @returns {Address6} 18379 * @example 18380 * var address = Address6.fromAddress4('192.168.0.1'); 18381 * address.correctForm(); // '::ffff:c0a8:1' 18382 * address.to4in6(); // '::ffff:192.168.0.1' 18383 */ 18384 static fromAddress4(address) { 18385 const address4 = new ipv4_1.Address4(address); 18386 const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); 18387 return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); 18388 } 18389 /** 18390 * Return an address from ip6.arpa form 18391 * @memberof Address6 18392 * @static 18393 * @param {string} arpaFormAddress - an 'ip6.arpa' form address 18394 * @returns {Adress6} 18395 * @example 18396 * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) 18397 * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' 18398 */ 18399 static fromArpa(arpaFormAddress) { 18400 // remove ending ".ip6.arpa." or just "." 18401 let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); 18402 const semicolonAmount = 7; 18403 // correct ip6.arpa form with ending removed will be 63 characters 18404 if (address.length !== 63) { 18405 throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); 18406 } 18407 const parts = address.split('.').reverse(); 18408 for (let i = semicolonAmount; i > 0; i--) { 18409 const insertIndex = i * 4; 18410 parts.splice(insertIndex, 0, ':'); 18411 } 18412 address = parts.join(''); 18413 return new Address6(address); 18414 } 18415 /** 18416 * Return the Microsoft UNC transcription of the address 18417 * @memberof Address6 18418 * @instance 18419 * @returns {String} the Microsoft UNC transcription of the address 18420 */ 18421 microsoftTranscription() { 18422 return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-')); 18423 } 18424 /** 18425 * Return the first n bits of the address, defaulting to the subnet mask 18426 * @memberof Address6 18427 * @instance 18428 * @param {number} [mask=subnet] - the number of bits to mask 18429 * @returns {String} the first n bits of the address as a string 18430 */ 18431 mask(mask = this.subnetMask) { 18432 return this.getBitsBase2(0, mask); 18433 } 18434 /** 18435 * Return the number of possible subnets of a given size in the address 18436 * @memberof Address6 18437 * @instance 18438 * @param {number} [size=128] - the subnet size 18439 * @returns {String} 18440 */ 18441 // TODO: probably useful to have a numeric version of this too 18442 possibleSubnets(subnetSize = 128) { 18443 const availableBits = constants6.BITS - this.subnetMask; 18444 const subnetBits = Math.abs(subnetSize - constants6.BITS); 18445 const subnetPowers = availableBits - subnetBits; 18446 if (subnetPowers < 0) { 18447 return '0'; 18448 } 18449 return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); 18450 } 18451 /** 18452 * Helper function getting start address. 18453 * @memberof Address6 18454 * @instance 18455 * @returns {BigInteger} 18456 */ 18457 _startAddress() { 18458 return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); 18459 } 18460 /** 18461 * The first address in the range given by this address' subnet 18462 * Often referred to as the Network Address. 18463 * @memberof Address6 18464 * @instance 18465 * @returns {Address6} 18466 */ 18467 startAddress() { 18468 return Address6.fromBigInteger(this._startAddress()); 18469 } 18470 /** 18471 * The first host address in the range given by this address's subnet ie 18472 * the first address after the Network Address 18473 * @memberof Address6 18474 * @instance 18475 * @returns {Address6} 18476 */ 18477 startAddressExclusive() { 18478 const adjust = new jsbn_1.BigInteger('1'); 18479 return Address6.fromBigInteger(this._startAddress().add(adjust)); 18480 } 18481 /** 18482 * Helper function getting end address. 18483 * @memberof Address6 18484 * @instance 18485 * @returns {BigInteger} 18486 */ 18487 _endAddress() { 18488 return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); 18489 } 18490 /** 18491 * The last address in the range given by this address' subnet 18492 * Often referred to as the Broadcast 18493 * @memberof Address6 18494 * @instance 18495 * @returns {Address6} 18496 */ 18497 endAddress() { 18498 return Address6.fromBigInteger(this._endAddress()); 18499 } 18500 /** 18501 * The last host address in the range given by this address's subnet ie 18502 * the last address prior to the Broadcast Address 18503 * @memberof Address6 18504 * @instance 18505 * @returns {Address6} 18506 */ 18507 endAddressExclusive() { 18508 const adjust = new jsbn_1.BigInteger('1'); 18509 return Address6.fromBigInteger(this._endAddress().subtract(adjust)); 18510 } 18511 /** 18512 * Return the scope of the address 18513 * @memberof Address6 18514 * @instance 18515 * @returns {String} 18516 */ 18517 getScope() { 18518 let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; 18519 if (this.getType() === 'Global unicast' && scope !== 'Link local') { 18520 scope = 'Global'; 18521 } 18522 return scope || 'Unknown'; 18523 } 18524 /** 18525 * Return the type of the address 18526 * @memberof Address6 18527 * @instance 18528 * @returns {String} 18529 */ 18530 getType() { 18531 for (const subnet of Object.keys(constants6.TYPES)) { 18532 if (this.isInSubnet(new Address6(subnet))) { 18533 return constants6.TYPES[subnet]; 18534 } 18535 } 18536 return 'Global unicast'; 18537 } 18538 /** 18539 * Return the bits in the given range as a BigInteger 18540 * @memberof Address6 18541 * @instance 18542 * @returns {BigInteger} 18543 */ 18544 getBits(start, end) { 18545 return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); 18546 } 18547 /** 18548 * Return the bits in the given range as a base-2 string 18549 * @memberof Address6 18550 * @instance 18551 * @returns {String} 18552 */ 18553 getBitsBase2(start, end) { 18554 return this.binaryZeroPad().slice(start, end); 18555 } 18556 /** 18557 * Return the bits in the given range as a base-16 string 18558 * @memberof Address6 18559 * @instance 18560 * @returns {String} 18561 */ 18562 getBitsBase16(start, end) { 18563 const length = end - start; 18564 if (length % 4 !== 0) { 18565 throw new Error('Length of bits to retrieve must be divisible by four'); 18566 } 18567 return this.getBits(start, end) 18568 .toString(16) 18569 .padStart(length / 4, '0'); 18570 } 18571 /** 18572 * Return the bits that are set past the subnet mask length 18573 * @memberof Address6 18574 * @instance 18575 * @returns {String} 18576 */ 18577 getBitsPastSubnet() { 18578 return this.getBitsBase2(this.subnetMask, constants6.BITS); 18579 } 18580 /** 18581 * Return the reversed ip6.arpa form of the address 18582 * @memberof Address6 18583 * @param {Object} options 18584 * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix 18585 * @instance 18586 * @returns {String} 18587 */ 18588 reverseForm(options) { 18589 if (!options) { 18590 options = {}; 18591 } 18592 const characters = Math.floor(this.subnetMask / 4); 18593 const reversed = this.canonicalForm() 18594 .replace(/:/g, '') 18595 .split('') 18596 .slice(0, characters) 18597 .reverse() 18598 .join('.'); 18599 if (characters > 0) { 18600 if (options.omitSuffix) { 18601 return reversed; 18602 } 18603 return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); 18604 } 18605 if (options.omitSuffix) { 18606 return ''; 18607 } 18608 return 'ip6.arpa.'; 18609 } 18610 /** 18611 * Return the correct form of the address 18612 * @memberof Address6 18613 * @instance 18614 * @returns {String} 18615 */ 18616 correctForm() { 18617 let i; 18618 let groups = []; 18619 let zeroCounter = 0; 18620 const zeroes = []; 18621 for (i = 0; i < this.parsedAddress.length; i++) { 18622 const value = parseInt(this.parsedAddress[i], 16); 18623 if (value === 0) { 18624 zeroCounter++; 18625 } 18626 if (value !== 0 && zeroCounter > 0) { 18627 if (zeroCounter > 1) { 18628 zeroes.push([i - zeroCounter, i - 1]); 18629 } 18630 zeroCounter = 0; 18631 } 18632 } 18633 // Do we end with a string of zeroes? 18634 if (zeroCounter > 1) { 18635 zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); 18636 } 18637 const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); 18638 if (zeroes.length > 0) { 18639 const index = zeroLengths.indexOf(Math.max(...zeroLengths)); 18640 groups = compact(this.parsedAddress, zeroes[index]); 18641 } 18642 else { 18643 groups = this.parsedAddress; 18644 } 18645 for (i = 0; i < groups.length; i++) { 18646 if (groups[i] !== 'compact') { 18647 groups[i] = parseInt(groups[i], 16).toString(16); 18648 } 18649 } 18650 let correct = groups.join(':'); 18651 correct = correct.replace(/^compact$/, '::'); 18652 correct = correct.replace(/^compact|compact$/, ':'); 18653 correct = correct.replace(/compact/, ''); 18654 return correct; 18655 } 18656 /** 18657 * Return a zero-padded base-2 string representation of the address 18658 * @memberof Address6 18659 * @instance 18660 * @returns {String} 18661 * @example 18662 * var address = new Address6('2001:4860:4001:803::1011'); 18663 * address.binaryZeroPad(); 18664 * // '0010000000000001010010000110000001000000000000010000100000000011 18665 * // 0000000000000000000000000000000000000000000000000001000000010001' 18666 */ 18667 binaryZeroPad() { 18668 return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); 18669 } 18670 // TODO: Improve the semantics of this helper function 18671 parse4in6(address) { 18672 const groups = address.split(':'); 18673 const lastGroup = groups.slice(-1)[0]; 18674 const address4 = lastGroup.match(constants4.RE_ADDRESS); 18675 if (address4) { 18676 this.parsedAddress4 = address4[0]; 18677 this.address4 = new ipv4_1.Address4(this.parsedAddress4); 18678 for (let i = 0; i < this.address4.groups; i++) { 18679 if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { 18680 throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); 18681 } 18682 } 18683 this.v4 = true; 18684 groups[groups.length - 1] = this.address4.toGroup6(); 18685 address = groups.join(':'); 18686 } 18687 return address; 18688 } 18689 // TODO: Make private? 18690 parse(address) { 18691 address = this.parse4in6(address); 18692 const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); 18693 if (badCharacters) { 18694 throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>')); 18695 } 18696 const badAddress = address.match(constants6.RE_BAD_ADDRESS); 18697 if (badAddress) { 18698 throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>')); 18699 } 18700 let groups = []; 18701 const halves = address.split('::'); 18702 if (halves.length === 2) { 18703 let first = halves[0].split(':'); 18704 let last = halves[1].split(':'); 18705 if (first.length === 1 && first[0] === '') { 18706 first = []; 18707 } 18708 if (last.length === 1 && last[0] === '') { 18709 last = []; 18710 } 18711 const remaining = this.groups - (first.length + last.length); 18712 if (!remaining) { 18713 throw new address_error_1.AddressError('Error parsing groups'); 18714 } 18715 this.elidedGroups = remaining; 18716 this.elisionBegin = first.length; 18717 this.elisionEnd = first.length + this.elidedGroups; 18718 groups = groups.concat(first); 18719 for (let i = 0; i < remaining; i++) { 18720 groups.push('0'); 18721 } 18722 groups = groups.concat(last); 18723 } 18724 else if (halves.length === 1) { 18725 groups = address.split(':'); 18726 this.elidedGroups = 0; 18727 } 18728 else { 18729 throw new address_error_1.AddressError('Too many :: groups found'); 18730 } 18731 groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); 18732 if (groups.length !== this.groups) { 18733 throw new address_error_1.AddressError('Incorrect number of groups found'); 18734 } 18735 return groups; 18736 } 18737 /** 18738 * Return the canonical form of the address 18739 * @memberof Address6 18740 * @instance 18741 * @returns {String} 18742 */ 18743 canonicalForm() { 18744 return this.parsedAddress.map(paddedHex).join(':'); 18745 } 18746 /** 18747 * Return the decimal form of the address 18748 * @memberof Address6 18749 * @instance 18750 * @returns {String} 18751 */ 18752 decimal() { 18753 return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':'); 18754 } 18755 /** 18756 * Return the address as a BigInteger 18757 * @memberof Address6 18758 * @instance 18759 * @returns {BigInteger} 18760 */ 18761 bigInteger() { 18762 return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); 18763 } 18764 /** 18765 * Return the last two groups of this address as an IPv4 address string 18766 * @memberof Address6 18767 * @instance 18768 * @returns {Address4} 18769 * @example 18770 * var address = new Address6('2001:4860:4001::1825:bf11'); 18771 * address.to4().correctForm(); // '24.37.191.17' 18772 */ 18773 to4() { 18774 const binary = this.binaryZeroPad().split(''); 18775 return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); 18776 } 18777 /** 18778 * Return the v4-in-v6 form of the address 18779 * @memberof Address6 18780 * @instance 18781 * @returns {String} 18782 */ 18783 to4in6() { 18784 const address4 = this.to4(); 18785 const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); 18786 const correct = address6.correctForm(); 18787 let infix = ''; 18788 if (!/:$/.test(correct)) { 18789 infix = ':'; 18790 } 18791 return correct + infix + address4.address; 18792 } 18793 /** 18794 * Return an object containing the Teredo properties of the address 18795 * @memberof Address6 18796 * @instance 18797 * @returns {Object} 18798 */ 18799 inspectTeredo() { 18800 /* 18801 - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). 18802 - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that 18803 is used. 18804 - Bits 64 to 79 can be used to define some flags. Currently only the 18805 higher order bit is used; it is set to 1 if the Teredo client is 18806 located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista 18807 and Windows Server 2008 implementations, more bits are used. In those 18808 implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", 18809 where "C" remains the "Cone" flag. The "R" bit is reserved for future 18810 use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit 18811 is Individual/Group flag (set to 0). The A bits are set to a 12-bit 18812 randomly generated number chosen by the Teredo client to introduce 18813 additional protection for the Teredo node against IPv6-based scanning 18814 attacks. 18815 - Bits 80 to 95 contains the obfuscated UDP port number. This is the 18816 port number that is mapped by the NAT to the Teredo client with all 18817 bits inverted. 18818 - Bits 96 to 127 contains the obfuscated IPv4 address. This is the 18819 public IPv4 address of the NAT with all bits inverted. 18820 */ 18821 const prefix = this.getBitsBase16(0, 32); 18822 const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString(); 18823 const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); 18824 const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16)); 18825 const flags = this.getBits(64, 80); 18826 const flagsBase2 = this.getBitsBase2(64, 80); 18827 const coneNat = flags.testBit(15); 18828 const reserved = flags.testBit(14); 18829 const groupIndividual = flags.testBit(8); 18830 const universalLocal = flags.testBit(9); 18831 const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); 18832 return { 18833 prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), 18834 server4: server4.address, 18835 client4: client4.address, 18836 flags: flagsBase2, 18837 coneNat, 18838 microsoft: { 18839 reserved, 18840 universalLocal, 18841 groupIndividual, 18842 nonce, 18843 }, 18844 udpPort, 18845 }; 18846 } 18847 /** 18848 * Return an object containing the 6to4 properties of the address 18849 * @memberof Address6 18850 * @instance 18851 * @returns {Object} 18852 */ 18853 inspect6to4() { 18854 /* 18855 - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). 18856 - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. 18857 */ 18858 const prefix = this.getBitsBase16(0, 16); 18859 const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); 18860 return { 18861 prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)), 18862 gateway: gateway.address, 18863 }; 18864 } 18865 /** 18866 * Return a v6 6to4 address from a v6 v4inv6 address 18867 * @memberof Address6 18868 * @instance 18869 * @returns {Address6} 18870 */ 18871 to6to4() { 18872 if (!this.is4()) { 18873 return null; 18874 } 18875 const addr6to4 = [ 18876 '2002', 18877 this.getBitsBase16(96, 112), 18878 this.getBitsBase16(112, 128), 18879 '', 18880 '/16', 18881 ].join(':'); 18882 return new Address6(addr6to4); 18883 } 18884 /** 18885 * Return a byte array 18886 * @memberof Address6 18887 * @instance 18888 * @returns {Array} 18889 */ 18890 toByteArray() { 18891 const byteArray = this.bigInteger().toByteArray(); 18892 // work around issue where `toByteArray` returns a leading 0 element 18893 if (byteArray.length === 17 && byteArray[0] === 0) { 18894 return byteArray.slice(1); 18895 } 18896 return byteArray; 18897 } 18898 /** 18899 * Return an unsigned byte array 18900 * @memberof Address6 18901 * @instance 18902 * @returns {Array} 18903 */ 18904 toUnsignedByteArray() { 18905 return this.toByteArray().map(unsignByte); 18906 } 18907 /** 18908 * Convert a byte array to an Address6 object 18909 * @memberof Address6 18910 * @static 18911 * @returns {Address6} 18912 */ 18913 static fromByteArray(bytes) { 18914 return this.fromUnsignedByteArray(bytes.map(unsignByte)); 18915 } 18916 /** 18917 * Convert an unsigned byte array to an Address6 object 18918 * @memberof Address6 18919 * @static 18920 * @returns {Address6} 18921 */ 18922 static fromUnsignedByteArray(bytes) { 18923 const BYTE_MAX = new jsbn_1.BigInteger('256', 10); 18924 let result = new jsbn_1.BigInteger('0', 10); 18925 let multiplier = new jsbn_1.BigInteger('1', 10); 18926 for (let i = bytes.length - 1; i >= 0; i--) { 18927 result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); 18928 multiplier = multiplier.multiply(BYTE_MAX); 18929 } 18930 return Address6.fromBigInteger(result); 18931 } 18932 /** 18933 * Returns true if the address is in the canonical form, false otherwise 18934 * @memberof Address6 18935 * @instance 18936 * @returns {boolean} 18937 */ 18938 isCanonical() { 18939 return this.addressMinusSuffix === this.canonicalForm(); 18940 } 18941 /** 18942 * Returns true if the address is a link local address, false otherwise 18943 * @memberof Address6 18944 * @instance 18945 * @returns {boolean} 18946 */ 18947 isLinkLocal() { 18948 // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' 18949 if (this.getBitsBase2(0, 64) === 18950 '1111111010000000000000000000000000000000000000000000000000000000') { 18951 return true; 18952 } 18953 return false; 18954 } 18955 /** 18956 * Returns true if the address is a multicast address, false otherwise 18957 * @memberof Address6 18958 * @instance 18959 * @returns {boolean} 18960 */ 18961 isMulticast() { 18962 return this.getType() === 'Multicast'; 18963 } 18964 /** 18965 * Returns true if the address is a v4-in-v6 address, false otherwise 18966 * @memberof Address6 18967 * @instance 18968 * @returns {boolean} 18969 */ 18970 is4() { 18971 return this.v4; 18972 } 18973 /** 18974 * Returns true if the address is a Teredo address, false otherwise 18975 * @memberof Address6 18976 * @instance 18977 * @returns {boolean} 18978 */ 18979 isTeredo() { 18980 return this.isInSubnet(new Address6('2001::/32')); 18981 } 18982 /** 18983 * Returns true if the address is a 6to4 address, false otherwise 18984 * @memberof Address6 18985 * @instance 18986 * @returns {boolean} 18987 */ 18988 is6to4() { 18989 return this.isInSubnet(new Address6('2002::/16')); 18990 } 18991 /** 18992 * Returns true if the address is a loopback address, false otherwise 18993 * @memberof Address6 18994 * @instance 18995 * @returns {boolean} 18996 */ 18997 isLoopback() { 18998 return this.getType() === 'Loopback'; 18999 } 19000 // #endregion 19001 // #region HTML 19002 /** 19003 * @returns {String} the address in link form with a default port of 80 19004 */ 19005 href(optionalPort) { 19006 if (optionalPort === undefined) { 19007 optionalPort = ''; 19008 } 19009 else { 19010 optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); 19011 } 19012 return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); 19013 } 19014 /** 19015 * @returns {String} a link suitable for conveying the address via a URL hash 19016 */ 19017 link(options) { 19018 if (!options) { 19019 options = {}; 19020 } 19021 if (options.className === undefined) { 19022 options.className = ''; 19023 } 19024 if (options.prefix === undefined) { 19025 options.prefix = '/#address='; 19026 } 19027 if (options.v4 === undefined) { 19028 options.v4 = false; 19029 } 19030 let formFunction = this.correctForm; 19031 if (options.v4) { 19032 formFunction = this.to4in6; 19033 } 19034 if (options.className) { 19035 return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>', options.prefix, formFunction.call(this), options.className); 19036 } 19037 return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s">%2$s</a>', options.prefix, formFunction.call(this)); 19038 } 19039 /** 19040 * Groups an address 19041 * @returns {String} 19042 */ 19043 group() { 19044 if (this.elidedGroups === 0) { 19045 // The simple case 19046 return helpers.simpleGroup(this.address).join(':'); 19047 } 19048 assert(typeof this.elidedGroups === 'number'); 19049 assert(typeof this.elisionBegin === 'number'); 19050 // The elided case 19051 const output = []; 19052 const [left, right] = this.address.split('::'); 19053 if (left.length) { 19054 output.push(...helpers.simpleGroup(left)); 19055 } 19056 else { 19057 output.push(''); 19058 } 19059 const classes = ['hover-group']; 19060 for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { 19061 classes.push((0, sprintf_js_1.sprintf)('group-%d', i)); 19062 } 19063 output.push((0, sprintf_js_1.sprintf)('<span class="%s"></span>', classes.join(' '))); 19064 if (right.length) { 19065 output.push(...helpers.simpleGroup(right, this.elisionEnd)); 19066 } 19067 else { 19068 output.push(''); 19069 } 19070 if (this.is4()) { 19071 assert(this.address4 instanceof ipv4_1.Address4); 19072 output.pop(); 19073 output.push(this.address4.groupForV6()); 19074 } 19075 return output.join(':'); 19076 } 19077 // #endregion 19078 // #region Regular expressions 19079 /** 19080 * Generate a regular expression string that can be used to find or validate 19081 * all variations of this address 19082 * @memberof Address6 19083 * @instance 19084 * @param {boolean} substringSearch 19085 * @returns {string} 19086 */ 19087 regularExpressionString(substringSearch = false) { 19088 let output = []; 19089 // TODO: revisit why this is necessary 19090 const address6 = new Address6(this.correctForm()); 19091 if (address6.elidedGroups === 0) { 19092 // The simple case 19093 output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); 19094 } 19095 else if (address6.elidedGroups === constants6.GROUPS) { 19096 // A completely elided address 19097 output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); 19098 } 19099 else { 19100 // A partially elided address 19101 const halves = address6.address.split('::'); 19102 if (halves[0].length) { 19103 output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); 19104 } 19105 assert(typeof address6.elidedGroups === 'number'); 19106 output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); 19107 if (halves[1].length) { 19108 output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); 19109 } 19110 output = [output.join(':')]; 19111 } 19112 if (!substringSearch) { 19113 output = [ 19114 '(?=^|', 19115 regular_expressions_1.ADDRESS_BOUNDARY, 19116 '|[^\\w\\:])(', 19117 ...output, 19118 ')(?=[^\\w\\:]|', 19119 regular_expressions_1.ADDRESS_BOUNDARY, 19120 '|$)', 19121 ]; 19122 } 19123 return output.join(''); 19124 } 19125 /** 19126 * Generate a regular expression that can be used to find or validate all 19127 * variations of this address. 19128 * @memberof Address6 19129 * @instance 19130 * @param {boolean} substringSearch 19131 * @returns {RegExp} 19132 */ 19133 regularExpression(substringSearch = false) { 19134 return new RegExp(this.regularExpressionString(substringSearch), 'i'); 19135 } 19136 } 19137 exports.Address6 = Address6; 19138 //# sourceMappingURL=ipv6.js.map 19139 19140 /***/ }), 19141 19142 /***/ 3075: 19143 /***/ ((__unused_webpack_module, exports) => { 19144 19145 "use strict"; 19146 19147 Object.defineProperty(exports, "__esModule", ({ value: true })); 19148 exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; 19149 exports.BITS = 32; 19150 exports.GROUPS = 4; 19151 exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; 19152 exports.RE_SUBNET_STRING = /\/\d{1,2}$/; 19153 //# sourceMappingURL=constants.js.map 19154 19155 /***/ }), 19156 19157 /***/ 7674: 19158 /***/ ((__unused_webpack_module, exports) => { 19159 19160 "use strict"; 19161 19162 Object.defineProperty(exports, "__esModule", ({ value: true })); 19163 exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; 19164 exports.BITS = 128; 19165 exports.GROUPS = 8; 19166 /** 19167 * Represents IPv6 address scopes 19168 * @memberof Address6 19169 * @static 19170 */ 19171 exports.SCOPES = { 19172 0: 'Reserved', 19173 1: 'Interface local', 19174 2: 'Link local', 19175 4: 'Admin local', 19176 5: 'Site local', 19177 8: 'Organization local', 19178 14: 'Global', 19179 15: 'Reserved', 19180 }; 19181 /** 19182 * Represents IPv6 address types 19183 * @memberof Address6 19184 * @static 19185 */ 19186 exports.TYPES = { 19187 'ff01::1/128': 'Multicast (All nodes on this interface)', 19188 'ff01::2/128': 'Multicast (All routers on this interface)', 19189 'ff02::1/128': 'Multicast (All nodes on this link)', 19190 'ff02::2/128': 'Multicast (All routers on this link)', 19191 'ff05::2/128': 'Multicast (All routers in this site)', 19192 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', 19193 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', 19194 'ff02::9/128': 'Multicast (RIP routers)', 19195 'ff02::a/128': 'Multicast (EIGRP routers)', 19196 'ff02::d/128': 'Multicast (PIM routers)', 19197 'ff02::16/128': 'Multicast (MLDv2 reports)', 19198 'ff01::fb/128': 'Multicast (mDNSv6)', 19199 'ff02::fb/128': 'Multicast (mDNSv6)', 19200 'ff05::fb/128': 'Multicast (mDNSv6)', 19201 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', 19202 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', 19203 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', 19204 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', 19205 '::/128': 'Unspecified', 19206 '::1/128': 'Loopback', 19207 'ff00::/8': 'Multicast', 19208 'fe80::/10': 'Link-local unicast', 19209 }; 19210 /** 19211 * A regular expression that matches bad characters in an IPv6 address 19212 * @memberof Address6 19213 * @static 19214 */ 19215 exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; 19216 /** 19217 * A regular expression that matches an incorrect IPv6 address 19218 * @memberof Address6 19219 * @static 19220 */ 19221 exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; 19222 /** 19223 * A regular expression that matches an IPv6 subnet 19224 * @memberof Address6 19225 * @static 19226 */ 19227 exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; 19228 /** 19229 * A regular expression that matches an IPv6 zone 19230 * @memberof Address6 19231 * @static 19232 */ 19233 exports.RE_ZONE_STRING = /%.*$/; 19234 exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); 19235 exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); 19236 //# sourceMappingURL=constants.js.map 19237 19238 /***/ }), 19239 19240 /***/ 945: 19241 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 19242 19243 "use strict"; 19244 19245 Object.defineProperty(exports, "__esModule", ({ value: true })); 19246 exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0; 19247 const sprintf_js_1 = __nccwpck_require__(3988); 19248 /** 19249 * @returns {String} the string with all zeroes contained in a <span> 19250 */ 19251 function spanAllZeroes(s) { 19252 return s.replace(/(0+)/g, '<span class="zero">$1</span>'); 19253 } 19254 exports.spanAllZeroes = spanAllZeroes; 19255 /** 19256 * @returns {String} the string with each character contained in a <span> 19257 */ 19258 function spanAll(s, offset = 0) { 19259 const letters = s.split(''); 19260 return letters 19261 .map((n, i) => (0, sprintf_js_1.sprintf)('<span class="digit value-%s position-%d">%s</span>', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead? 19262 ) 19263 .join(''); 19264 } 19265 exports.spanAll = spanAll; 19266 function spanLeadingZeroesSimple(group) { 19267 return group.replace(/^(0+)/, '<span class="zero">$1</span>'); 19268 } 19269 /** 19270 * @returns {String} the string with leading zeroes contained in a <span> 19271 */ 19272 function spanLeadingZeroes(address) { 19273 const groups = address.split(':'); 19274 return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); 19275 } 19276 exports.spanLeadingZeroes = spanLeadingZeroes; 19277 /** 19278 * Groups an address 19279 * @returns {String} a grouped address 19280 */ 19281 function simpleGroup(addressString, offset = 0) { 19282 const groups = addressString.split(':'); 19283 return groups.map((g, i) => { 19284 if (/group-v4/.test(g)) { 19285 return g; 19286 } 19287 return (0, sprintf_js_1.sprintf)('<span class="hover-group group-%d">%s</span>', i + offset, spanLeadingZeroesSimple(g)); 19288 }); 19289 } 19290 exports.simpleGroup = simpleGroup; 19291 //# sourceMappingURL=helpers.js.map 19292 19293 /***/ }), 19294 19295 /***/ 6738: 19296 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 19297 19298 "use strict"; 19299 19300 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 19301 if (k2 === undefined) k2 = k; 19302 var desc = Object.getOwnPropertyDescriptor(m, k); 19303 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 19304 desc = { enumerable: true, get: function() { return m[k]; } }; 19305 } 19306 Object.defineProperty(o, k2, desc); 19307 }) : (function(o, m, k, k2) { 19308 if (k2 === undefined) k2 = k; 19309 o[k2] = m[k]; 19310 })); 19311 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 19312 Object.defineProperty(o, "default", { enumerable: true, value: v }); 19313 }) : function(o, v) { 19314 o["default"] = v; 19315 }); 19316 var __importStar = (this && this.__importStar) || function (mod) { 19317 if (mod && mod.__esModule) return mod; 19318 var result = {}; 19319 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 19320 __setModuleDefault(result, mod); 19321 return result; 19322 }; 19323 Object.defineProperty(exports, "__esModule", ({ value: true })); 19324 exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; 19325 const v6 = __importStar(__nccwpck_require__(7674)); 19326 const sprintf_js_1 = __nccwpck_require__(3988); 19327 function groupPossibilities(possibilities) { 19328 return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); 19329 } 19330 exports.groupPossibilities = groupPossibilities; 19331 function padGroup(group) { 19332 if (group.length < 4) { 19333 return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group); 19334 } 19335 return group; 19336 } 19337 exports.padGroup = padGroup; 19338 exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; 19339 function simpleRegularExpression(groups) { 19340 const zeroIndexes = []; 19341 groups.forEach((group, i) => { 19342 const groupInteger = parseInt(group, 16); 19343 if (groupInteger === 0) { 19344 zeroIndexes.push(i); 19345 } 19346 }); 19347 // You can technically elide a single 0, this creates the regular expressions 19348 // to match that eventuality 19349 const possibilities = zeroIndexes.map((zeroIndex) => groups 19350 .map((group, i) => { 19351 if (i === zeroIndex) { 19352 const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; 19353 return groupPossibilities([padGroup(group), elision]); 19354 } 19355 return padGroup(group); 19356 }) 19357 .join(':')); 19358 // The simplest case 19359 possibilities.push(groups.map(padGroup).join(':')); 19360 return groupPossibilities(possibilities); 19361 } 19362 exports.simpleRegularExpression = simpleRegularExpression; 19363 function possibleElisions(elidedGroups, moreLeft, moreRight) { 19364 const left = moreLeft ? '' : ':'; 19365 const right = moreRight ? '' : ':'; 19366 const possibilities = []; 19367 // 1. elision of everything (::) 19368 if (!moreLeft && !moreRight) { 19369 possibilities.push('::'); 19370 } 19371 // 2. complete elision of the middle 19372 if (moreLeft && moreRight) { 19373 possibilities.push(''); 19374 } 19375 if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { 19376 // 3. complete elision of one side 19377 possibilities.push(':'); 19378 } 19379 // 4. elision from the left side 19380 possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); 19381 // 5. elision from the right side 19382 possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); 19383 // 6. no elision 19384 possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); 19385 // 7. elision (including sloppy elision) from the middle 19386 for (let groups = 1; groups < elidedGroups - 1; groups++) { 19387 for (let position = 1; position < elidedGroups - groups; position++) { 19388 possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1)); 19389 } 19390 } 19391 return groupPossibilities(possibilities); 19392 } 19393 exports.possibleElisions = possibleElisions; 19394 //# sourceMappingURL=regular-expressions.js.map 19395 19396 /***/ }), 19397 19398 /***/ 5587: 19399 /***/ (function(module, exports) { 19400 19401 (function(){ 19402 19403 // Copyright (c) 2005 Tom Wu 19404 // All Rights Reserved. 19405 // See "LICENSE" for details. 19406 19407 // Basic JavaScript BN library - subset useful for RSA encryption. 19408 19409 // Bits per digit 19410 var dbits; 19411 19412 // JavaScript engine analysis 19413 var canary = 0xdeadbeefcafe; 19414 var j_lm = ((canary&0xffffff)==0xefcafe); 19415 19416 // (public) Constructor 19417 function BigInteger(a,b,c) { 19418 if(a != null) 19419 if("number" == typeof a) this.fromNumber(a,b,c); 19420 else if(b == null && "string" != typeof a) this.fromString(a,256); 19421 else this.fromString(a,b); 19422 } 19423 19424 // return new, unset BigInteger 19425 function nbi() { return new BigInteger(null); } 19426 19427 // am: Compute w_j += (x*this_i), propagate carries, 19428 // c is initial carry, returns final carry. 19429 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue 19430 // We need to select the fastest one that works in this environment. 19431 19432 // am1: use a single mult and divide to get the high bits, 19433 // max digit bits should be 26 because 19434 // max internal value = 2*dvalue^2-2*dvalue (< 2^53) 19435 function am1(i,x,w,j,c,n) { 19436 while(--n >= 0) { 19437 var v = x*this[i++]+w[j]+c; 19438 c = Math.floor(v/0x4000000); 19439 w[j++] = v&0x3ffffff; 19440 } 19441 return c; 19442 } 19443 // am2 avoids a big mult-and-extract completely. 19444 // Max digit bits should be <= 30 because we do bitwise ops 19445 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) 19446 function am2(i,x,w,j,c,n) { 19447 var xl = x&0x7fff, xh = x>>15; 19448 while(--n >= 0) { 19449 var l = this[i]&0x7fff; 19450 var h = this[i++]>>15; 19451 var m = xh*l+h*xl; 19452 l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); 19453 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); 19454 w[j++] = l&0x3fffffff; 19455 } 19456 return c; 19457 } 19458 // Alternately, set max digit bits to 28 since some 19459 // browsers slow down when dealing with 32-bit numbers. 19460 function am3(i,x,w,j,c,n) { 19461 var xl = x&0x3fff, xh = x>>14; 19462 while(--n >= 0) { 19463 var l = this[i]&0x3fff; 19464 var h = this[i++]>>14; 19465 var m = xh*l+h*xl; 19466 l = xl*l+((m&0x3fff)<<14)+w[j]+c; 19467 c = (l>>28)+(m>>14)+xh*h; 19468 w[j++] = l&0xfffffff; 19469 } 19470 return c; 19471 } 19472 var inBrowser = typeof navigator !== "undefined"; 19473 if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { 19474 BigInteger.prototype.am = am2; 19475 dbits = 30; 19476 } 19477 else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { 19478 BigInteger.prototype.am = am1; 19479 dbits = 26; 19480 } 19481 else { // Mozilla/Netscape seems to prefer am3 19482 BigInteger.prototype.am = am3; 19483 dbits = 28; 19484 } 19485 19486 BigInteger.prototype.DB = dbits; 19487 BigInteger.prototype.DM = ((1<<dbits)-1); 19488 BigInteger.prototype.DV = (1<<dbits); 19489 19490 var BI_FP = 52; 19491 BigInteger.prototype.FV = Math.pow(2,BI_FP); 19492 BigInteger.prototype.F1 = BI_FP-dbits; 19493 BigInteger.prototype.F2 = 2*dbits-BI_FP; 19494 19495 // Digit conversions 19496 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; 19497 var BI_RC = new Array(); 19498 var rr,vv; 19499 rr = "0".charCodeAt(0); 19500 for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; 19501 rr = "a".charCodeAt(0); 19502 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; 19503 rr = "A".charCodeAt(0); 19504 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; 19505 19506 function int2char(n) { return BI_RM.charAt(n); } 19507 function intAt(s,i) { 19508 var c = BI_RC[s.charCodeAt(i)]; 19509 return (c==null)?-1:c; 19510 } 19511 19512 // (protected) copy this to r 19513 function bnpCopyTo(r) { 19514 for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; 19515 r.t = this.t; 19516 r.s = this.s; 19517 } 19518 19519 // (protected) set from integer value x, -DV <= x < DV 19520 function bnpFromInt(x) { 19521 this.t = 1; 19522 this.s = (x<0)?-1:0; 19523 if(x > 0) this[0] = x; 19524 else if(x < -1) this[0] = x+this.DV; 19525 else this.t = 0; 19526 } 19527 19528 // return bigint initialized to value 19529 function nbv(i) { var r = nbi(); r.fromInt(i); return r; } 19530 19531 // (protected) set from string and radix 19532 function bnpFromString(s,b) { 19533 var k; 19534 if(b == 16) k = 4; 19535 else if(b == 8) k = 3; 19536 else if(b == 256) k = 8; // byte array 19537 else if(b == 2) k = 1; 19538 else if(b == 32) k = 5; 19539 else if(b == 4) k = 2; 19540 else { this.fromRadix(s,b); return; } 19541 this.t = 0; 19542 this.s = 0; 19543 var i = s.length, mi = false, sh = 0; 19544 while(--i >= 0) { 19545 var x = (k==8)?s[i]&0xff:intAt(s,i); 19546 if(x < 0) { 19547 if(s.charAt(i) == "-") mi = true; 19548 continue; 19549 } 19550 mi = false; 19551 if(sh == 0) 19552 this[this.t++] = x; 19553 else if(sh+k > this.DB) { 19554 this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; 19555 this[this.t++] = (x>>(this.DB-sh)); 19556 } 19557 else 19558 this[this.t-1] |= x<<sh; 19559 sh += k; 19560 if(sh >= this.DB) sh -= this.DB; 19561 } 19562 if(k == 8 && (s[0]&0x80) != 0) { 19563 this.s = -1; 19564 if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; 19565 } 19566 this.clamp(); 19567 if(mi) BigInteger.ZERO.subTo(this,this); 19568 } 19569 19570 // (protected) clamp off excess high words 19571 function bnpClamp() { 19572 var c = this.s&this.DM; 19573 while(this.t > 0 && this[this.t-1] == c) --this.t; 19574 } 19575 19576 // (public) return string representation in given radix 19577 function bnToString(b) { 19578 if(this.s < 0) return "-"+this.negate().toString(b); 19579 var k; 19580 if(b == 16) k = 4; 19581 else if(b == 8) k = 3; 19582 else if(b == 2) k = 1; 19583 else if(b == 32) k = 5; 19584 else if(b == 4) k = 2; 19585 else return this.toRadix(b); 19586 var km = (1<<k)-1, d, m = false, r = "", i = this.t; 19587 var p = this.DB-(i*this.DB)%k; 19588 if(i-- > 0) { 19589 if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } 19590 while(i >= 0) { 19591 if(p < k) { 19592 d = (this[i]&((1<<p)-1))<<(k-p); 19593 d |= this[--i]>>(p+=this.DB-k); 19594 } 19595 else { 19596 d = (this[i]>>(p-=k))&km; 19597 if(p <= 0) { p += this.DB; --i; } 19598 } 19599 if(d > 0) m = true; 19600 if(m) r += int2char(d); 19601 } 19602 } 19603 return m?r:"0"; 19604 } 19605 19606 // (public) -this 19607 function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } 19608 19609 // (public) |this| 19610 function bnAbs() { return (this.s<0)?this.negate():this; } 19611 19612 // (public) return + if this > a, - if this < a, 0 if equal 19613 function bnCompareTo(a) { 19614 var r = this.s-a.s; 19615 if(r != 0) return r; 19616 var i = this.t; 19617 r = i-a.t; 19618 if(r != 0) return (this.s<0)?-r:r; 19619 while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; 19620 return 0; 19621 } 19622 19623 // returns bit length of the integer x 19624 function nbits(x) { 19625 var r = 1, t; 19626 if((t=x>>>16) != 0) { x = t; r += 16; } 19627 if((t=x>>8) != 0) { x = t; r += 8; } 19628 if((t=x>>4) != 0) { x = t; r += 4; } 19629 if((t=x>>2) != 0) { x = t; r += 2; } 19630 if((t=x>>1) != 0) { x = t; r += 1; } 19631 return r; 19632 } 19633 19634 // (public) return the number of bits in "this" 19635 function bnBitLength() { 19636 if(this.t <= 0) return 0; 19637 return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); 19638 } 19639 19640 // (protected) r = this << n*DB 19641 function bnpDLShiftTo(n,r) { 19642 var i; 19643 for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; 19644 for(i = n-1; i >= 0; --i) r[i] = 0; 19645 r.t = this.t+n; 19646 r.s = this.s; 19647 } 19648 19649 // (protected) r = this >> n*DB 19650 function bnpDRShiftTo(n,r) { 19651 for(var i = n; i < this.t; ++i) r[i-n] = this[i]; 19652 r.t = Math.max(this.t-n,0); 19653 r.s = this.s; 19654 } 19655 19656 // (protected) r = this << n 19657 function bnpLShiftTo(n,r) { 19658 var bs = n%this.DB; 19659 var cbs = this.DB-bs; 19660 var bm = (1<<cbs)-1; 19661 var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; 19662 for(i = this.t-1; i >= 0; --i) { 19663 r[i+ds+1] = (this[i]>>cbs)|c; 19664 c = (this[i]&bm)<<bs; 19665 } 19666 for(i = ds-1; i >= 0; --i) r[i] = 0; 19667 r[ds] = c; 19668 r.t = this.t+ds+1; 19669 r.s = this.s; 19670 r.clamp(); 19671 } 19672 19673 // (protected) r = this >> n 19674 function bnpRShiftTo(n,r) { 19675 r.s = this.s; 19676 var ds = Math.floor(n/this.DB); 19677 if(ds >= this.t) { r.t = 0; return; } 19678 var bs = n%this.DB; 19679 var cbs = this.DB-bs; 19680 var bm = (1<<bs)-1; 19681 r[0] = this[ds]>>bs; 19682 for(var i = ds+1; i < this.t; ++i) { 19683 r[i-ds-1] |= (this[i]&bm)<<cbs; 19684 r[i-ds] = this[i]>>bs; 19685 } 19686 if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; 19687 r.t = this.t-ds; 19688 r.clamp(); 19689 } 19690 19691 // (protected) r = this - a 19692 function bnpSubTo(a,r) { 19693 var i = 0, c = 0, m = Math.min(a.t,this.t); 19694 while(i < m) { 19695 c += this[i]-a[i]; 19696 r[i++] = c&this.DM; 19697 c >>= this.DB; 19698 } 19699 if(a.t < this.t) { 19700 c -= a.s; 19701 while(i < this.t) { 19702 c += this[i]; 19703 r[i++] = c&this.DM; 19704 c >>= this.DB; 19705 } 19706 c += this.s; 19707 } 19708 else { 19709 c += this.s; 19710 while(i < a.t) { 19711 c -= a[i]; 19712 r[i++] = c&this.DM; 19713 c >>= this.DB; 19714 } 19715 c -= a.s; 19716 } 19717 r.s = (c<0)?-1:0; 19718 if(c < -1) r[i++] = this.DV+c; 19719 else if(c > 0) r[i++] = c; 19720 r.t = i; 19721 r.clamp(); 19722 } 19723 19724 // (protected) r = this * a, r != this,a (HAC 14.12) 19725 // "this" should be the larger one if appropriate. 19726 function bnpMultiplyTo(a,r) { 19727 var x = this.abs(), y = a.abs(); 19728 var i = x.t; 19729 r.t = i+y.t; 19730 while(--i >= 0) r[i] = 0; 19731 for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); 19732 r.s = 0; 19733 r.clamp(); 19734 if(this.s != a.s) BigInteger.ZERO.subTo(r,r); 19735 } 19736 19737 // (protected) r = this^2, r != this (HAC 14.16) 19738 function bnpSquareTo(r) { 19739 var x = this.abs(); 19740 var i = r.t = 2*x.t; 19741 while(--i >= 0) r[i] = 0; 19742 for(i = 0; i < x.t-1; ++i) { 19743 var c = x.am(i,x[i],r,2*i,0,1); 19744 if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { 19745 r[i+x.t] -= x.DV; 19746 r[i+x.t+1] = 1; 19747 } 19748 } 19749 if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); 19750 r.s = 0; 19751 r.clamp(); 19752 } 19753 19754 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) 19755 // r != q, this != m. q or r may be null. 19756 function bnpDivRemTo(m,q,r) { 19757 var pm = m.abs(); 19758 if(pm.t <= 0) return; 19759 var pt = this.abs(); 19760 if(pt.t < pm.t) { 19761 if(q != null) q.fromInt(0); 19762 if(r != null) this.copyTo(r); 19763 return; 19764 } 19765 if(r == null) r = nbi(); 19766 var y = nbi(), ts = this.s, ms = m.s; 19767 var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus 19768 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } 19769 else { pm.copyTo(y); pt.copyTo(r); } 19770 var ys = y.t; 19771 var y0 = y[ys-1]; 19772 if(y0 == 0) return; 19773 var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); 19774 var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; 19775 var i = r.t, j = i-ys, t = (q==null)?nbi():q; 19776 y.dlShiftTo(j,t); 19777 if(r.compareTo(t) >= 0) { 19778 r[r.t++] = 1; 19779 r.subTo(t,r); 19780 } 19781 BigInteger.ONE.dlShiftTo(ys,t); 19782 t.subTo(y,y); // "negative" y so we can replace sub with am later 19783 while(y.t < ys) y[y.t++] = 0; 19784 while(--j >= 0) { 19785 // Estimate quotient digit 19786 var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); 19787 if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out 19788 y.dlShiftTo(j,t); 19789 r.subTo(t,r); 19790 while(r[i] < --qd) r.subTo(t,r); 19791 } 19792 } 19793 if(q != null) { 19794 r.drShiftTo(ys,q); 19795 if(ts != ms) BigInteger.ZERO.subTo(q,q); 19796 } 19797 r.t = ys; 19798 r.clamp(); 19799 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder 19800 if(ts < 0) BigInteger.ZERO.subTo(r,r); 19801 } 19802 19803 // (public) this mod a 19804 function bnMod(a) { 19805 var r = nbi(); 19806 this.abs().divRemTo(a,null,r); 19807 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); 19808 return r; 19809 } 19810 19811 // Modular reduction using "classic" algorithm 19812 function Classic(m) { this.m = m; } 19813 function cConvert(x) { 19814 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); 19815 else return x; 19816 } 19817 function cRevert(x) { return x; } 19818 function cReduce(x) { x.divRemTo(this.m,null,x); } 19819 function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } 19820 function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } 19821 19822 Classic.prototype.convert = cConvert; 19823 Classic.prototype.revert = cRevert; 19824 Classic.prototype.reduce = cReduce; 19825 Classic.prototype.mulTo = cMulTo; 19826 Classic.prototype.sqrTo = cSqrTo; 19827 19828 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction 19829 // justification: 19830 // xy == 1 (mod m) 19831 // xy = 1+km 19832 // xy(2-xy) = (1+km)(1-km) 19833 // x[y(2-xy)] = 1-k^2m^2 19834 // x[y(2-xy)] == 1 (mod m^2) 19835 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 19836 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. 19837 // JS multiply "overflows" differently from C/C++, so care is needed here. 19838 function bnpInvDigit() { 19839 if(this.t < 1) return 0; 19840 var x = this[0]; 19841 if((x&1) == 0) return 0; 19842 var y = x&3; // y == 1/x mod 2^2 19843 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 19844 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 19845 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 19846 // last step - calculate inverse mod DV directly; 19847 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints 19848 y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits 19849 // we really want the negative inverse, and -DV < y < DV 19850 return (y>0)?this.DV-y:-y; 19851 } 19852 19853 // Montgomery reduction 19854 function Montgomery(m) { 19855 this.m = m; 19856 this.mp = m.invDigit(); 19857 this.mpl = this.mp&0x7fff; 19858 this.mph = this.mp>>15; 19859 this.um = (1<<(m.DB-15))-1; 19860 this.mt2 = 2*m.t; 19861 } 19862 19863 // xR mod m 19864 function montConvert(x) { 19865 var r = nbi(); 19866 x.abs().dlShiftTo(this.m.t,r); 19867 r.divRemTo(this.m,null,r); 19868 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); 19869 return r; 19870 } 19871 19872 // x/R mod m 19873 function montRevert(x) { 19874 var r = nbi(); 19875 x.copyTo(r); 19876 this.reduce(r); 19877 return r; 19878 } 19879 19880 // x = x/R mod m (HAC 14.32) 19881 function montReduce(x) { 19882 while(x.t <= this.mt2) // pad x so am has enough room later 19883 x[x.t++] = 0; 19884 for(var i = 0; i < this.m.t; ++i) { 19885 // faster way of calculating u0 = x[i]*mp mod DV 19886 var j = x[i]&0x7fff; 19887 var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; 19888 // use am to combine the multiply-shift-add into one call 19889 j = i+this.m.t; 19890 x[j] += this.m.am(0,u0,x,i,0,this.m.t); 19891 // propagate carry 19892 while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } 19893 } 19894 x.clamp(); 19895 x.drShiftTo(this.m.t,x); 19896 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); 19897 } 19898 19899 // r = "x^2/R mod m"; x != r 19900 function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } 19901 19902 // r = "xy/R mod m"; x,y != r 19903 function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } 19904 19905 Montgomery.prototype.convert = montConvert; 19906 Montgomery.prototype.revert = montRevert; 19907 Montgomery.prototype.reduce = montReduce; 19908 Montgomery.prototype.mulTo = montMulTo; 19909 Montgomery.prototype.sqrTo = montSqrTo; 19910 19911 // (protected) true iff this is even 19912 function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } 19913 19914 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) 19915 function bnpExp(e,z) { 19916 if(e > 0xffffffff || e < 1) return BigInteger.ONE; 19917 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; 19918 g.copyTo(r); 19919 while(--i >= 0) { 19920 z.sqrTo(r,r2); 19921 if((e&(1<<i)) > 0) z.mulTo(r2,g,r); 19922 else { var t = r; r = r2; r2 = t; } 19923 } 19924 return z.revert(r); 19925 } 19926 19927 // (public) this^e % m, 0 <= e < 2^32 19928 function bnModPowInt(e,m) { 19929 var z; 19930 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); 19931 return this.exp(e,z); 19932 } 19933 19934 // protected 19935 BigInteger.prototype.copyTo = bnpCopyTo; 19936 BigInteger.prototype.fromInt = bnpFromInt; 19937 BigInteger.prototype.fromString = bnpFromString; 19938 BigInteger.prototype.clamp = bnpClamp; 19939 BigInteger.prototype.dlShiftTo = bnpDLShiftTo; 19940 BigInteger.prototype.drShiftTo = bnpDRShiftTo; 19941 BigInteger.prototype.lShiftTo = bnpLShiftTo; 19942 BigInteger.prototype.rShiftTo = bnpRShiftTo; 19943 BigInteger.prototype.subTo = bnpSubTo; 19944 BigInteger.prototype.multiplyTo = bnpMultiplyTo; 19945 BigInteger.prototype.squareTo = bnpSquareTo; 19946 BigInteger.prototype.divRemTo = bnpDivRemTo; 19947 BigInteger.prototype.invDigit = bnpInvDigit; 19948 BigInteger.prototype.isEven = bnpIsEven; 19949 BigInteger.prototype.exp = bnpExp; 19950 19951 // public 19952 BigInteger.prototype.toString = bnToString; 19953 BigInteger.prototype.negate = bnNegate; 19954 BigInteger.prototype.abs = bnAbs; 19955 BigInteger.prototype.compareTo = bnCompareTo; 19956 BigInteger.prototype.bitLength = bnBitLength; 19957 BigInteger.prototype.mod = bnMod; 19958 BigInteger.prototype.modPowInt = bnModPowInt; 19959 19960 // "constants" 19961 BigInteger.ZERO = nbv(0); 19962 BigInteger.ONE = nbv(1); 19963 19964 // Copyright (c) 2005-2009 Tom Wu 19965 // All Rights Reserved. 19966 // See "LICENSE" for details. 19967 19968 // Extended JavaScript BN functions, required for RSA private ops. 19969 19970 // Version 1.1: new BigInteger("0", 10) returns "proper" zero 19971 // Version 1.2: square() API, isProbablePrime fix 19972 19973 // (public) 19974 function bnClone() { var r = nbi(); this.copyTo(r); return r; } 19975 19976 // (public) return value as integer 19977 function bnIntValue() { 19978 if(this.s < 0) { 19979 if(this.t == 1) return this[0]-this.DV; 19980 else if(this.t == 0) return -1; 19981 } 19982 else if(this.t == 1) return this[0]; 19983 else if(this.t == 0) return 0; 19984 // assumes 16 < DB < 32 19985 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]; 19986 } 19987 19988 // (public) return value as byte 19989 function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; } 19990 19991 // (public) return value as short (assumes DB>=16) 19992 function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } 19993 19994 // (protected) return x s.t. r^x < DV 19995 function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } 19996 19997 // (public) 0 if this == 0, 1 if this > 0 19998 function bnSigNum() { 19999 if(this.s < 0) return -1; 20000 else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; 20001 else return 1; 20002 } 20003 20004 // (protected) convert to radix string 20005 function bnpToRadix(b) { 20006 if(b == null) b = 10; 20007 if(this.signum() == 0 || b < 2 || b > 36) return "0"; 20008 var cs = this.chunkSize(b); 20009 var a = Math.pow(b,cs); 20010 var d = nbv(a), y = nbi(), z = nbi(), r = ""; 20011 this.divRemTo(d,y,z); 20012 while(y.signum() > 0) { 20013 r = (a+z.intValue()).toString(b).substr(1) + r; 20014 y.divRemTo(d,y,z); 20015 } 20016 return z.intValue().toString(b) + r; 20017 } 20018 20019 // (protected) convert from radix string 20020 function bnpFromRadix(s,b) { 20021 this.fromInt(0); 20022 if(b == null) b = 10; 20023 var cs = this.chunkSize(b); 20024 var d = Math.pow(b,cs), mi = false, j = 0, w = 0; 20025 for(var i = 0; i < s.length; ++i) { 20026 var x = intAt(s,i); 20027 if(x < 0) { 20028 if(s.charAt(i) == "-" && this.signum() == 0) mi = true; 20029 continue; 20030 } 20031 w = b*w+x; 20032 if(++j >= cs) { 20033 this.dMultiply(d); 20034 this.dAddOffset(w,0); 20035 j = 0; 20036 w = 0; 20037 } 20038 } 20039 if(j > 0) { 20040 this.dMultiply(Math.pow(b,j)); 20041 this.dAddOffset(w,0); 20042 } 20043 if(mi) BigInteger.ZERO.subTo(this,this); 20044 } 20045 20046 // (protected) alternate constructor 20047 function bnpFromNumber(a,b,c) { 20048 if("number" == typeof b) { 20049 // new BigInteger(int,int,RNG) 20050 if(a < 2) this.fromInt(1); 20051 else { 20052 this.fromNumber(a,c); 20053 if(!this.testBit(a-1)) // force MSB set 20054 this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); 20055 if(this.isEven()) this.dAddOffset(1,0); // force odd 20056 while(!this.isProbablePrime(b)) { 20057 this.dAddOffset(2,0); 20058 if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); 20059 } 20060 } 20061 } 20062 else { 20063 // new BigInteger(int,RNG) 20064 var x = new Array(), t = a&7; 20065 x.length = (a>>3)+1; 20066 b.nextBytes(x); 20067 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; 20068 this.fromString(x,256); 20069 } 20070 } 20071 20072 // (public) convert to bigendian byte array 20073 function bnToByteArray() { 20074 var i = this.t, r = new Array(); 20075 r[0] = this.s; 20076 var p = this.DB-(i*this.DB)%8, d, k = 0; 20077 if(i-- > 0) { 20078 if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) 20079 r[k++] = d|(this.s<<(this.DB-p)); 20080 while(i >= 0) { 20081 if(p < 8) { 20082 d = (this[i]&((1<<p)-1))<<(8-p); 20083 d |= this[--i]>>(p+=this.DB-8); 20084 } 20085 else { 20086 d = (this[i]>>(p-=8))&0xff; 20087 if(p <= 0) { p += this.DB; --i; } 20088 } 20089 if((d&0x80) != 0) d |= -256; 20090 if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; 20091 if(k > 0 || d != this.s) r[k++] = d; 20092 } 20093 } 20094 return r; 20095 } 20096 20097 function bnEquals(a) { return(this.compareTo(a)==0); } 20098 function bnMin(a) { return(this.compareTo(a)<0)?this:a; } 20099 function bnMax(a) { return(this.compareTo(a)>0)?this:a; } 20100 20101 // (protected) r = this op a (bitwise) 20102 function bnpBitwiseTo(a,op,r) { 20103 var i, f, m = Math.min(a.t,this.t); 20104 for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); 20105 if(a.t < this.t) { 20106 f = a.s&this.DM; 20107 for(i = m; i < this.t; ++i) r[i] = op(this[i],f); 20108 r.t = this.t; 20109 } 20110 else { 20111 f = this.s&this.DM; 20112 for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); 20113 r.t = a.t; 20114 } 20115 r.s = op(this.s,a.s); 20116 r.clamp(); 20117 } 20118 20119 // (public) this & a 20120 function op_and(x,y) { return x&y; } 20121 function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } 20122 20123 // (public) this | a 20124 function op_or(x,y) { return x|y; } 20125 function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } 20126 20127 // (public) this ^ a 20128 function op_xor(x,y) { return x^y; } 20129 function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } 20130 20131 // (public) this & ~a 20132 function op_andnot(x,y) { return x&~y; } 20133 function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } 20134 20135 // (public) ~this 20136 function bnNot() { 20137 var r = nbi(); 20138 for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; 20139 r.t = this.t; 20140 r.s = ~this.s; 20141 return r; 20142 } 20143 20144 // (public) this << n 20145 function bnShiftLeft(n) { 20146 var r = nbi(); 20147 if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); 20148 return r; 20149 } 20150 20151 // (public) this >> n 20152 function bnShiftRight(n) { 20153 var r = nbi(); 20154 if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); 20155 return r; 20156 } 20157 20158 // return index of lowest 1-bit in x, x < 2^31 20159 function lbit(x) { 20160 if(x == 0) return -1; 20161 var r = 0; 20162 if((x&0xffff) == 0) { x >>= 16; r += 16; } 20163 if((x&0xff) == 0) { x >>= 8; r += 8; } 20164 if((x&0xf) == 0) { x >>= 4; r += 4; } 20165 if((x&3) == 0) { x >>= 2; r += 2; } 20166 if((x&1) == 0) ++r; 20167 return r; 20168 } 20169 20170 // (public) returns index of lowest 1-bit (or -1 if none) 20171 function bnGetLowestSetBit() { 20172 for(var i = 0; i < this.t; ++i) 20173 if(this[i] != 0) return i*this.DB+lbit(this[i]); 20174 if(this.s < 0) return this.t*this.DB; 20175 return -1; 20176 } 20177 20178 // return number of 1 bits in x 20179 function cbit(x) { 20180 var r = 0; 20181 while(x != 0) { x &= x-1; ++r; } 20182 return r; 20183 } 20184 20185 // (public) return number of set bits 20186 function bnBitCount() { 20187 var r = 0, x = this.s&this.DM; 20188 for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); 20189 return r; 20190 } 20191 20192 // (public) true iff nth bit is set 20193 function bnTestBit(n) { 20194 var j = Math.floor(n/this.DB); 20195 if(j >= this.t) return(this.s!=0); 20196 return((this[j]&(1<<(n%this.DB)))!=0); 20197 } 20198 20199 // (protected) this op (1<<n) 20200 function bnpChangeBit(n,op) { 20201 var r = BigInteger.ONE.shiftLeft(n); 20202 this.bitwiseTo(r,op,r); 20203 return r; 20204 } 20205 20206 // (public) this | (1<<n) 20207 function bnSetBit(n) { return this.changeBit(n,op_or); } 20208 20209 // (public) this & ~(1<<n) 20210 function bnClearBit(n) { return this.changeBit(n,op_andnot); } 20211 20212 // (public) this ^ (1<<n) 20213 function bnFlipBit(n) { return this.changeBit(n,op_xor); } 20214 20215 // (protected) r = this + a 20216 function bnpAddTo(a,r) { 20217 var i = 0, c = 0, m = Math.min(a.t,this.t); 20218 while(i < m) { 20219 c += this[i]+a[i]; 20220 r[i++] = c&this.DM; 20221 c >>= this.DB; 20222 } 20223 if(a.t < this.t) { 20224 c += a.s; 20225 while(i < this.t) { 20226 c += this[i]; 20227 r[i++] = c&this.DM; 20228 c >>= this.DB; 20229 } 20230 c += this.s; 20231 } 20232 else { 20233 c += this.s; 20234 while(i < a.t) { 20235 c += a[i]; 20236 r[i++] = c&this.DM; 20237 c >>= this.DB; 20238 } 20239 c += a.s; 20240 } 20241 r.s = (c<0)?-1:0; 20242 if(c > 0) r[i++] = c; 20243 else if(c < -1) r[i++] = this.DV+c; 20244 r.t = i; 20245 r.clamp(); 20246 } 20247 20248 // (public) this + a 20249 function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } 20250 20251 // (public) this - a 20252 function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } 20253 20254 // (public) this * a 20255 function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } 20256 20257 // (public) this^2 20258 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } 20259 20260 // (public) this / a 20261 function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } 20262 20263 // (public) this % a 20264 function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } 20265 20266 // (public) [this/a,this%a] 20267 function bnDivideAndRemainder(a) { 20268 var q = nbi(), r = nbi(); 20269 this.divRemTo(a,q,r); 20270 return new Array(q,r); 20271 } 20272 20273 // (protected) this *= n, this >= 0, 1 < n < DV 20274 function bnpDMultiply(n) { 20275 this[this.t] = this.am(0,n-1,this,0,0,this.t); 20276 ++this.t; 20277 this.clamp(); 20278 } 20279 20280 // (protected) this += n << w words, this >= 0 20281 function bnpDAddOffset(n,w) { 20282 if(n == 0) return; 20283 while(this.t <= w) this[this.t++] = 0; 20284 this[w] += n; 20285 while(this[w] >= this.DV) { 20286 this[w] -= this.DV; 20287 if(++w >= this.t) this[this.t++] = 0; 20288 ++this[w]; 20289 } 20290 } 20291 20292 // A "null" reducer 20293 function NullExp() {} 20294 function nNop(x) { return x; } 20295 function nMulTo(x,y,r) { x.multiplyTo(y,r); } 20296 function nSqrTo(x,r) { x.squareTo(r); } 20297 20298 NullExp.prototype.convert = nNop; 20299 NullExp.prototype.revert = nNop; 20300 NullExp.prototype.mulTo = nMulTo; 20301 NullExp.prototype.sqrTo = nSqrTo; 20302 20303 // (public) this^e 20304 function bnPow(e) { return this.exp(e,new NullExp()); } 20305 20306 // (protected) r = lower n words of "this * a", a.t <= n 20307 // "this" should be the larger one if appropriate. 20308 function bnpMultiplyLowerTo(a,n,r) { 20309 var i = Math.min(this.t+a.t,n); 20310 r.s = 0; // assumes a,this >= 0 20311 r.t = i; 20312 while(i > 0) r[--i] = 0; 20313 var j; 20314 for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); 20315 for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); 20316 r.clamp(); 20317 } 20318 20319 // (protected) r = "this * a" without lower n words, n > 0 20320 // "this" should be the larger one if appropriate. 20321 function bnpMultiplyUpperTo(a,n,r) { 20322 --n; 20323 var i = r.t = this.t+a.t-n; 20324 r.s = 0; // assumes a,this >= 0 20325 while(--i >= 0) r[i] = 0; 20326 for(i = Math.max(n-this.t,0); i < a.t; ++i) 20327 r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); 20328 r.clamp(); 20329 r.drShiftTo(1,r); 20330 } 20331 20332 // Barrett modular reduction 20333 function Barrett(m) { 20334 // setup Barrett 20335 this.r2 = nbi(); 20336 this.q3 = nbi(); 20337 BigInteger.ONE.dlShiftTo(2*m.t,this.r2); 20338 this.mu = this.r2.divide(m); 20339 this.m = m; 20340 } 20341 20342 function barrettConvert(x) { 20343 if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); 20344 else if(x.compareTo(this.m) < 0) return x; 20345 else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } 20346 } 20347 20348 function barrettRevert(x) { return x; } 20349 20350 // x = x mod m (HAC 14.42) 20351 function barrettReduce(x) { 20352 x.drShiftTo(this.m.t-1,this.r2); 20353 if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } 20354 this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); 20355 this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); 20356 while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); 20357 x.subTo(this.r2,x); 20358 while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); 20359 } 20360 20361 // r = x^2 mod m; x != r 20362 function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } 20363 20364 // r = x*y mod m; x,y != r 20365 function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } 20366 20367 Barrett.prototype.convert = barrettConvert; 20368 Barrett.prototype.revert = barrettRevert; 20369 Barrett.prototype.reduce = barrettReduce; 20370 Barrett.prototype.mulTo = barrettMulTo; 20371 Barrett.prototype.sqrTo = barrettSqrTo; 20372 20373 // (public) this^e % m (HAC 14.85) 20374 function bnModPow(e,m) { 20375 var i = e.bitLength(), k, r = nbv(1), z; 20376 if(i <= 0) return r; 20377 else if(i < 18) k = 1; 20378 else if(i < 48) k = 3; 20379 else if(i < 144) k = 4; 20380 else if(i < 768) k = 5; 20381 else k = 6; 20382 if(i < 8) 20383 z = new Classic(m); 20384 else if(m.isEven()) 20385 z = new Barrett(m); 20386 else 20387 z = new Montgomery(m); 20388 20389 // precomputation 20390 var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1; 20391 g[1] = z.convert(this); 20392 if(k > 1) { 20393 var g2 = nbi(); 20394 z.sqrTo(g[1],g2); 20395 while(n <= km) { 20396 g[n] = nbi(); 20397 z.mulTo(g2,g[n-2],g[n]); 20398 n += 2; 20399 } 20400 } 20401 20402 var j = e.t-1, w, is1 = true, r2 = nbi(), t; 20403 i = nbits(e[j])-1; 20404 while(j >= 0) { 20405 if(i >= k1) w = (e[j]>>(i-k1))&km; 20406 else { 20407 w = (e[j]&((1<<(i+1))-1))<<(k1-i); 20408 if(j > 0) w |= e[j-1]>>(this.DB+i-k1); 20409 } 20410 20411 n = k; 20412 while((w&1) == 0) { w >>= 1; --n; } 20413 if((i -= n) < 0) { i += this.DB; --j; } 20414 if(is1) { // ret == 1, don't bother squaring or multiplying it 20415 g[w].copyTo(r); 20416 is1 = false; 20417 } 20418 else { 20419 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } 20420 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } 20421 z.mulTo(r2,g[w],r); 20422 } 20423 20424 while(j >= 0 && (e[j]&(1<<i)) == 0) { 20425 z.sqrTo(r,r2); t = r; r = r2; r2 = t; 20426 if(--i < 0) { i = this.DB-1; --j; } 20427 } 20428 } 20429 return z.revert(r); 20430 } 20431 20432 // (public) gcd(this,a) (HAC 14.54) 20433 function bnGCD(a) { 20434 var x = (this.s<0)?this.negate():this.clone(); 20435 var y = (a.s<0)?a.negate():a.clone(); 20436 if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } 20437 var i = x.getLowestSetBit(), g = y.getLowestSetBit(); 20438 if(g < 0) return x; 20439 if(i < g) g = i; 20440 if(g > 0) { 20441 x.rShiftTo(g,x); 20442 y.rShiftTo(g,y); 20443 } 20444 while(x.signum() > 0) { 20445 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); 20446 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); 20447 if(x.compareTo(y) >= 0) { 20448 x.subTo(y,x); 20449 x.rShiftTo(1,x); 20450 } 20451 else { 20452 y.subTo(x,y); 20453 y.rShiftTo(1,y); 20454 } 20455 } 20456 if(g > 0) y.lShiftTo(g,y); 20457 return y; 20458 } 20459 20460 // (protected) this % n, n < 2^26 20461 function bnpModInt(n) { 20462 if(n <= 0) return 0; 20463 var d = this.DV%n, r = (this.s<0)?n-1:0; 20464 if(this.t > 0) 20465 if(d == 0) r = this[0]%n; 20466 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; 20467 return r; 20468 } 20469 20470 // (public) 1/this % m (HAC 14.61) 20471 function bnModInverse(m) { 20472 var ac = m.isEven(); 20473 if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; 20474 var u = m.clone(), v = this.clone(); 20475 var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); 20476 while(u.signum() != 0) { 20477 while(u.isEven()) { 20478 u.rShiftTo(1,u); 20479 if(ac) { 20480 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } 20481 a.rShiftTo(1,a); 20482 } 20483 else if(!b.isEven()) b.subTo(m,b); 20484 b.rShiftTo(1,b); 20485 } 20486 while(v.isEven()) { 20487 v.rShiftTo(1,v); 20488 if(ac) { 20489 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } 20490 c.rShiftTo(1,c); 20491 } 20492 else if(!d.isEven()) d.subTo(m,d); 20493 d.rShiftTo(1,d); 20494 } 20495 if(u.compareTo(v) >= 0) { 20496 u.subTo(v,u); 20497 if(ac) a.subTo(c,a); 20498 b.subTo(d,b); 20499 } 20500 else { 20501 v.subTo(u,v); 20502 if(ac) c.subTo(a,c); 20503 d.subTo(b,d); 20504 } 20505 } 20506 if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; 20507 if(d.compareTo(m) >= 0) return d.subtract(m); 20508 if(d.signum() < 0) d.addTo(m,d); else return d; 20509 if(d.signum() < 0) return d.add(m); else return d; 20510 } 20511 20512 var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; 20513 var lplim = (1<<26)/lowprimes[lowprimes.length-1]; 20514 20515 // (public) test primality with certainty >= 1-.5^t 20516 function bnIsProbablePrime(t) { 20517 var i, x = this.abs(); 20518 if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { 20519 for(i = 0; i < lowprimes.length; ++i) 20520 if(x[0] == lowprimes[i]) return true; 20521 return false; 20522 } 20523 if(x.isEven()) return false; 20524 i = 1; 20525 while(i < lowprimes.length) { 20526 var m = lowprimes[i], j = i+1; 20527 while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; 20528 m = x.modInt(m); 20529 while(i < j) if(m%lowprimes[i++] == 0) return false; 20530 } 20531 return x.millerRabin(t); 20532 } 20533 20534 // (protected) true if probably prime (HAC 4.24, Miller-Rabin) 20535 function bnpMillerRabin(t) { 20536 var n1 = this.subtract(BigInteger.ONE); 20537 var k = n1.getLowestSetBit(); 20538 if(k <= 0) return false; 20539 var r = n1.shiftRight(k); 20540 t = (t+1)>>1; 20541 if(t > lowprimes.length) t = lowprimes.length; 20542 var a = nbi(); 20543 for(var i = 0; i < t; ++i) { 20544 //Pick bases at random, instead of starting at 2 20545 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); 20546 var y = a.modPow(r,this); 20547 if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { 20548 var j = 1; 20549 while(j++ < k && y.compareTo(n1) != 0) { 20550 y = y.modPowInt(2,this); 20551 if(y.compareTo(BigInteger.ONE) == 0) return false; 20552 } 20553 if(y.compareTo(n1) != 0) return false; 20554 } 20555 } 20556 return true; 20557 } 20558 20559 // protected 20560 BigInteger.prototype.chunkSize = bnpChunkSize; 20561 BigInteger.prototype.toRadix = bnpToRadix; 20562 BigInteger.prototype.fromRadix = bnpFromRadix; 20563 BigInteger.prototype.fromNumber = bnpFromNumber; 20564 BigInteger.prototype.bitwiseTo = bnpBitwiseTo; 20565 BigInteger.prototype.changeBit = bnpChangeBit; 20566 BigInteger.prototype.addTo = bnpAddTo; 20567 BigInteger.prototype.dMultiply = bnpDMultiply; 20568 BigInteger.prototype.dAddOffset = bnpDAddOffset; 20569 BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; 20570 BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; 20571 BigInteger.prototype.modInt = bnpModInt; 20572 BigInteger.prototype.millerRabin = bnpMillerRabin; 20573 20574 // public 20575 BigInteger.prototype.clone = bnClone; 20576 BigInteger.prototype.intValue = bnIntValue; 20577 BigInteger.prototype.byteValue = bnByteValue; 20578 BigInteger.prototype.shortValue = bnShortValue; 20579 BigInteger.prototype.signum = bnSigNum; 20580 BigInteger.prototype.toByteArray = bnToByteArray; 20581 BigInteger.prototype.equals = bnEquals; 20582 BigInteger.prototype.min = bnMin; 20583 BigInteger.prototype.max = bnMax; 20584 BigInteger.prototype.and = bnAnd; 20585 BigInteger.prototype.or = bnOr; 20586 BigInteger.prototype.xor = bnXor; 20587 BigInteger.prototype.andNot = bnAndNot; 20588 BigInteger.prototype.not = bnNot; 20589 BigInteger.prototype.shiftLeft = bnShiftLeft; 20590 BigInteger.prototype.shiftRight = bnShiftRight; 20591 BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; 20592 BigInteger.prototype.bitCount = bnBitCount; 20593 BigInteger.prototype.testBit = bnTestBit; 20594 BigInteger.prototype.setBit = bnSetBit; 20595 BigInteger.prototype.clearBit = bnClearBit; 20596 BigInteger.prototype.flipBit = bnFlipBit; 20597 BigInteger.prototype.add = bnAdd; 20598 BigInteger.prototype.subtract = bnSubtract; 20599 BigInteger.prototype.multiply = bnMultiply; 20600 BigInteger.prototype.divide = bnDivide; 20601 BigInteger.prototype.remainder = bnRemainder; 20602 BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; 20603 BigInteger.prototype.modPow = bnModPow; 20604 BigInteger.prototype.modInverse = bnModInverse; 20605 BigInteger.prototype.pow = bnPow; 20606 BigInteger.prototype.gcd = bnGCD; 20607 BigInteger.prototype.isProbablePrime = bnIsProbablePrime; 20608 20609 // JSBN-specific extension 20610 BigInteger.prototype.square = bnSquare; 20611 20612 // Expose the Barrett function 20613 BigInteger.prototype.Barrett = Barrett 20614 20615 // BigInteger interfaces not implemented in jsbn: 20616 20617 // BigInteger(int signum, byte[] magnitude) 20618 // double doubleValue() 20619 // float floatValue() 20620 // int hashCode() 20621 // long longValue() 20622 // static BigInteger valueOf(long val) 20623 20624 // Random number generator - requires a PRNG backend, e.g. prng4.js 20625 20626 // For best results, put code like 20627 // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> 20628 // in your main HTML document. 20629 20630 var rng_state; 20631 var rng_pool; 20632 var rng_pptr; 20633 20634 // Mix in a 32-bit integer into the pool 20635 function rng_seed_int(x) { 20636 rng_pool[rng_pptr++] ^= x & 255; 20637 rng_pool[rng_pptr++] ^= (x >> 8) & 255; 20638 rng_pool[rng_pptr++] ^= (x >> 16) & 255; 20639 rng_pool[rng_pptr++] ^= (x >> 24) & 255; 20640 if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; 20641 } 20642 20643 // Mix in the current time (w/milliseconds) into the pool 20644 function rng_seed_time() { 20645 rng_seed_int(new Date().getTime()); 20646 } 20647 20648 // Initialize the pool with junk if needed. 20649 if(rng_pool == null) { 20650 rng_pool = new Array(); 20651 rng_pptr = 0; 20652 var t; 20653 if(typeof window !== "undefined" && window.crypto) { 20654 if (window.crypto.getRandomValues) { 20655 // Use webcrypto if available 20656 var ua = new Uint8Array(32); 20657 window.crypto.getRandomValues(ua); 20658 for(t = 0; t < 32; ++t) 20659 rng_pool[rng_pptr++] = ua[t]; 20660 } 20661 else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { 20662 // Extract entropy (256 bits) from NS4 RNG if available 20663 var z = window.crypto.random(32); 20664 for(t = 0; t < z.length; ++t) 20665 rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; 20666 } 20667 } 20668 while(rng_pptr < rng_psize) { // extract some randomness from Math.random() 20669 t = Math.floor(65536 * Math.random()); 20670 rng_pool[rng_pptr++] = t >>> 8; 20671 rng_pool[rng_pptr++] = t & 255; 20672 } 20673 rng_pptr = 0; 20674 rng_seed_time(); 20675 //rng_seed_int(window.screenX); 20676 //rng_seed_int(window.screenY); 20677 } 20678 20679 function rng_get_byte() { 20680 if(rng_state == null) { 20681 rng_seed_time(); 20682 rng_state = prng_newstate(); 20683 rng_state.init(rng_pool); 20684 for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) 20685 rng_pool[rng_pptr] = 0; 20686 rng_pptr = 0; 20687 //rng_pool = null; 20688 } 20689 // TODO: allow reseeding after first request 20690 return rng_state.next(); 20691 } 20692 20693 function rng_get_bytes(ba) { 20694 var i; 20695 for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); 20696 } 20697 20698 function SecureRandom() {} 20699 20700 SecureRandom.prototype.nextBytes = rng_get_bytes; 20701 20702 // prng4.js - uses Arcfour as a PRNG 20703 20704 function Arcfour() { 20705 this.i = 0; 20706 this.j = 0; 20707 this.S = new Array(); 20708 } 20709 20710 // Initialize arcfour context from key, an array of ints, each from [0..255] 20711 function ARC4init(key) { 20712 var i, j, t; 20713 for(i = 0; i < 256; ++i) 20714 this.S[i] = i; 20715 j = 0; 20716 for(i = 0; i < 256; ++i) { 20717 j = (j + this.S[i] + key[i % key.length]) & 255; 20718 t = this.S[i]; 20719 this.S[i] = this.S[j]; 20720 this.S[j] = t; 20721 } 20722 this.i = 0; 20723 this.j = 0; 20724 } 20725 20726 function ARC4next() { 20727 var t; 20728 this.i = (this.i + 1) & 255; 20729 this.j = (this.j + this.S[this.i]) & 255; 20730 t = this.S[this.i]; 20731 this.S[this.i] = this.S[this.j]; 20732 this.S[this.j] = t; 20733 return this.S[(t + this.S[this.i]) & 255]; 20734 } 20735 20736 Arcfour.prototype.init = ARC4init; 20737 Arcfour.prototype.next = ARC4next; 20738 20739 // Plug in your RNG constructor here 20740 function prng_newstate() { 20741 return new Arcfour(); 20742 } 20743 20744 // Pool size must be a multiple of 4 and greater than 32. 20745 // An array of bytes the size of the pool will be passed to init() 20746 var rng_psize = 256; 20747 20748 if (true) { 20749 exports = module.exports = { 20750 default: BigInteger, 20751 BigInteger: BigInteger, 20752 SecureRandom: SecureRandom, 20753 }; 20754 } else {} 20755 20756 }).call(this); 20757 20758 20759 /***/ }), 20760 20761 /***/ 7129: 20762 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 20763 20764 "use strict"; 20765 20766 20767 // A linked list to keep track of recently-used-ness 20768 const Yallist = __nccwpck_require__(665) 20769 20770 const MAX = Symbol('max') 20771 const LENGTH = Symbol('length') 20772 const LENGTH_CALCULATOR = Symbol('lengthCalculator') 20773 const ALLOW_STALE = Symbol('allowStale') 20774 const MAX_AGE = Symbol('maxAge') 20775 const DISPOSE = Symbol('dispose') 20776 const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') 20777 const LRU_LIST = Symbol('lruList') 20778 const CACHE = Symbol('cache') 20779 const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') 20780 20781 const naiveLength = () => 1 20782 20783 // lruList is a yallist where the head is the youngest 20784 // item, and the tail is the oldest. the list contains the Hit 20785 // objects as the entries. 20786 // Each Hit object has a reference to its Yallist.Node. This 20787 // never changes. 20788 // 20789 // cache is a Map (or PseudoMap) that matches the keys to 20790 // the Yallist.Node object. 20791 class LRUCache { 20792 constructor (options) { 20793 if (typeof options === 'number') 20794 options = { max: options } 20795 20796 if (!options) 20797 options = {} 20798 20799 if (options.max && (typeof options.max !== 'number' || options.max < 0)) 20800 throw new TypeError('max must be a non-negative number') 20801 // Kind of weird to have a default max of Infinity, but oh well. 20802 const max = this[MAX] = options.max || Infinity 20803 20804 const lc = options.length || naiveLength 20805 this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc 20806 this[ALLOW_STALE] = options.stale || false 20807 if (options.maxAge && typeof options.maxAge !== 'number') 20808 throw new TypeError('maxAge must be a number') 20809 this[MAX_AGE] = options.maxAge || 0 20810 this[DISPOSE] = options.dispose 20811 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false 20812 this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false 20813 this.reset() 20814 } 20815 20816 // resize the cache when the max changes. 20817 set max (mL) { 20818 if (typeof mL !== 'number' || mL < 0) 20819 throw new TypeError('max must be a non-negative number') 20820 20821 this[MAX] = mL || Infinity 20822 trim(this) 20823 } 20824 get max () { 20825 return this[MAX] 20826 } 20827 20828 set allowStale (allowStale) { 20829 this[ALLOW_STALE] = !!allowStale 20830 } 20831 get allowStale () { 20832 return this[ALLOW_STALE] 20833 } 20834 20835 set maxAge (mA) { 20836 if (typeof mA !== 'number') 20837 throw new TypeError('maxAge must be a non-negative number') 20838 20839 this[MAX_AGE] = mA 20840 trim(this) 20841 } 20842 get maxAge () { 20843 return this[MAX_AGE] 20844 } 20845 20846 // resize the cache when the lengthCalculator changes. 20847 set lengthCalculator (lC) { 20848 if (typeof lC !== 'function') 20849 lC = naiveLength 20850 20851 if (lC !== this[LENGTH_CALCULATOR]) { 20852 this[LENGTH_CALCULATOR] = lC 20853 this[LENGTH] = 0 20854 this[LRU_LIST].forEach(hit => { 20855 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) 20856 this[LENGTH] += hit.length 20857 }) 20858 } 20859 trim(this) 20860 } 20861 get lengthCalculator () { return this[LENGTH_CALCULATOR] } 20862 20863 get length () { return this[LENGTH] } 20864 get itemCount () { return this[LRU_LIST].length } 20865 20866 rforEach (fn, thisp) { 20867 thisp = thisp || this 20868 for (let walker = this[LRU_LIST].tail; walker !== null;) { 20869 const prev = walker.prev 20870 forEachStep(this, fn, walker, thisp) 20871 walker = prev 20872 } 20873 } 20874 20875 forEach (fn, thisp) { 20876 thisp = thisp || this 20877 for (let walker = this[LRU_LIST].head; walker !== null;) { 20878 const next = walker.next 20879 forEachStep(this, fn, walker, thisp) 20880 walker = next 20881 } 20882 } 20883 20884 keys () { 20885 return this[LRU_LIST].toArray().map(k => k.key) 20886 } 20887 20888 values () { 20889 return this[LRU_LIST].toArray().map(k => k.value) 20890 } 20891 20892 reset () { 20893 if (this[DISPOSE] && 20894 this[LRU_LIST] && 20895 this[LRU_LIST].length) { 20896 this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) 20897 } 20898 20899 this[CACHE] = new Map() // hash of items by key 20900 this[LRU_LIST] = new Yallist() // list of items in order of use recency 20901 this[LENGTH] = 0 // length of items in the list 20902 } 20903 20904 dump () { 20905 return this[LRU_LIST].map(hit => 20906 isStale(this, hit) ? false : { 20907 k: hit.key, 20908 v: hit.value, 20909 e: hit.now + (hit.maxAge || 0) 20910 }).toArray().filter(h => h) 20911 } 20912 20913 dumpLru () { 20914 return this[LRU_LIST] 20915 } 20916 20917 set (key, value, maxAge) { 20918 maxAge = maxAge || this[MAX_AGE] 20919 20920 if (maxAge && typeof maxAge !== 'number') 20921 throw new TypeError('maxAge must be a number') 20922 20923 const now = maxAge ? Date.now() : 0 20924 const len = this[LENGTH_CALCULATOR](value, key) 20925 20926 if (this[CACHE].has(key)) { 20927 if (len > this[MAX]) { 20928 del(this, this[CACHE].get(key)) 20929 return false 20930 } 20931 20932 const node = this[CACHE].get(key) 20933 const item = node.value 20934 20935 // dispose of the old one before overwriting 20936 // split out into 2 ifs for better coverage tracking 20937 if (this[DISPOSE]) { 20938 if (!this[NO_DISPOSE_ON_SET]) 20939 this[DISPOSE](key, item.value) 20940 } 20941 20942 item.now = now 20943 item.maxAge = maxAge 20944 item.value = value 20945 this[LENGTH] += len - item.length 20946 item.length = len 20947 this.get(key) 20948 trim(this) 20949 return true 20950 } 20951 20952 const hit = new Entry(key, value, len, now, maxAge) 20953 20954 // oversized objects fall out of cache automatically. 20955 if (hit.length > this[MAX]) { 20956 if (this[DISPOSE]) 20957 this[DISPOSE](key, value) 20958 20959 return false 20960 } 20961 20962 this[LENGTH] += hit.length 20963 this[LRU_LIST].unshift(hit) 20964 this[CACHE].set(key, this[LRU_LIST].head) 20965 trim(this) 20966 return true 20967 } 20968 20969 has (key) { 20970 if (!this[CACHE].has(key)) return false 20971 const hit = this[CACHE].get(key).value 20972 return !isStale(this, hit) 20973 } 20974 20975 get (key) { 20976 return get(this, key, true) 20977 } 20978 20979 peek (key) { 20980 return get(this, key, false) 20981 } 20982 20983 pop () { 20984 const node = this[LRU_LIST].tail 20985 if (!node) 20986 return null 20987 20988 del(this, node) 20989 return node.value 20990 } 20991 20992 del (key) { 20993 del(this, this[CACHE].get(key)) 20994 } 20995 20996 load (arr) { 20997 // reset the cache 20998 this.reset() 20999 21000 const now = Date.now() 21001 // A previous serialized cache has the most recent items first 21002 for (let l = arr.length - 1; l >= 0; l--) { 21003 const hit = arr[l] 21004 const expiresAt = hit.e || 0 21005 if (expiresAt === 0) 21006 // the item was created without expiration in a non aged cache 21007 this.set(hit.k, hit.v) 21008 else { 21009 const maxAge = expiresAt - now 21010 // dont add already expired items 21011 if (maxAge > 0) { 21012 this.set(hit.k, hit.v, maxAge) 21013 } 21014 } 21015 } 21016 } 21017 21018 prune () { 21019 this[CACHE].forEach((value, key) => get(this, key, false)) 21020 } 21021 } 21022 21023 const get = (self, key, doUse) => { 21024 const node = self[CACHE].get(key) 21025 if (node) { 21026 const hit = node.value 21027 if (isStale(self, hit)) { 21028 del(self, node) 21029 if (!self[ALLOW_STALE]) 21030 return undefined 21031 } else { 21032 if (doUse) { 21033 if (self[UPDATE_AGE_ON_GET]) 21034 node.value.now = Date.now() 21035 self[LRU_LIST].unshiftNode(node) 21036 } 21037 } 21038 return hit.value 21039 } 21040 } 21041 21042 const isStale = (self, hit) => { 21043 if (!hit || (!hit.maxAge && !self[MAX_AGE])) 21044 return false 21045 21046 const diff = Date.now() - hit.now 21047 return hit.maxAge ? diff > hit.maxAge 21048 : self[MAX_AGE] && (diff > self[MAX_AGE]) 21049 } 21050 21051 const trim = self => { 21052 if (self[LENGTH] > self[MAX]) { 21053 for (let walker = self[LRU_LIST].tail; 21054 self[LENGTH] > self[MAX] && walker !== null;) { 21055 // We know that we're about to delete this one, and also 21056 // what the next least recently used key will be, so just 21057 // go ahead and set it now. 21058 const prev = walker.prev 21059 del(self, walker) 21060 walker = prev 21061 } 21062 } 21063 } 21064 21065 const del = (self, node) => { 21066 if (node) { 21067 const hit = node.value 21068 if (self[DISPOSE]) 21069 self[DISPOSE](hit.key, hit.value) 21070 21071 self[LENGTH] -= hit.length 21072 self[CACHE].delete(hit.key) 21073 self[LRU_LIST].removeNode(node) 21074 } 21075 } 21076 21077 class Entry { 21078 constructor (key, value, length, now, maxAge) { 21079 this.key = key 21080 this.value = value 21081 this.length = length 21082 this.now = now 21083 this.maxAge = maxAge || 0 21084 } 21085 } 21086 21087 const forEachStep = (self, fn, node, thisp) => { 21088 let hit = node.value 21089 if (isStale(self, hit)) { 21090 del(self, node) 21091 if (!self[ALLOW_STALE]) 21092 hit = undefined 21093 } 21094 if (hit) 21095 fn.call(thisp, hit.value, hit.key, self) 21096 } 21097 21098 module.exports = LRUCache 21099 21100 21101 /***/ }), 21102 21103 /***/ 7943: 21104 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21105 21106 const { Request, Response } = __nccwpck_require__(8998) 21107 const { Minipass } = __nccwpck_require__(4968) 21108 const MinipassFlush = __nccwpck_require__(4181) 21109 const cacache = __nccwpck_require__(5490) 21110 const url = __nccwpck_require__(7310) 21111 21112 const CachingMinipassPipeline = __nccwpck_require__(1064) 21113 const CachePolicy = __nccwpck_require__(7986) 21114 const cacheKey = __nccwpck_require__(2147) 21115 const remote = __nccwpck_require__(2619) 21116 21117 const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) 21118 21119 // allow list for request headers that will be written to the cache index 21120 // note: we will also store any request headers 21121 // that are named in a response's vary header 21122 const KEEP_REQUEST_HEADERS = [ 21123 'accept-charset', 21124 'accept-encoding', 21125 'accept-language', 21126 'accept', 21127 'cache-control', 21128 ] 21129 21130 // allow list for response headers that will be written to the cache index 21131 // note: we must not store the real response's age header, or when we load 21132 // a cache policy based on the metadata it will think the cached response 21133 // is always stale 21134 const KEEP_RESPONSE_HEADERS = [ 21135 'cache-control', 21136 'content-encoding', 21137 'content-language', 21138 'content-type', 21139 'date', 21140 'etag', 21141 'expires', 21142 'last-modified', 21143 'link', 21144 'location', 21145 'pragma', 21146 'vary', 21147 ] 21148 21149 // return an object containing all metadata to be written to the index 21150 const getMetadata = (request, response, options) => { 21151 const metadata = { 21152 time: Date.now(), 21153 url: request.url, 21154 reqHeaders: {}, 21155 resHeaders: {}, 21156 21157 // options on which we must match the request and vary the response 21158 options: { 21159 compress: options.compress != null ? options.compress : request.compress, 21160 }, 21161 } 21162 21163 // only save the status if it's not a 200 or 304 21164 if (response.status !== 200 && response.status !== 304) { 21165 metadata.status = response.status 21166 } 21167 21168 for (const name of KEEP_REQUEST_HEADERS) { 21169 if (request.headers.has(name)) { 21170 metadata.reqHeaders[name] = request.headers.get(name) 21171 } 21172 } 21173 21174 // if the request's host header differs from the host in the url 21175 // we need to keep it, otherwise it's just noise and we ignore it 21176 const host = request.headers.get('host') 21177 const parsedUrl = new url.URL(request.url) 21178 if (host && parsedUrl.host !== host) { 21179 metadata.reqHeaders.host = host 21180 } 21181 21182 // if the response has a vary header, make sure 21183 // we store the relevant request headers too 21184 if (response.headers.has('vary')) { 21185 const vary = response.headers.get('vary') 21186 // a vary of "*" means every header causes a different response. 21187 // in that scenario, we do not include any additional headers 21188 // as the freshness check will always fail anyway and we don't 21189 // want to bloat the cache indexes 21190 if (vary !== '*') { 21191 // copy any other request headers that will vary the response 21192 const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) 21193 for (const name of varyHeaders) { 21194 if (request.headers.has(name)) { 21195 metadata.reqHeaders[name] = request.headers.get(name) 21196 } 21197 } 21198 } 21199 } 21200 21201 for (const name of KEEP_RESPONSE_HEADERS) { 21202 if (response.headers.has(name)) { 21203 metadata.resHeaders[name] = response.headers.get(name) 21204 } 21205 } 21206 21207 for (const name of options.cacheAdditionalHeaders) { 21208 if (response.headers.has(name)) { 21209 metadata.resHeaders[name] = response.headers.get(name) 21210 } 21211 } 21212 21213 return metadata 21214 } 21215 21216 // symbols used to hide objects that may be lazily evaluated in a getter 21217 const _request = Symbol('request') 21218 const _response = Symbol('response') 21219 const _policy = Symbol('policy') 21220 21221 class CacheEntry { 21222 constructor ({ entry, request, response, options }) { 21223 if (entry) { 21224 this.key = entry.key 21225 this.entry = entry 21226 // previous versions of this module didn't write an explicit timestamp in 21227 // the metadata, so fall back to the entry's timestamp. we can't use the 21228 // entry timestamp to determine staleness because cacache will update it 21229 // when it verifies its data 21230 this.entry.metadata.time = this.entry.metadata.time || this.entry.time 21231 } else { 21232 this.key = cacheKey(request) 21233 } 21234 21235 this.options = options 21236 21237 // these properties are behind getters that lazily evaluate 21238 this[_request] = request 21239 this[_response] = response 21240 this[_policy] = null 21241 } 21242 21243 // returns a CacheEntry instance that satisfies the given request 21244 // or undefined if no existing entry satisfies 21245 static async find (request, options) { 21246 try { 21247 // compacts the index and returns an array of unique entries 21248 var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { 21249 const entryA = new CacheEntry({ entry: A, options }) 21250 const entryB = new CacheEntry({ entry: B, options }) 21251 return entryA.policy.satisfies(entryB.request) 21252 }, { 21253 validateEntry: (entry) => { 21254 // clean out entries with a buggy content-encoding value 21255 if (entry.metadata && 21256 entry.metadata.resHeaders && 21257 entry.metadata.resHeaders['content-encoding'] === null) { 21258 return false 21259 } 21260 21261 // if an integrity is null, it needs to have a status specified 21262 if (entry.integrity === null) { 21263 return !!(entry.metadata && entry.metadata.status) 21264 } 21265 21266 return true 21267 }, 21268 }) 21269 } catch (err) { 21270 // if the compact request fails, ignore the error and return 21271 return 21272 } 21273 21274 // a cache mode of 'reload' means to behave as though we have no cache 21275 // on the way to the network. return undefined to allow cacheFetch to 21276 // create a brand new request no matter what. 21277 if (options.cache === 'reload') { 21278 return 21279 } 21280 21281 // find the specific entry that satisfies the request 21282 let match 21283 for (const entry of matches) { 21284 const _entry = new CacheEntry({ 21285 entry, 21286 options, 21287 }) 21288 21289 if (_entry.policy.satisfies(request)) { 21290 match = _entry 21291 break 21292 } 21293 } 21294 21295 return match 21296 } 21297 21298 // if the user made a PUT/POST/PATCH then we invalidate our 21299 // cache for the same url by deleting the index entirely 21300 static async invalidate (request, options) { 21301 const key = cacheKey(request) 21302 try { 21303 await cacache.rm.entry(options.cachePath, key, { removeFully: true }) 21304 } catch (err) { 21305 // ignore errors 21306 } 21307 } 21308 21309 get request () { 21310 if (!this[_request]) { 21311 this[_request] = new Request(this.entry.metadata.url, { 21312 method: 'GET', 21313 headers: this.entry.metadata.reqHeaders, 21314 ...this.entry.metadata.options, 21315 }) 21316 } 21317 21318 return this[_request] 21319 } 21320 21321 get response () { 21322 if (!this[_response]) { 21323 this[_response] = new Response(null, { 21324 url: this.entry.metadata.url, 21325 counter: this.options.counter, 21326 status: this.entry.metadata.status || 200, 21327 headers: { 21328 ...this.entry.metadata.resHeaders, 21329 'content-length': this.entry.size, 21330 }, 21331 }) 21332 } 21333 21334 return this[_response] 21335 } 21336 21337 get policy () { 21338 if (!this[_policy]) { 21339 this[_policy] = new CachePolicy({ 21340 entry: this.entry, 21341 request: this.request, 21342 response: this.response, 21343 options: this.options, 21344 }) 21345 } 21346 21347 return this[_policy] 21348 } 21349 21350 // wraps the response in a pipeline that stores the data 21351 // in the cache while the user consumes it 21352 async store (status) { 21353 // if we got a status other than 200, 301, or 308, 21354 // or the CachePolicy forbid storage, append the 21355 // cache status header and return it untouched 21356 if ( 21357 this.request.method !== 'GET' || 21358 ![200, 301, 308].includes(this.response.status) || 21359 !this.policy.storable() 21360 ) { 21361 this.response.headers.set('x-local-cache-status', 'skip') 21362 return this.response 21363 } 21364 21365 const size = this.response.headers.get('content-length') 21366 const cacheOpts = { 21367 algorithms: this.options.algorithms, 21368 metadata: getMetadata(this.request, this.response, this.options), 21369 size, 21370 integrity: this.options.integrity, 21371 integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, 21372 } 21373 21374 let body = null 21375 // we only set a body if the status is a 200, redirects are 21376 // stored as metadata only 21377 if (this.response.status === 200) { 21378 let cacheWriteResolve, cacheWriteReject 21379 const cacheWritePromise = new Promise((resolve, reject) => { 21380 cacheWriteResolve = resolve 21381 cacheWriteReject = reject 21382 }).catch((err) => { 21383 body.emit('error', err) 21384 }) 21385 21386 body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ 21387 flush () { 21388 return cacheWritePromise 21389 }, 21390 })) 21391 // this is always true since if we aren't reusing the one from the remote fetch, we 21392 // are using the one from cacache 21393 body.hasIntegrityEmitter = true 21394 21395 const onResume = () => { 21396 const tee = new Minipass() 21397 const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) 21398 // re-emit the integrity and size events on our new response body so they can be reused 21399 cacheStream.on('integrity', i => body.emit('integrity', i)) 21400 cacheStream.on('size', s => body.emit('size', s)) 21401 // stick a flag on here so downstream users will know if they can expect integrity events 21402 tee.pipe(cacheStream) 21403 // TODO if the cache write fails, log a warning but return the response anyway 21404 // eslint-disable-next-line promise/catch-or-return 21405 cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) 21406 body.unshift(tee) 21407 body.unshift(this.response.body) 21408 } 21409 21410 body.once('resume', onResume) 21411 body.once('end', () => body.removeListener('resume', onResume)) 21412 } else { 21413 await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) 21414 } 21415 21416 // note: we do not set the x-local-cache-hash header because we do not know 21417 // the hash value until after the write to the cache completes, which doesn't 21418 // happen until after the response has been sent and it's too late to write 21419 // the header anyway 21420 this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) 21421 this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) 21422 this.response.headers.set('x-local-cache-mode', 'stream') 21423 this.response.headers.set('x-local-cache-status', status) 21424 this.response.headers.set('x-local-cache-time', new Date().toISOString()) 21425 const newResponse = new Response(body, { 21426 url: this.response.url, 21427 status: this.response.status, 21428 headers: this.response.headers, 21429 counter: this.options.counter, 21430 }) 21431 return newResponse 21432 } 21433 21434 // use the cached data to create a response and return it 21435 async respond (method, options, status) { 21436 let response 21437 if (method === 'HEAD' || [301, 308].includes(this.response.status)) { 21438 // if the request is a HEAD, or the response is a redirect, 21439 // then the metadata in the entry already includes everything 21440 // we need to build a response 21441 response = this.response 21442 } else { 21443 // we're responding with a full cached response, so create a body 21444 // that reads from cacache and attach it to a new Response 21445 const body = new Minipass() 21446 const headers = { ...this.policy.responseHeaders() } 21447 21448 const onResume = () => { 21449 const cacheStream = cacache.get.stream.byDigest( 21450 this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } 21451 ) 21452 cacheStream.on('error', async (err) => { 21453 cacheStream.pause() 21454 if (err.code === 'EINTEGRITY') { 21455 await cacache.rm.content( 21456 this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } 21457 ) 21458 } 21459 if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { 21460 await CacheEntry.invalidate(this.request, this.options) 21461 } 21462 body.emit('error', err) 21463 cacheStream.resume() 21464 }) 21465 // emit the integrity and size events based on our metadata so we're consistent 21466 body.emit('integrity', this.entry.integrity) 21467 body.emit('size', Number(headers['content-length'])) 21468 cacheStream.pipe(body) 21469 } 21470 21471 body.once('resume', onResume) 21472 body.once('end', () => body.removeListener('resume', onResume)) 21473 response = new Response(body, { 21474 url: this.entry.metadata.url, 21475 counter: options.counter, 21476 status: 200, 21477 headers, 21478 }) 21479 } 21480 21481 response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) 21482 response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) 21483 response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) 21484 response.headers.set('x-local-cache-mode', 'stream') 21485 response.headers.set('x-local-cache-status', status) 21486 response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) 21487 return response 21488 } 21489 21490 // use the provided request along with this cache entry to 21491 // revalidate the stored response. returns a response, either 21492 // from the cache or from the update 21493 async revalidate (request, options) { 21494 const revalidateRequest = new Request(request, { 21495 headers: this.policy.revalidationHeaders(request), 21496 }) 21497 21498 try { 21499 // NOTE: be sure to remove the headers property from the 21500 // user supplied options, since we have already defined 21501 // them on the new request object. if they're still in the 21502 // options then those will overwrite the ones from the policy 21503 var response = await remote(revalidateRequest, { 21504 ...options, 21505 headers: undefined, 21506 }) 21507 } catch (err) { 21508 // if the network fetch fails, return the stale 21509 // cached response unless it has a cache-control 21510 // of 'must-revalidate' 21511 if (!this.policy.mustRevalidate) { 21512 return this.respond(request.method, options, 'stale') 21513 } 21514 21515 throw err 21516 } 21517 21518 if (this.policy.revalidated(revalidateRequest, response)) { 21519 // we got a 304, write a new index to the cache and respond from cache 21520 const metadata = getMetadata(request, response, options) 21521 // 304 responses do not include headers that are specific to the response data 21522 // since they do not include a body, so we copy values for headers that were 21523 // in the old cache entry to the new one, if the new metadata does not already 21524 // include that header 21525 for (const name of KEEP_RESPONSE_HEADERS) { 21526 if ( 21527 !hasOwnProperty(metadata.resHeaders, name) && 21528 hasOwnProperty(this.entry.metadata.resHeaders, name) 21529 ) { 21530 metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] 21531 } 21532 } 21533 21534 for (const name of options.cacheAdditionalHeaders) { 21535 const inMeta = hasOwnProperty(metadata.resHeaders, name) 21536 const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) 21537 const inPolicy = hasOwnProperty(this.policy.response.headers, name) 21538 21539 // if the header is in the existing entry, but it is not in the metadata 21540 // then we need to write it to the metadata as this will refresh the on-disk cache 21541 if (!inMeta && inEntry) { 21542 metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] 21543 } 21544 // if the header is in the metadata, but not in the policy, then we need to set 21545 // it in the policy so that it's included in the immediate response. future 21546 // responses will load a new cache entry, so we don't need to change that 21547 if (!inPolicy && inMeta) { 21548 this.policy.response.headers[name] = metadata.resHeaders[name] 21549 } 21550 } 21551 21552 try { 21553 await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { 21554 size: this.entry.size, 21555 metadata, 21556 }) 21557 } catch (err) { 21558 // if updating the cache index fails, we ignore it and 21559 // respond anyway 21560 } 21561 return this.respond(request.method, options, 'revalidated') 21562 } 21563 21564 // if we got a modified response, create a new entry based on it 21565 const newEntry = new CacheEntry({ 21566 request, 21567 response, 21568 options, 21569 }) 21570 21571 // respond with the new entry while writing it to the cache 21572 return newEntry.store('updated') 21573 } 21574 } 21575 21576 module.exports = CacheEntry 21577 21578 21579 /***/ }), 21580 21581 /***/ 3104: 21582 /***/ ((module) => { 21583 21584 class NotCachedError extends Error { 21585 constructor (url) { 21586 /* eslint-disable-next-line max-len */ 21587 super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) 21588 this.code = 'ENOTCACHED' 21589 } 21590 } 21591 21592 module.exports = { 21593 NotCachedError, 21594 } 21595 21596 21597 /***/ }), 21598 21599 /***/ 3189: 21600 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21601 21602 const { NotCachedError } = __nccwpck_require__(3104) 21603 const CacheEntry = __nccwpck_require__(7943) 21604 const remote = __nccwpck_require__(2619) 21605 21606 // do whatever is necessary to get a Response and return it 21607 const cacheFetch = async (request, options) => { 21608 // try to find a cached entry that satisfies this request 21609 const entry = await CacheEntry.find(request, options) 21610 if (!entry) { 21611 // no cached result, if the cache mode is 'only-if-cached' that's a failure 21612 if (options.cache === 'only-if-cached') { 21613 throw new NotCachedError(request.url) 21614 } 21615 21616 // otherwise, we make a request, store it and return it 21617 const response = await remote(request, options) 21618 const newEntry = new CacheEntry({ request, response, options }) 21619 return newEntry.store('miss') 21620 } 21621 21622 // we have a cached response that satisfies this request, however if the cache 21623 // mode is 'no-cache' then we send the revalidation request no matter what 21624 if (options.cache === 'no-cache') { 21625 return entry.revalidate(request, options) 21626 } 21627 21628 // if the cached entry is not stale, or if the cache mode is 'force-cache' or 21629 // 'only-if-cached' we can respond with the cached entry. set the status 21630 // based on the result of needsRevalidation and respond 21631 const _needsRevalidation = entry.policy.needsRevalidation(request) 21632 if (options.cache === 'force-cache' || 21633 options.cache === 'only-if-cached' || 21634 !_needsRevalidation) { 21635 return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') 21636 } 21637 21638 // if we got here, the cache entry is stale so revalidate it 21639 return entry.revalidate(request, options) 21640 } 21641 21642 cacheFetch.invalidate = async (request, options) => { 21643 if (!options.cachePath) { 21644 return 21645 } 21646 21647 return CacheEntry.invalidate(request, options) 21648 } 21649 21650 module.exports = cacheFetch 21651 21652 21653 /***/ }), 21654 21655 /***/ 2147: 21656 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21657 21658 const { URL, format } = __nccwpck_require__(7310) 21659 21660 // options passed to url.format() when generating a key 21661 const formatOptions = { 21662 auth: false, 21663 fragment: false, 21664 search: true, 21665 unicode: false, 21666 } 21667 21668 // returns a string to be used as the cache key for the Request 21669 const cacheKey = (request) => { 21670 const parsed = new URL(request.url) 21671 return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` 21672 } 21673 21674 module.exports = cacheKey 21675 21676 21677 /***/ }), 21678 21679 /***/ 7986: 21680 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21681 21682 const CacheSemantics = __nccwpck_require__(1002) 21683 const Negotiator = __nccwpck_require__(5385) 21684 const ssri = __nccwpck_require__(4406) 21685 21686 // options passed to http-cache-semantics constructor 21687 const policyOptions = { 21688 shared: false, 21689 ignoreCargoCult: true, 21690 } 21691 21692 // a fake empty response, used when only testing the 21693 // request for storability 21694 const emptyResponse = { status: 200, headers: {} } 21695 21696 // returns a plain object representation of the Request 21697 const requestObject = (request) => { 21698 const _obj = { 21699 method: request.method, 21700 url: request.url, 21701 headers: {}, 21702 compress: request.compress, 21703 } 21704 21705 request.headers.forEach((value, key) => { 21706 _obj.headers[key] = value 21707 }) 21708 21709 return _obj 21710 } 21711 21712 // returns a plain object representation of the Response 21713 const responseObject = (response) => { 21714 const _obj = { 21715 status: response.status, 21716 headers: {}, 21717 } 21718 21719 response.headers.forEach((value, key) => { 21720 _obj.headers[key] = value 21721 }) 21722 21723 return _obj 21724 } 21725 21726 class CachePolicy { 21727 constructor ({ entry, request, response, options }) { 21728 this.entry = entry 21729 this.request = requestObject(request) 21730 this.response = responseObject(response) 21731 this.options = options 21732 this.policy = new CacheSemantics(this.request, this.response, policyOptions) 21733 21734 if (this.entry) { 21735 // if we have an entry, copy the timestamp to the _responseTime 21736 // this is necessary because the CacheSemantics constructor forces 21737 // the value to Date.now() which means a policy created from a 21738 // cache entry is likely to always identify itself as stale 21739 this.policy._responseTime = this.entry.metadata.time 21740 } 21741 } 21742 21743 // static method to quickly determine if a request alone is storable 21744 static storable (request, options) { 21745 // no cachePath means no caching 21746 if (!options.cachePath) { 21747 return false 21748 } 21749 21750 // user explicitly asked not to cache 21751 if (options.cache === 'no-store') { 21752 return false 21753 } 21754 21755 // we only cache GET and HEAD requests 21756 if (!['GET', 'HEAD'].includes(request.method)) { 21757 return false 21758 } 21759 21760 // otherwise, let http-cache-semantics make the decision 21761 // based on the request's headers 21762 const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) 21763 return policy.storable() 21764 } 21765 21766 // returns true if the policy satisfies the request 21767 satisfies (request) { 21768 const _req = requestObject(request) 21769 if (this.request.headers.host !== _req.headers.host) { 21770 return false 21771 } 21772 21773 if (this.request.compress !== _req.compress) { 21774 return false 21775 } 21776 21777 const negotiatorA = new Negotiator(this.request) 21778 const negotiatorB = new Negotiator(_req) 21779 21780 if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { 21781 return false 21782 } 21783 21784 if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { 21785 return false 21786 } 21787 21788 if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { 21789 return false 21790 } 21791 21792 if (this.options.integrity) { 21793 return ssri.parse(this.options.integrity).match(this.entry.integrity) 21794 } 21795 21796 return true 21797 } 21798 21799 // returns true if the request and response allow caching 21800 storable () { 21801 return this.policy.storable() 21802 } 21803 21804 // NOTE: this is a hack to avoid parsing the cache-control 21805 // header ourselves, it returns true if the response's 21806 // cache-control contains must-revalidate 21807 get mustRevalidate () { 21808 return !!this.policy._rescc['must-revalidate'] 21809 } 21810 21811 // returns true if the cached response requires revalidation 21812 // for the given request 21813 needsRevalidation (request) { 21814 const _req = requestObject(request) 21815 // force method to GET because we only cache GETs 21816 // but can serve a HEAD from a cached GET 21817 _req.method = 'GET' 21818 return !this.policy.satisfiesWithoutRevalidation(_req) 21819 } 21820 21821 responseHeaders () { 21822 return this.policy.responseHeaders() 21823 } 21824 21825 // returns a new object containing the appropriate headers 21826 // to send a revalidation request 21827 revalidationHeaders (request) { 21828 const _req = requestObject(request) 21829 return this.policy.revalidationHeaders(_req) 21830 } 21831 21832 // returns true if the request/response was revalidated 21833 // successfully. returns false if a new response was received 21834 revalidated (request, response) { 21835 const _req = requestObject(request) 21836 const _res = responseObject(response) 21837 const policy = this.policy.revalidatedPolicy(_req, _res) 21838 return !policy.modified 21839 } 21840 } 21841 21842 module.exports = CachePolicy 21843 21844 21845 /***/ }), 21846 21847 /***/ 1371: 21848 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21849 21850 "use strict"; 21851 21852 21853 const { FetchError, Request, isRedirect } = __nccwpck_require__(8998) 21854 const url = __nccwpck_require__(7310) 21855 21856 const CachePolicy = __nccwpck_require__(7986) 21857 const cache = __nccwpck_require__(3189) 21858 const remote = __nccwpck_require__(2619) 21859 21860 // given a Request, a Response and user options 21861 // return true if the response is a redirect that 21862 // can be followed. we throw errors that will result 21863 // in the fetch being rejected if the redirect is 21864 // possible but invalid for some reason 21865 const canFollowRedirect = (request, response, options) => { 21866 if (!isRedirect(response.status)) { 21867 return false 21868 } 21869 21870 if (options.redirect === 'manual') { 21871 return false 21872 } 21873 21874 if (options.redirect === 'error') { 21875 throw new FetchError(`redirect mode is set to error: ${request.url}`, 21876 'no-redirect', { code: 'ENOREDIRECT' }) 21877 } 21878 21879 if (!response.headers.has('location')) { 21880 throw new FetchError(`redirect location header missing for: ${request.url}`, 21881 'no-location', { code: 'EINVALIDREDIRECT' }) 21882 } 21883 21884 if (request.counter >= request.follow) { 21885 throw new FetchError(`maximum redirect reached at: ${request.url}`, 21886 'max-redirect', { code: 'EMAXREDIRECT' }) 21887 } 21888 21889 return true 21890 } 21891 21892 // given a Request, a Response, and the user's options return an object 21893 // with a new Request and a new options object that will be used for 21894 // following the redirect 21895 const getRedirect = (request, response, options) => { 21896 const _opts = { ...options } 21897 const location = response.headers.get('location') 21898 const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) 21899 // Comment below is used under the following license: 21900 /** 21901 * @license 21902 * Copyright (c) 2010-2012 Mikeal Rogers 21903 * Licensed under the Apache License, Version 2.0 (the "License"); 21904 * you may not use this file except in compliance with the License. 21905 * You may obtain a copy of the License at 21906 * http://www.apache.org/licenses/LICENSE-2.0 21907 * Unless required by applicable law or agreed to in writing, 21908 * software distributed under the License is distributed on an "AS 21909 * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 21910 * express or implied. See the License for the specific language 21911 * governing permissions and limitations under the License. 21912 */ 21913 21914 // Remove authorization if changing hostnames (but not if just 21915 // changing ports or protocols). This matches the behavior of request: 21916 // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 21917 if (new url.URL(request.url).hostname !== redirectUrl.hostname) { 21918 request.headers.delete('authorization') 21919 request.headers.delete('cookie') 21920 } 21921 21922 // for POST request with 301/302 response, or any request with 303 response, 21923 // use GET when following redirect 21924 if ( 21925 response.status === 303 || 21926 (request.method === 'POST' && [301, 302].includes(response.status)) 21927 ) { 21928 _opts.method = 'GET' 21929 _opts.body = null 21930 request.headers.delete('content-length') 21931 } 21932 21933 _opts.headers = {} 21934 request.headers.forEach((value, key) => { 21935 _opts.headers[key] = value 21936 }) 21937 21938 _opts.counter = ++request.counter 21939 const redirectReq = new Request(url.format(redirectUrl), _opts) 21940 return { 21941 request: redirectReq, 21942 options: _opts, 21943 } 21944 } 21945 21946 const fetch = async (request, options) => { 21947 const response = CachePolicy.storable(request, options) 21948 ? await cache(request, options) 21949 : await remote(request, options) 21950 21951 // if the request wasn't a GET or HEAD, and the response 21952 // status is between 200 and 399 inclusive, invalidate the 21953 // request url 21954 if (!['GET', 'HEAD'].includes(request.method) && 21955 response.status >= 200 && 21956 response.status <= 399) { 21957 await cache.invalidate(request, options) 21958 } 21959 21960 if (!canFollowRedirect(request, response, options)) { 21961 return response 21962 } 21963 21964 const redirect = getRedirect(request, response, options) 21965 return fetch(redirect.request, redirect.options) 21966 } 21967 21968 module.exports = fetch 21969 21970 21971 /***/ }), 21972 21973 /***/ 9525: 21974 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 21975 21976 const { FetchError, Headers, Request, Response } = __nccwpck_require__(8998) 21977 21978 const configureOptions = __nccwpck_require__(5530) 21979 const fetch = __nccwpck_require__(1371) 21980 21981 const makeFetchHappen = (url, opts) => { 21982 const options = configureOptions(opts) 21983 21984 const request = new Request(url, options) 21985 return fetch(request, options) 21986 } 21987 21988 makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { 21989 if (typeof defaultUrl === 'object') { 21990 defaultOptions = defaultUrl 21991 defaultUrl = null 21992 } 21993 21994 const defaultedFetch = (url, options = {}) => { 21995 const finalUrl = url || defaultUrl 21996 const finalOptions = { 21997 ...defaultOptions, 21998 ...options, 21999 headers: { 22000 ...defaultOptions.headers, 22001 ...options.headers, 22002 }, 22003 } 22004 return wrappedFetch(finalUrl, finalOptions) 22005 } 22006 22007 defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => 22008 makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) 22009 return defaultedFetch 22010 } 22011 22012 module.exports = makeFetchHappen 22013 module.exports.FetchError = FetchError 22014 module.exports.Headers = Headers 22015 module.exports.Request = Request 22016 module.exports.Response = Response 22017 22018 22019 /***/ }), 22020 22021 /***/ 5530: 22022 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22023 22024 const dns = __nccwpck_require__(9523) 22025 22026 const conditionalHeaders = [ 22027 'if-modified-since', 22028 'if-none-match', 22029 'if-unmodified-since', 22030 'if-match', 22031 'if-range', 22032 ] 22033 22034 const configureOptions = (opts) => { 22035 const { strictSSL, ...options } = { ...opts } 22036 options.method = options.method ? options.method.toUpperCase() : 'GET' 22037 options.rejectUnauthorized = strictSSL !== false 22038 22039 if (!options.retry) { 22040 options.retry = { retries: 0 } 22041 } else if (typeof options.retry === 'string') { 22042 const retries = parseInt(options.retry, 10) 22043 if (isFinite(retries)) { 22044 options.retry = { retries } 22045 } else { 22046 options.retry = { retries: 0 } 22047 } 22048 } else if (typeof options.retry === 'number') { 22049 options.retry = { retries: options.retry } 22050 } else { 22051 options.retry = { retries: 0, ...options.retry } 22052 } 22053 22054 options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } 22055 22056 options.cache = options.cache || 'default' 22057 if (options.cache === 'default') { 22058 const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { 22059 return conditionalHeaders.includes(name.toLowerCase()) 22060 }) 22061 if (hasConditionalHeader) { 22062 options.cache = 'no-store' 22063 } 22064 } 22065 22066 options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] 22067 22068 // cacheManager is deprecated, but if it's set and 22069 // cachePath is not we should copy it to the new field 22070 if (options.cacheManager && !options.cachePath) { 22071 options.cachePath = options.cacheManager 22072 } 22073 22074 return options 22075 } 22076 22077 module.exports = configureOptions 22078 22079 22080 /***/ }), 22081 22082 /***/ 1064: 22083 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22084 22085 "use strict"; 22086 22087 22088 const MinipassPipeline = __nccwpck_require__(9891) 22089 22090 class CachingMinipassPipeline extends MinipassPipeline { 22091 #events = [] 22092 #data = new Map() 22093 22094 constructor (opts, ...streams) { 22095 // CRITICAL: do NOT pass the streams to the call to super(), this will start 22096 // the flow of data and potentially cause the events we need to catch to emit 22097 // before we've finished our own setup. instead we call super() with no args, 22098 // finish our setup, and then push the streams into ourselves to start the 22099 // data flow 22100 super() 22101 this.#events = opts.events 22102 22103 /* istanbul ignore next - coverage disabled because this is pointless to test here */ 22104 if (streams.length) { 22105 this.push(...streams) 22106 } 22107 } 22108 22109 on (event, handler) { 22110 if (this.#events.includes(event) && this.#data.has(event)) { 22111 return handler(...this.#data.get(event)) 22112 } 22113 22114 return super.on(event, handler) 22115 } 22116 22117 emit (event, ...data) { 22118 if (this.#events.includes(event)) { 22119 this.#data.set(event, data) 22120 } 22121 22122 return super.emit(event, ...data) 22123 } 22124 } 22125 22126 module.exports = CachingMinipassPipeline 22127 22128 22129 /***/ }), 22130 22131 /***/ 2619: 22132 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22133 22134 const { Minipass } = __nccwpck_require__(4968) 22135 const fetch = __nccwpck_require__(8998) 22136 const promiseRetry = __nccwpck_require__(4742) 22137 const ssri = __nccwpck_require__(4406) 22138 const { log } = __nccwpck_require__(6528) 22139 22140 const CachingMinipassPipeline = __nccwpck_require__(1064) 22141 const { getAgent } = __nccwpck_require__(9907) 22142 const pkg = __nccwpck_require__(557) 22143 22144 const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` 22145 22146 const RETRY_ERRORS = [ 22147 'ECONNRESET', // remote socket closed on us 22148 'ECONNREFUSED', // remote host refused to open connection 22149 'EADDRINUSE', // failed to bind to a local port (proxy?) 22150 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW 22151 // from @npmcli/agent 22152 'ECONNECTIONTIMEOUT', 22153 'EIDLETIMEOUT', 22154 'ERESPONSETIMEOUT', 22155 'ETRANSFERTIMEOUT', 22156 // Known codes we do NOT retry on: 22157 // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) 22158 // EINVALIDPROXY // invalid protocol from @npmcli/agent 22159 // EINVALIDRESPONSE // invalid status code from @npmcli/agent 22160 ] 22161 22162 const RETRY_TYPES = [ 22163 'request-timeout', 22164 ] 22165 22166 // make a request directly to the remote source, 22167 // retrying certain classes of errors as well as 22168 // following redirects (through the cache if necessary) 22169 // and verifying response integrity 22170 const remoteFetch = (request, options) => { 22171 const agent = getAgent(request.url, options) 22172 if (!request.headers.has('connection')) { 22173 request.headers.set('connection', agent ? 'keep-alive' : 'close') 22174 } 22175 22176 if (!request.headers.has('user-agent')) { 22177 request.headers.set('user-agent', USER_AGENT) 22178 } 22179 22180 // keep our own options since we're overriding the agent 22181 // and the redirect mode 22182 const _opts = { 22183 ...options, 22184 agent, 22185 redirect: 'manual', 22186 } 22187 22188 return promiseRetry(async (retryHandler, attemptNum) => { 22189 const req = new fetch.Request(request, _opts) 22190 try { 22191 let res = await fetch(req, _opts) 22192 if (_opts.integrity && res.status === 200) { 22193 // we got a 200 response and the user has specified an expected 22194 // integrity value, so wrap the response in an ssri stream to verify it 22195 const integrityStream = ssri.integrityStream({ 22196 algorithms: _opts.algorithms, 22197 integrity: _opts.integrity, 22198 size: _opts.size, 22199 }) 22200 const pipeline = new CachingMinipassPipeline({ 22201 events: ['integrity', 'size'], 22202 }, res.body, integrityStream) 22203 // we also propagate the integrity and size events out to the pipeline so we can use 22204 // this new response body as an integrityEmitter for cacache 22205 integrityStream.on('integrity', i => pipeline.emit('integrity', i)) 22206 integrityStream.on('size', s => pipeline.emit('size', s)) 22207 res = new fetch.Response(pipeline, res) 22208 // set an explicit flag so we know if our response body will emit integrity and size 22209 res.body.hasIntegrityEmitter = true 22210 } 22211 22212 res.headers.set('x-fetch-attempts', attemptNum) 22213 22214 // do not retry POST requests, or requests with a streaming body 22215 // do retry requests with a 408, 420, 429 or 500+ status in the response 22216 const isStream = Minipass.isStream(req.body) 22217 const isRetriable = req.method !== 'POST' && 22218 !isStream && 22219 ([408, 420, 429].includes(res.status) || res.status >= 500) 22220 22221 if (isRetriable) { 22222 if (typeof options.onRetry === 'function') { 22223 options.onRetry(res) 22224 } 22225 22226 /* eslint-disable-next-line max-len */ 22227 log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) 22228 return retryHandler(res) 22229 } 22230 22231 return res 22232 } catch (err) { 22233 const code = (err.code === 'EPROMISERETRY') 22234 ? err.retried.code 22235 : err.code 22236 22237 // err.retried will be the thing that was thrown from above 22238 // if it's a response, we just got a bad status code and we 22239 // can re-throw to allow the retry 22240 const isRetryError = err.retried instanceof fetch.Response || 22241 (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) 22242 22243 if (req.method === 'POST' || isRetryError) { 22244 throw err 22245 } 22246 22247 if (typeof options.onRetry === 'function') { 22248 options.onRetry(err) 22249 } 22250 22251 log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) 22252 return retryHandler(err) 22253 } 22254 }, options.retry).catch((err) => { 22255 // don't reject for http errors, just return them 22256 if (err.status >= 400 && err.type !== 'system') { 22257 return err 22258 } 22259 22260 throw err 22261 }) 22262 } 22263 22264 module.exports = remoteFetch 22265 22266 22267 /***/ }), 22268 22269 /***/ 4658: 22270 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22271 22272 const { Minipass } = __nccwpck_require__(4968) 22273 const _data = Symbol('_data') 22274 const _length = Symbol('_length') 22275 class Collect extends Minipass { 22276 constructor (options) { 22277 super(options) 22278 this[_data] = [] 22279 this[_length] = 0 22280 } 22281 write (chunk, encoding, cb) { 22282 if (typeof encoding === 'function') 22283 cb = encoding, encoding = 'utf8' 22284 22285 if (!encoding) 22286 encoding = 'utf8' 22287 22288 const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) 22289 this[_data].push(c) 22290 this[_length] += c.length 22291 if (cb) 22292 cb() 22293 return true 22294 } 22295 end (chunk, encoding, cb) { 22296 if (typeof chunk === 'function') 22297 cb = chunk, chunk = null 22298 if (typeof encoding === 'function') 22299 cb = encoding, encoding = 'utf8' 22300 if (chunk) 22301 this.write(chunk, encoding) 22302 const result = Buffer.concat(this[_data], this[_length]) 22303 super.write(result) 22304 return super.end(cb) 22305 } 22306 } 22307 module.exports = Collect 22308 22309 // it would be possible to DRY this a bit by doing something like 22310 // this.collector = new Collect() and listening on its data event, 22311 // but it's not much code, and we may as well save the extra obj 22312 class CollectPassThrough extends Minipass { 22313 constructor (options) { 22314 super(options) 22315 this[_data] = [] 22316 this[_length] = 0 22317 } 22318 write (chunk, encoding, cb) { 22319 if (typeof encoding === 'function') 22320 cb = encoding, encoding = 'utf8' 22321 22322 if (!encoding) 22323 encoding = 'utf8' 22324 22325 const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) 22326 this[_data].push(c) 22327 this[_length] += c.length 22328 return super.write(chunk, encoding, cb) 22329 } 22330 end (chunk, encoding, cb) { 22331 if (typeof chunk === 'function') 22332 cb = chunk, chunk = null 22333 if (typeof encoding === 'function') 22334 cb = encoding, encoding = 'utf8' 22335 if (chunk) 22336 this.write(chunk, encoding) 22337 const result = Buffer.concat(this[_data], this[_length]) 22338 this.emit('collect', result) 22339 return super.end(cb) 22340 } 22341 } 22342 module.exports.PassThrough = CollectPassThrough 22343 22344 22345 /***/ }), 22346 22347 /***/ 1078: 22348 /***/ ((module) => { 22349 22350 "use strict"; 22351 22352 class AbortError extends Error { 22353 constructor (message) { 22354 super(message) 22355 this.code = 'FETCH_ABORTED' 22356 this.type = 'aborted' 22357 Error.captureStackTrace(this, this.constructor) 22358 } 22359 22360 get name () { 22361 return 'AbortError' 22362 } 22363 22364 // don't allow name to be overridden, but don't throw either 22365 set name (s) {} 22366 } 22367 module.exports = AbortError 22368 22369 22370 /***/ }), 22371 22372 /***/ 7911: 22373 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22374 22375 "use strict"; 22376 22377 const { Minipass } = __nccwpck_require__(4968) 22378 const TYPE = Symbol('type') 22379 const BUFFER = Symbol('buffer') 22380 22381 class Blob { 22382 constructor (blobParts, options) { 22383 this[TYPE] = '' 22384 22385 const buffers = [] 22386 let size = 0 22387 22388 if (blobParts) { 22389 const a = blobParts 22390 const length = Number(a.length) 22391 for (let i = 0; i < length; i++) { 22392 const element = a[i] 22393 const buffer = element instanceof Buffer ? element 22394 : ArrayBuffer.isView(element) 22395 ? Buffer.from(element.buffer, element.byteOffset, element.byteLength) 22396 : element instanceof ArrayBuffer ? Buffer.from(element) 22397 : element instanceof Blob ? element[BUFFER] 22398 : typeof element === 'string' ? Buffer.from(element) 22399 : Buffer.from(String(element)) 22400 size += buffer.length 22401 buffers.push(buffer) 22402 } 22403 } 22404 22405 this[BUFFER] = Buffer.concat(buffers, size) 22406 22407 const type = options && options.type !== undefined 22408 && String(options.type).toLowerCase() 22409 if (type && !/[^\u0020-\u007E]/.test(type)) { 22410 this[TYPE] = type 22411 } 22412 } 22413 22414 get size () { 22415 return this[BUFFER].length 22416 } 22417 22418 get type () { 22419 return this[TYPE] 22420 } 22421 22422 text () { 22423 return Promise.resolve(this[BUFFER].toString()) 22424 } 22425 22426 arrayBuffer () { 22427 const buf = this[BUFFER] 22428 const off = buf.byteOffset 22429 const len = buf.byteLength 22430 const ab = buf.buffer.slice(off, off + len) 22431 return Promise.resolve(ab) 22432 } 22433 22434 stream () { 22435 return new Minipass().end(this[BUFFER]) 22436 } 22437 22438 slice (start, end, type) { 22439 const size = this.size 22440 const relativeStart = start === undefined ? 0 22441 : start < 0 ? Math.max(size + start, 0) 22442 : Math.min(start, size) 22443 const relativeEnd = end === undefined ? size 22444 : end < 0 ? Math.max(size + end, 0) 22445 : Math.min(end, size) 22446 const span = Math.max(relativeEnd - relativeStart, 0) 22447 22448 const buffer = this[BUFFER] 22449 const slicedBuffer = buffer.slice( 22450 relativeStart, 22451 relativeStart + span 22452 ) 22453 const blob = new Blob([], { type }) 22454 blob[BUFFER] = slicedBuffer 22455 return blob 22456 } 22457 22458 get [Symbol.toStringTag] () { 22459 return 'Blob' 22460 } 22461 22462 static get BUFFER () { 22463 return BUFFER 22464 } 22465 } 22466 22467 Object.defineProperties(Blob.prototype, { 22468 size: { enumerable: true }, 22469 type: { enumerable: true }, 22470 }) 22471 22472 module.exports = Blob 22473 22474 22475 /***/ }), 22476 22477 /***/ 7223: 22478 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 22479 22480 "use strict"; 22481 22482 const { Minipass } = __nccwpck_require__(4968) 22483 const MinipassSized = __nccwpck_require__(5952) 22484 22485 const Blob = __nccwpck_require__(7911) 22486 const { BUFFER } = Blob 22487 const FetchError = __nccwpck_require__(2899) 22488 22489 // optional dependency on 'encoding' 22490 let convert 22491 try { 22492 convert = (__nccwpck_require__(3975).convert) 22493 } catch (e) { 22494 // defer error until textConverted is called 22495 } 22496 22497 const INTERNALS = Symbol('Body internals') 22498 const CONSUME_BODY = Symbol('consumeBody') 22499 22500 class Body { 22501 constructor (bodyArg, options = {}) { 22502 const { size = 0, timeout = 0 } = options 22503 const body = bodyArg === undefined || bodyArg === null ? null 22504 : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString()) 22505 : isBlob(bodyArg) ? bodyArg 22506 : Buffer.isBuffer(bodyArg) ? bodyArg 22507 : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]' 22508 ? Buffer.from(bodyArg) 22509 : ArrayBuffer.isView(bodyArg) 22510 ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength) 22511 : Minipass.isStream(bodyArg) ? bodyArg 22512 : Buffer.from(String(bodyArg)) 22513 22514 this[INTERNALS] = { 22515 body, 22516 disturbed: false, 22517 error: null, 22518 } 22519 22520 this.size = size 22521 this.timeout = timeout 22522 22523 if (Minipass.isStream(body)) { 22524 body.on('error', er => { 22525 const error = er.name === 'AbortError' ? er 22526 : new FetchError(`Invalid response while trying to fetch ${ 22527 this.url}: ${er.message}`, 'system', er) 22528 this[INTERNALS].error = error 22529 }) 22530 } 22531 } 22532 22533 get body () { 22534 return this[INTERNALS].body 22535 } 22536 22537 get bodyUsed () { 22538 return this[INTERNALS].disturbed 22539 } 22540 22541 arrayBuffer () { 22542 return this[CONSUME_BODY]().then(buf => 22543 buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)) 22544 } 22545 22546 blob () { 22547 const ct = this.headers && this.headers.get('content-type') || '' 22548 return this[CONSUME_BODY]().then(buf => Object.assign( 22549 new Blob([], { type: ct.toLowerCase() }), 22550 { [BUFFER]: buf } 22551 )) 22552 } 22553 22554 async json () { 22555 const buf = await this[CONSUME_BODY]() 22556 try { 22557 return JSON.parse(buf.toString()) 22558 } catch (er) { 22559 throw new FetchError( 22560 `invalid json response body at ${this.url} reason: ${er.message}`, 22561 'invalid-json' 22562 ) 22563 } 22564 } 22565 22566 text () { 22567 return this[CONSUME_BODY]().then(buf => buf.toString()) 22568 } 22569 22570 buffer () { 22571 return this[CONSUME_BODY]() 22572 } 22573 22574 textConverted () { 22575 return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers)) 22576 } 22577 22578 [CONSUME_BODY] () { 22579 if (this[INTERNALS].disturbed) { 22580 return Promise.reject(new TypeError(`body used already for: ${ 22581 this.url}`)) 22582 } 22583 22584 this[INTERNALS].disturbed = true 22585 22586 if (this[INTERNALS].error) { 22587 return Promise.reject(this[INTERNALS].error) 22588 } 22589 22590 // body is null 22591 if (this.body === null) { 22592 return Promise.resolve(Buffer.alloc(0)) 22593 } 22594 22595 if (Buffer.isBuffer(this.body)) { 22596 return Promise.resolve(this.body) 22597 } 22598 22599 const upstream = isBlob(this.body) ? this.body.stream() : this.body 22600 22601 /* istanbul ignore if: should never happen */ 22602 if (!Minipass.isStream(upstream)) { 22603 return Promise.resolve(Buffer.alloc(0)) 22604 } 22605 22606 const stream = this.size && upstream instanceof MinipassSized ? upstream 22607 : !this.size && upstream instanceof Minipass && 22608 !(upstream instanceof MinipassSized) ? upstream 22609 : this.size ? new MinipassSized({ size: this.size }) 22610 : new Minipass() 22611 22612 // allow timeout on slow response body, but only if the stream is still writable. this 22613 // makes the timeout center on the socket stream from lib/index.js rather than the 22614 // intermediary minipass stream we create to receive the data 22615 const resTimeout = this.timeout && stream.writable ? setTimeout(() => { 22616 stream.emit('error', new FetchError( 22617 `Response timeout while trying to fetch ${ 22618 this.url} (over ${this.timeout}ms)`, 'body-timeout')) 22619 }, this.timeout) : null 22620 22621 // do not keep the process open just for this timeout, even 22622 // though we expect it'll get cleared eventually. 22623 if (resTimeout && resTimeout.unref) { 22624 resTimeout.unref() 22625 } 22626 22627 // do the pipe in the promise, because the pipe() can send too much 22628 // data through right away and upset the MP Sized object 22629 return new Promise((resolve, reject) => { 22630 // if the stream is some other kind of stream, then pipe through a MP 22631 // so we can collect it more easily. 22632 if (stream !== upstream) { 22633 upstream.on('error', er => stream.emit('error', er)) 22634 upstream.pipe(stream) 22635 } 22636 resolve() 22637 }).then(() => stream.concat()).then(buf => { 22638 clearTimeout(resTimeout) 22639 return buf 22640 }).catch(er => { 22641 clearTimeout(resTimeout) 22642 // request was aborted, reject with this Error 22643 if (er.name === 'AbortError' || er.name === 'FetchError') { 22644 throw er 22645 } else if (er.name === 'RangeError') { 22646 throw new FetchError(`Could not create Buffer from response body for ${ 22647 this.url}: ${er.message}`, 'system', er) 22648 } else { 22649 // other errors, such as incorrect content-encoding or content-length 22650 throw new FetchError(`Invalid response body while trying to fetch ${ 22651 this.url}: ${er.message}`, 'system', er) 22652 } 22653 }) 22654 } 22655 22656 static clone (instance) { 22657 if (instance.bodyUsed) { 22658 throw new Error('cannot clone body after it is used') 22659 } 22660 22661 const body = instance.body 22662 22663 // check that body is a stream and not form-data object 22664 // NB: can't clone the form-data object without having it as a dependency 22665 if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') { 22666 // create a dedicated tee stream so that we don't lose data 22667 // potentially sitting in the body stream's buffer by writing it 22668 // immediately to p1 and not having it for p2. 22669 const tee = new Minipass() 22670 const p1 = new Minipass() 22671 const p2 = new Minipass() 22672 tee.on('error', er => { 22673 p1.emit('error', er) 22674 p2.emit('error', er) 22675 }) 22676 body.on('error', er => tee.emit('error', er)) 22677 tee.pipe(p1) 22678 tee.pipe(p2) 22679 body.pipe(tee) 22680 // set instance body to one fork, return the other 22681 instance[INTERNALS].body = p1 22682 return p2 22683 } else { 22684 return instance.body 22685 } 22686 } 22687 22688 static extractContentType (body) { 22689 return body === null || body === undefined ? null 22690 : typeof body === 'string' ? 'text/plain;charset=UTF-8' 22691 : isURLSearchParams(body) 22692 ? 'application/x-www-form-urlencoded;charset=UTF-8' 22693 : isBlob(body) ? body.type || null 22694 : Buffer.isBuffer(body) ? null 22695 : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null 22696 : ArrayBuffer.isView(body) ? null 22697 : typeof body.getBoundary === 'function' 22698 ? `multipart/form-data;boundary=${body.getBoundary()}` 22699 : Minipass.isStream(body) ? null 22700 : 'text/plain;charset=UTF-8' 22701 } 22702 22703 static getTotalBytes (instance) { 22704 const { body } = instance 22705 return (body === null || body === undefined) ? 0 22706 : isBlob(body) ? body.size 22707 : Buffer.isBuffer(body) ? body.length 22708 : body && typeof body.getLengthSync === 'function' && ( 22709 // detect form data input from form-data module 22710 body._lengthRetrievers && 22711 /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x 22712 body.hasKnownLength && body.hasKnownLength()) // 2.x 22713 ? body.getLengthSync() 22714 : null 22715 } 22716 22717 static writeToStream (dest, instance) { 22718 const { body } = instance 22719 22720 if (body === null || body === undefined) { 22721 dest.end() 22722 } else if (Buffer.isBuffer(body) || typeof body === 'string') { 22723 dest.end(body) 22724 } else { 22725 // body is stream or blob 22726 const stream = isBlob(body) ? body.stream() : body 22727 stream.on('error', er => dest.emit('error', er)).pipe(dest) 22728 } 22729 22730 return dest 22731 } 22732 } 22733 22734 Object.defineProperties(Body.prototype, { 22735 body: { enumerable: true }, 22736 bodyUsed: { enumerable: true }, 22737 arrayBuffer: { enumerable: true }, 22738 blob: { enumerable: true }, 22739 json: { enumerable: true }, 22740 text: { enumerable: true }, 22741 }) 22742 22743 const isURLSearchParams = obj => 22744 // Duck-typing as a necessary condition. 22745 (typeof obj !== 'object' || 22746 typeof obj.append !== 'function' || 22747 typeof obj.delete !== 'function' || 22748 typeof obj.get !== 'function' || 22749 typeof obj.getAll !== 'function' || 22750 typeof obj.has !== 'function' || 22751 typeof obj.set !== 'function') ? false 22752 // Brand-checking and more duck-typing as optional condition. 22753 : obj.constructor.name === 'URLSearchParams' || 22754 Object.prototype.toString.call(obj) === '[object URLSearchParams]' || 22755 typeof obj.sort === 'function' 22756 22757 const isBlob = obj => 22758 typeof obj === 'object' && 22759 typeof obj.arrayBuffer === 'function' && 22760 typeof obj.type === 'string' && 22761 typeof obj.stream === 'function' && 22762 typeof obj.constructor === 'function' && 22763 typeof obj.constructor.name === 'string' && 22764 /^(Blob|File)$/.test(obj.constructor.name) && 22765 /^(Blob|File)$/.test(obj[Symbol.toStringTag]) 22766 22767 const convertBody = (buffer, headers) => { 22768 /* istanbul ignore if */ 22769 if (typeof convert !== 'function') { 22770 throw new Error('The package `encoding` must be installed to use the textConverted() function') 22771 } 22772 22773 const ct = headers && headers.get('content-type') 22774 let charset = 'utf-8' 22775 let res 22776 22777 // header 22778 if (ct) { 22779 res = /charset=([^;]*)/i.exec(ct) 22780 } 22781 22782 // no charset in content type, peek at response body for at most 1024 bytes 22783 const str = buffer.slice(0, 1024).toString() 22784 22785 // html5 22786 if (!res && str) { 22787 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str) 22788 } 22789 22790 // html4 22791 if (!res && str) { 22792 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str) 22793 22794 if (!res) { 22795 res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str) 22796 if (res) { 22797 res.pop() 22798 } // drop last quote 22799 } 22800 22801 if (res) { 22802 res = /charset=(.*)/i.exec(res.pop()) 22803 } 22804 } 22805 22806 // xml 22807 if (!res && str) { 22808 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str) 22809 } 22810 22811 // found charset 22812 if (res) { 22813 charset = res.pop() 22814 22815 // prevent decode issues when sites use incorrect encoding 22816 // ref: https://hsivonen.fi/encoding-menu/ 22817 if (charset === 'gb2312' || charset === 'gbk') { 22818 charset = 'gb18030' 22819 } 22820 } 22821 22822 // turn raw buffers into a single utf-8 buffer 22823 return convert( 22824 buffer, 22825 'UTF-8', 22826 charset 22827 ).toString() 22828 } 22829 22830 module.exports = Body 22831 22832 22833 /***/ }), 22834 22835 /***/ 2899: 22836 /***/ ((module) => { 22837 22838 "use strict"; 22839 22840 class FetchError extends Error { 22841 constructor (message, type, systemError) { 22842 super(message) 22843 this.code = 'FETCH_ERROR' 22844 22845 // pick up code, expected, path, ... 22846 if (systemError) { 22847 Object.assign(this, systemError) 22848 } 22849 22850 this.errno = this.code 22851 22852 // override anything the system error might've clobbered 22853 this.type = this.code === 'EBADSIZE' && this.found > this.expect 22854 ? 'max-size' : type 22855 this.message = message 22856 Error.captureStackTrace(this, this.constructor) 22857 } 22858 22859 get name () { 22860 return 'FetchError' 22861 } 22862 22863 // don't allow name to be overwritten 22864 set name (n) {} 22865 22866 get [Symbol.toStringTag] () { 22867 return 'FetchError' 22868 } 22869 } 22870 module.exports = FetchError 22871 22872 22873 /***/ }), 22874 22875 /***/ 1504: 22876 /***/ ((module) => { 22877 22878 "use strict"; 22879 22880 const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/ 22881 const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/ 22882 22883 const validateName = name => { 22884 name = `${name}` 22885 if (invalidTokenRegex.test(name) || name === '') { 22886 throw new TypeError(`${name} is not a legal HTTP header name`) 22887 } 22888 } 22889 22890 const validateValue = value => { 22891 value = `${value}` 22892 if (invalidHeaderCharRegex.test(value)) { 22893 throw new TypeError(`${value} is not a legal HTTP header value`) 22894 } 22895 } 22896 22897 const find = (map, name) => { 22898 name = name.toLowerCase() 22899 for (const key in map) { 22900 if (key.toLowerCase() === name) { 22901 return key 22902 } 22903 } 22904 return undefined 22905 } 22906 22907 const MAP = Symbol('map') 22908 class Headers { 22909 constructor (init = undefined) { 22910 this[MAP] = Object.create(null) 22911 if (init instanceof Headers) { 22912 const rawHeaders = init.raw() 22913 const headerNames = Object.keys(rawHeaders) 22914 for (const headerName of headerNames) { 22915 for (const value of rawHeaders[headerName]) { 22916 this.append(headerName, value) 22917 } 22918 } 22919 return 22920 } 22921 22922 // no-op 22923 if (init === undefined || init === null) { 22924 return 22925 } 22926 22927 if (typeof init === 'object') { 22928 const method = init[Symbol.iterator] 22929 if (method !== null && method !== undefined) { 22930 if (typeof method !== 'function') { 22931 throw new TypeError('Header pairs must be iterable') 22932 } 22933 22934 // sequence<sequence<ByteString>> 22935 // Note: per spec we have to first exhaust the lists then process them 22936 const pairs = [] 22937 for (const pair of init) { 22938 if (typeof pair !== 'object' || 22939 typeof pair[Symbol.iterator] !== 'function') { 22940 throw new TypeError('Each header pair must be iterable') 22941 } 22942 const arrPair = Array.from(pair) 22943 if (arrPair.length !== 2) { 22944 throw new TypeError('Each header pair must be a name/value tuple') 22945 } 22946 pairs.push(arrPair) 22947 } 22948 22949 for (const pair of pairs) { 22950 this.append(pair[0], pair[1]) 22951 } 22952 } else { 22953 // record<ByteString, ByteString> 22954 for (const key of Object.keys(init)) { 22955 this.append(key, init[key]) 22956 } 22957 } 22958 } else { 22959 throw new TypeError('Provided initializer must be an object') 22960 } 22961 } 22962 22963 get (name) { 22964 name = `${name}` 22965 validateName(name) 22966 const key = find(this[MAP], name) 22967 if (key === undefined) { 22968 return null 22969 } 22970 22971 return this[MAP][key].join(', ') 22972 } 22973 22974 forEach (callback, thisArg = undefined) { 22975 let pairs = getHeaders(this) 22976 for (let i = 0; i < pairs.length; i++) { 22977 const [name, value] = pairs[i] 22978 callback.call(thisArg, value, name, this) 22979 // refresh in case the callback added more headers 22980 pairs = getHeaders(this) 22981 } 22982 } 22983 22984 set (name, value) { 22985 name = `${name}` 22986 value = `${value}` 22987 validateName(name) 22988 validateValue(value) 22989 const key = find(this[MAP], name) 22990 this[MAP][key !== undefined ? key : name] = [value] 22991 } 22992 22993 append (name, value) { 22994 name = `${name}` 22995 value = `${value}` 22996 validateName(name) 22997 validateValue(value) 22998 const key = find(this[MAP], name) 22999 if (key !== undefined) { 23000 this[MAP][key].push(value) 23001 } else { 23002 this[MAP][name] = [value] 23003 } 23004 } 23005 23006 has (name) { 23007 name = `${name}` 23008 validateName(name) 23009 return find(this[MAP], name) !== undefined 23010 } 23011 23012 delete (name) { 23013 name = `${name}` 23014 validateName(name) 23015 const key = find(this[MAP], name) 23016 if (key !== undefined) { 23017 delete this[MAP][key] 23018 } 23019 } 23020 23021 raw () { 23022 return this[MAP] 23023 } 23024 23025 keys () { 23026 return new HeadersIterator(this, 'key') 23027 } 23028 23029 values () { 23030 return new HeadersIterator(this, 'value') 23031 } 23032 23033 [Symbol.iterator] () { 23034 return new HeadersIterator(this, 'key+value') 23035 } 23036 23037 entries () { 23038 return new HeadersIterator(this, 'key+value') 23039 } 23040 23041 get [Symbol.toStringTag] () { 23042 return 'Headers' 23043 } 23044 23045 static exportNodeCompatibleHeaders (headers) { 23046 const obj = Object.assign(Object.create(null), headers[MAP]) 23047 23048 // http.request() only supports string as Host header. This hack makes 23049 // specifying custom Host header possible. 23050 const hostHeaderKey = find(headers[MAP], 'Host') 23051 if (hostHeaderKey !== undefined) { 23052 obj[hostHeaderKey] = obj[hostHeaderKey][0] 23053 } 23054 23055 return obj 23056 } 23057 23058 static createHeadersLenient (obj) { 23059 const headers = new Headers() 23060 for (const name of Object.keys(obj)) { 23061 if (invalidTokenRegex.test(name)) { 23062 continue 23063 } 23064 23065 if (Array.isArray(obj[name])) { 23066 for (const val of obj[name]) { 23067 if (invalidHeaderCharRegex.test(val)) { 23068 continue 23069 } 23070 23071 if (headers[MAP][name] === undefined) { 23072 headers[MAP][name] = [val] 23073 } else { 23074 headers[MAP][name].push(val) 23075 } 23076 } 23077 } else if (!invalidHeaderCharRegex.test(obj[name])) { 23078 headers[MAP][name] = [obj[name]] 23079 } 23080 } 23081 return headers 23082 } 23083 } 23084 23085 Object.defineProperties(Headers.prototype, { 23086 get: { enumerable: true }, 23087 forEach: { enumerable: true }, 23088 set: { enumerable: true }, 23089 append: { enumerable: true }, 23090 has: { enumerable: true }, 23091 delete: { enumerable: true }, 23092 keys: { enumerable: true }, 23093 values: { enumerable: true }, 23094 entries: { enumerable: true }, 23095 }) 23096 23097 const getHeaders = (headers, kind = 'key+value') => 23098 Object.keys(headers[MAP]).sort().map( 23099 kind === 'key' ? k => k.toLowerCase() 23100 : kind === 'value' ? k => headers[MAP][k].join(', ') 23101 : k => [k.toLowerCase(), headers[MAP][k].join(', ')] 23102 ) 23103 23104 const INTERNAL = Symbol('internal') 23105 23106 class HeadersIterator { 23107 constructor (target, kind) { 23108 this[INTERNAL] = { 23109 target, 23110 kind, 23111 index: 0, 23112 } 23113 } 23114 23115 get [Symbol.toStringTag] () { 23116 return 'HeadersIterator' 23117 } 23118 23119 next () { 23120 /* istanbul ignore if: should be impossible */ 23121 if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) { 23122 throw new TypeError('Value of `this` is not a HeadersIterator') 23123 } 23124 23125 const { target, kind, index } = this[INTERNAL] 23126 const values = getHeaders(target, kind) 23127 const len = values.length 23128 if (index >= len) { 23129 return { 23130 value: undefined, 23131 done: true, 23132 } 23133 } 23134 23135 this[INTERNAL].index++ 23136 23137 return { value: values[index], done: false } 23138 } 23139 } 23140 23141 // manually extend because 'extends' requires a ctor 23142 Object.setPrototypeOf(HeadersIterator.prototype, 23143 Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))) 23144 23145 module.exports = Headers 23146 23147 23148 /***/ }), 23149 23150 /***/ 8998: 23151 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 23152 23153 "use strict"; 23154 23155 const { URL } = __nccwpck_require__(7310) 23156 const http = __nccwpck_require__(3685) 23157 const https = __nccwpck_require__(5687) 23158 const zlib = __nccwpck_require__(3486) 23159 const { Minipass } = __nccwpck_require__(4968) 23160 23161 const Body = __nccwpck_require__(7223) 23162 const { writeToStream, getTotalBytes } = Body 23163 const Response = __nccwpck_require__(2587) 23164 const Headers = __nccwpck_require__(1504) 23165 const { createHeadersLenient } = Headers 23166 const Request = __nccwpck_require__(4410) 23167 const { getNodeRequestOptions } = Request 23168 const FetchError = __nccwpck_require__(2899) 23169 const AbortError = __nccwpck_require__(1078) 23170 23171 // XXX this should really be split up and unit-ized for easier testing 23172 // and better DRY implementation of data/http request aborting 23173 const fetch = async (url, opts) => { 23174 if (/^data:/.test(url)) { 23175 const request = new Request(url, opts) 23176 // delay 1 promise tick so that the consumer can abort right away 23177 return Promise.resolve().then(() => new Promise((resolve, reject) => { 23178 let type, data 23179 try { 23180 const { pathname, search } = new URL(url) 23181 const split = pathname.split(',') 23182 if (split.length < 2) { 23183 throw new Error('invalid data: URI') 23184 } 23185 const mime = split.shift() 23186 const base64 = /;base64$/.test(mime) 23187 type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime 23188 const rawData = decodeURIComponent(split.join(',') + search) 23189 data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData) 23190 } catch (er) { 23191 return reject(new FetchError(`[${request.method}] ${ 23192 request.url} invalid URL, ${er.message}`, 'system', er)) 23193 } 23194 23195 const { signal } = request 23196 if (signal && signal.aborted) { 23197 return reject(new AbortError('The user aborted a request.')) 23198 } 23199 23200 const headers = { 'Content-Length': data.length } 23201 if (type) { 23202 headers['Content-Type'] = type 23203 } 23204 return resolve(new Response(data, { headers })) 23205 })) 23206 } 23207 23208 return new Promise((resolve, reject) => { 23209 // build request object 23210 const request = new Request(url, opts) 23211 let options 23212 try { 23213 options = getNodeRequestOptions(request) 23214 } catch (er) { 23215 return reject(er) 23216 } 23217 23218 const send = (options.protocol === 'https:' ? https : http).request 23219 const { signal } = request 23220 let response = null 23221 const abort = () => { 23222 const error = new AbortError('The user aborted a request.') 23223 reject(error) 23224 if (Minipass.isStream(request.body) && 23225 typeof request.body.destroy === 'function') { 23226 request.body.destroy(error) 23227 } 23228 if (response && response.body) { 23229 response.body.emit('error', error) 23230 } 23231 } 23232 23233 if (signal && signal.aborted) { 23234 return abort() 23235 } 23236 23237 const abortAndFinalize = () => { 23238 abort() 23239 finalize() 23240 } 23241 23242 const finalize = () => { 23243 req.abort() 23244 if (signal) { 23245 signal.removeEventListener('abort', abortAndFinalize) 23246 } 23247 clearTimeout(reqTimeout) 23248 } 23249 23250 // send request 23251 const req = send(options) 23252 23253 if (signal) { 23254 signal.addEventListener('abort', abortAndFinalize) 23255 } 23256 23257 let reqTimeout = null 23258 if (request.timeout) { 23259 req.once('socket', socket => { 23260 reqTimeout = setTimeout(() => { 23261 reject(new FetchError(`network timeout at: ${ 23262 request.url}`, 'request-timeout')) 23263 finalize() 23264 }, request.timeout) 23265 }) 23266 } 23267 23268 req.on('error', er => { 23269 // if a 'response' event is emitted before the 'error' event, then by the 23270 // time this handler is run it's too late to reject the Promise for the 23271 // response. instead, we forward the error event to the response stream 23272 // so that the error will surface to the user when they try to consume 23273 // the body. this is done as a side effect of aborting the request except 23274 // for in windows, where we must forward the event manually, otherwise 23275 // there is no longer a ref'd socket attached to the request and the 23276 // stream never ends so the event loop runs out of work and the process 23277 // exits without warning. 23278 // coverage skipped here due to the difficulty in testing 23279 // istanbul ignore next 23280 if (req.res) { 23281 req.res.emit('error', er) 23282 } 23283 reject(new FetchError(`request to ${request.url} failed, reason: ${ 23284 er.message}`, 'system', er)) 23285 finalize() 23286 }) 23287 23288 req.on('response', res => { 23289 clearTimeout(reqTimeout) 23290 23291 const headers = createHeadersLenient(res.headers) 23292 23293 // HTTP fetch step 5 23294 if (fetch.isRedirect(res.statusCode)) { 23295 // HTTP fetch step 5.2 23296 const location = headers.get('Location') 23297 23298 // HTTP fetch step 5.3 23299 let locationURL = null 23300 try { 23301 locationURL = location === null ? null : new URL(location, request.url).toString() 23302 } catch { 23303 // error here can only be invalid URL in Location: header 23304 // do not throw when options.redirect == manual 23305 // let the user extract the errorneous redirect URL 23306 if (request.redirect !== 'manual') { 23307 /* eslint-disable-next-line max-len */ 23308 reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')) 23309 finalize() 23310 return 23311 } 23312 } 23313 23314 // HTTP fetch step 5.5 23315 if (request.redirect === 'error') { 23316 reject(new FetchError('uri requested responds with a redirect, ' + 23317 `redirect mode is set to error: ${request.url}`, 'no-redirect')) 23318 finalize() 23319 return 23320 } else if (request.redirect === 'manual') { 23321 // node-fetch-specific step: make manual redirect a bit easier to 23322 // use by setting the Location header value to the resolved URL. 23323 if (locationURL !== null) { 23324 // handle corrupted header 23325 try { 23326 headers.set('Location', locationURL) 23327 } catch (err) { 23328 /* istanbul ignore next: nodejs server prevent invalid 23329 response headers, we can't test this through normal 23330 request */ 23331 reject(err) 23332 } 23333 } 23334 } else if (request.redirect === 'follow' && locationURL !== null) { 23335 // HTTP-redirect fetch step 5 23336 if (request.counter >= request.follow) { 23337 reject(new FetchError(`maximum redirect reached at: ${ 23338 request.url}`, 'max-redirect')) 23339 finalize() 23340 return 23341 } 23342 23343 // HTTP-redirect fetch step 9 23344 if (res.statusCode !== 303 && 23345 request.body && 23346 getTotalBytes(request) === null) { 23347 reject(new FetchError( 23348 'Cannot follow redirect with body being a readable stream', 23349 'unsupported-redirect' 23350 )) 23351 finalize() 23352 return 23353 } 23354 23355 // Update host due to redirection 23356 request.headers.set('host', (new URL(locationURL)).host) 23357 23358 // HTTP-redirect fetch step 6 (counter increment) 23359 // Create a new Request object. 23360 const requestOpts = { 23361 headers: new Headers(request.headers), 23362 follow: request.follow, 23363 counter: request.counter + 1, 23364 agent: request.agent, 23365 compress: request.compress, 23366 method: request.method, 23367 body: request.body, 23368 signal: request.signal, 23369 timeout: request.timeout, 23370 } 23371 23372 // if the redirect is to a new hostname, strip the authorization and cookie headers 23373 const parsedOriginal = new URL(request.url) 23374 const parsedRedirect = new URL(locationURL) 23375 if (parsedOriginal.hostname !== parsedRedirect.hostname) { 23376 requestOpts.headers.delete('authorization') 23377 requestOpts.headers.delete('cookie') 23378 } 23379 23380 // HTTP-redirect fetch step 11 23381 if (res.statusCode === 303 || ( 23382 (res.statusCode === 301 || res.statusCode === 302) && 23383 request.method === 'POST' 23384 )) { 23385 requestOpts.method = 'GET' 23386 requestOpts.body = undefined 23387 requestOpts.headers.delete('content-length') 23388 } 23389 23390 // HTTP-redirect fetch step 15 23391 resolve(fetch(new Request(locationURL, requestOpts))) 23392 finalize() 23393 return 23394 } 23395 } // end if(isRedirect) 23396 23397 // prepare response 23398 res.once('end', () => 23399 signal && signal.removeEventListener('abort', abortAndFinalize)) 23400 23401 const body = new Minipass() 23402 // if an error occurs, either on the response stream itself, on one of the 23403 // decoder streams, or a response length timeout from the Body class, we 23404 // forward the error through to our internal body stream. If we see an 23405 // error event on that, we call finalize to abort the request and ensure 23406 // we don't leave a socket believing a request is in flight. 23407 // this is difficult to test, so lacks specific coverage. 23408 body.on('error', finalize) 23409 // exceedingly rare that the stream would have an error, 23410 // but just in case we proxy it to the stream in use. 23411 res.on('error', /* istanbul ignore next */ er => body.emit('error', er)) 23412 res.on('data', (chunk) => body.write(chunk)) 23413 res.on('end', () => body.end()) 23414 23415 const responseOptions = { 23416 url: request.url, 23417 status: res.statusCode, 23418 statusText: res.statusMessage, 23419 headers: headers, 23420 size: request.size, 23421 timeout: request.timeout, 23422 counter: request.counter, 23423 trailer: new Promise(resolveTrailer => 23424 res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))), 23425 } 23426 23427 // HTTP-network fetch step 12.1.1.3 23428 const codings = headers.get('Content-Encoding') 23429 23430 // HTTP-network fetch step 12.1.1.4: handle content codings 23431 23432 // in following scenarios we ignore compression support 23433 // 1. compression support is disabled 23434 // 2. HEAD request 23435 // 3. no Content-Encoding header 23436 // 4. no content response (204) 23437 // 5. content not modified response (304) 23438 if (!request.compress || 23439 request.method === 'HEAD' || 23440 codings === null || 23441 res.statusCode === 204 || 23442 res.statusCode === 304) { 23443 response = new Response(body, responseOptions) 23444 resolve(response) 23445 return 23446 } 23447 23448 // Be less strict when decoding compressed responses, since sometimes 23449 // servers send slightly invalid responses that are still accepted 23450 // by common browsers. 23451 // Always using Z_SYNC_FLUSH is what cURL does. 23452 const zlibOptions = { 23453 flush: zlib.constants.Z_SYNC_FLUSH, 23454 finishFlush: zlib.constants.Z_SYNC_FLUSH, 23455 } 23456 23457 // for gzip 23458 if (codings === 'gzip' || codings === 'x-gzip') { 23459 const unzip = new zlib.Gunzip(zlibOptions) 23460 response = new Response( 23461 // exceedingly rare that the stream would have an error, 23462 // but just in case we proxy it to the stream in use. 23463 body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip), 23464 responseOptions 23465 ) 23466 resolve(response) 23467 return 23468 } 23469 23470 // for deflate 23471 if (codings === 'deflate' || codings === 'x-deflate') { 23472 // handle the infamous raw deflate response from old servers 23473 // a hack for old IIS and Apache servers 23474 const raw = res.pipe(new Minipass()) 23475 raw.once('data', chunk => { 23476 // see http://stackoverflow.com/questions/37519828 23477 const decoder = (chunk[0] & 0x0F) === 0x08 23478 ? new zlib.Inflate() 23479 : new zlib.InflateRaw() 23480 // exceedingly rare that the stream would have an error, 23481 // but just in case we proxy it to the stream in use. 23482 body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) 23483 response = new Response(decoder, responseOptions) 23484 resolve(response) 23485 }) 23486 return 23487 } 23488 23489 // for br 23490 if (codings === 'br') { 23491 // ignoring coverage so tests don't have to fake support (or lack of) for brotli 23492 // istanbul ignore next 23493 try { 23494 var decoder = new zlib.BrotliDecompress() 23495 } catch (err) { 23496 reject(err) 23497 finalize() 23498 return 23499 } 23500 // exceedingly rare that the stream would have an error, 23501 // but just in case we proxy it to the stream in use. 23502 body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) 23503 response = new Response(decoder, responseOptions) 23504 resolve(response) 23505 return 23506 } 23507 23508 // otherwise, use response as-is 23509 response = new Response(body, responseOptions) 23510 resolve(response) 23511 }) 23512 23513 writeToStream(req, request) 23514 }) 23515 } 23516 23517 module.exports = fetch 23518 23519 fetch.isRedirect = code => 23520 code === 301 || 23521 code === 302 || 23522 code === 303 || 23523 code === 307 || 23524 code === 308 23525 23526 fetch.Headers = Headers 23527 fetch.Request = Request 23528 fetch.Response = Response 23529 fetch.FetchError = FetchError 23530 fetch.AbortError = AbortError 23531 23532 23533 /***/ }), 23534 23535 /***/ 4410: 23536 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 23537 23538 "use strict"; 23539 23540 const { URL } = __nccwpck_require__(7310) 23541 const { Minipass } = __nccwpck_require__(4968) 23542 const Headers = __nccwpck_require__(1504) 23543 const { exportNodeCompatibleHeaders } = Headers 23544 const Body = __nccwpck_require__(7223) 23545 const { clone, extractContentType, getTotalBytes } = Body 23546 23547 const version = (__nccwpck_require__(500)/* .version */ .i8) 23548 const defaultUserAgent = 23549 `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)` 23550 23551 const INTERNALS = Symbol('Request internals') 23552 23553 const isRequest = input => 23554 typeof input === 'object' && typeof input[INTERNALS] === 'object' 23555 23556 const isAbortSignal = signal => { 23557 const proto = ( 23558 signal 23559 && typeof signal === 'object' 23560 && Object.getPrototypeOf(signal) 23561 ) 23562 return !!(proto && proto.constructor.name === 'AbortSignal') 23563 } 23564 23565 class Request extends Body { 23566 constructor (input, init = {}) { 23567 const parsedURL = isRequest(input) ? new URL(input.url) 23568 : input && input.href ? new URL(input.href) 23569 : new URL(`${input}`) 23570 23571 if (isRequest(input)) { 23572 init = { ...input[INTERNALS], ...init } 23573 } else if (!input || typeof input === 'string') { 23574 input = {} 23575 } 23576 23577 const method = (init.method || input.method || 'GET').toUpperCase() 23578 const isGETHEAD = method === 'GET' || method === 'HEAD' 23579 23580 if ((init.body !== null && init.body !== undefined || 23581 isRequest(input) && input.body !== null) && isGETHEAD) { 23582 throw new TypeError('Request with GET/HEAD method cannot have body') 23583 } 23584 23585 const inputBody = init.body !== null && init.body !== undefined ? init.body 23586 : isRequest(input) && input.body !== null ? clone(input) 23587 : null 23588 23589 super(inputBody, { 23590 timeout: init.timeout || input.timeout || 0, 23591 size: init.size || input.size || 0, 23592 }) 23593 23594 const headers = new Headers(init.headers || input.headers || {}) 23595 23596 if (inputBody !== null && inputBody !== undefined && 23597 !headers.has('Content-Type')) { 23598 const contentType = extractContentType(inputBody) 23599 if (contentType) { 23600 headers.append('Content-Type', contentType) 23601 } 23602 } 23603 23604 const signal = 'signal' in init ? init.signal 23605 : null 23606 23607 if (signal !== null && signal !== undefined && !isAbortSignal(signal)) { 23608 throw new TypeError('Expected signal must be an instanceof AbortSignal') 23609 } 23610 23611 // TLS specific options that are handled by node 23612 const { 23613 ca, 23614 cert, 23615 ciphers, 23616 clientCertEngine, 23617 crl, 23618 dhparam, 23619 ecdhCurve, 23620 family, 23621 honorCipherOrder, 23622 key, 23623 passphrase, 23624 pfx, 23625 rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', 23626 secureOptions, 23627 secureProtocol, 23628 servername, 23629 sessionIdContext, 23630 } = init 23631 23632 this[INTERNALS] = { 23633 method, 23634 redirect: init.redirect || input.redirect || 'follow', 23635 headers, 23636 parsedURL, 23637 signal, 23638 ca, 23639 cert, 23640 ciphers, 23641 clientCertEngine, 23642 crl, 23643 dhparam, 23644 ecdhCurve, 23645 family, 23646 honorCipherOrder, 23647 key, 23648 passphrase, 23649 pfx, 23650 rejectUnauthorized, 23651 secureOptions, 23652 secureProtocol, 23653 servername, 23654 sessionIdContext, 23655 } 23656 23657 // node-fetch-only options 23658 this.follow = init.follow !== undefined ? init.follow 23659 : input.follow !== undefined ? input.follow 23660 : 20 23661 this.compress = init.compress !== undefined ? init.compress 23662 : input.compress !== undefined ? input.compress 23663 : true 23664 this.counter = init.counter || input.counter || 0 23665 this.agent = init.agent || input.agent 23666 } 23667 23668 get method () { 23669 return this[INTERNALS].method 23670 } 23671 23672 get url () { 23673 return this[INTERNALS].parsedURL.toString() 23674 } 23675 23676 get headers () { 23677 return this[INTERNALS].headers 23678 } 23679 23680 get redirect () { 23681 return this[INTERNALS].redirect 23682 } 23683 23684 get signal () { 23685 return this[INTERNALS].signal 23686 } 23687 23688 clone () { 23689 return new Request(this) 23690 } 23691 23692 get [Symbol.toStringTag] () { 23693 return 'Request' 23694 } 23695 23696 static getNodeRequestOptions (request) { 23697 const parsedURL = request[INTERNALS].parsedURL 23698 const headers = new Headers(request[INTERNALS].headers) 23699 23700 // fetch step 1.3 23701 if (!headers.has('Accept')) { 23702 headers.set('Accept', '*/*') 23703 } 23704 23705 // Basic fetch 23706 if (!/^https?:$/.test(parsedURL.protocol)) { 23707 throw new TypeError('Only HTTP(S) protocols are supported') 23708 } 23709 23710 if (request.signal && 23711 Minipass.isStream(request.body) && 23712 typeof request.body.destroy !== 'function') { 23713 throw new Error( 23714 'Cancellation of streamed requests with AbortSignal is not supported') 23715 } 23716 23717 // HTTP-network-or-cache fetch steps 2.4-2.7 23718 const contentLengthValue = 23719 (request.body === null || request.body === undefined) && 23720 /^(POST|PUT)$/i.test(request.method) ? '0' 23721 : request.body !== null && request.body !== undefined 23722 ? getTotalBytes(request) 23723 : null 23724 23725 if (contentLengthValue) { 23726 headers.set('Content-Length', contentLengthValue + '') 23727 } 23728 23729 // HTTP-network-or-cache fetch step 2.11 23730 if (!headers.has('User-Agent')) { 23731 headers.set('User-Agent', defaultUserAgent) 23732 } 23733 23734 // HTTP-network-or-cache fetch step 2.15 23735 if (request.compress && !headers.has('Accept-Encoding')) { 23736 headers.set('Accept-Encoding', 'gzip,deflate') 23737 } 23738 23739 const agent = typeof request.agent === 'function' 23740 ? request.agent(parsedURL) 23741 : request.agent 23742 23743 if (!headers.has('Connection') && !agent) { 23744 headers.set('Connection', 'close') 23745 } 23746 23747 // TLS specific options that are handled by node 23748 const { 23749 ca, 23750 cert, 23751 ciphers, 23752 clientCertEngine, 23753 crl, 23754 dhparam, 23755 ecdhCurve, 23756 family, 23757 honorCipherOrder, 23758 key, 23759 passphrase, 23760 pfx, 23761 rejectUnauthorized, 23762 secureOptions, 23763 secureProtocol, 23764 servername, 23765 sessionIdContext, 23766 } = request[INTERNALS] 23767 23768 // HTTP-network fetch step 4.2 23769 // chunked encoding is handled by Node.js 23770 23771 // we cannot spread parsedURL directly, so we have to read each property one-by-one 23772 // and map them to the equivalent https?.request() method options 23773 const urlProps = { 23774 auth: parsedURL.username || parsedURL.password 23775 ? `${parsedURL.username}:${parsedURL.password}` 23776 : '', 23777 host: parsedURL.host, 23778 hostname: parsedURL.hostname, 23779 path: `${parsedURL.pathname}${parsedURL.search}`, 23780 port: parsedURL.port, 23781 protocol: parsedURL.protocol, 23782 } 23783 23784 return { 23785 ...urlProps, 23786 method: request.method, 23787 headers: exportNodeCompatibleHeaders(headers), 23788 agent, 23789 ca, 23790 cert, 23791 ciphers, 23792 clientCertEngine, 23793 crl, 23794 dhparam, 23795 ecdhCurve, 23796 family, 23797 honorCipherOrder, 23798 key, 23799 passphrase, 23800 pfx, 23801 rejectUnauthorized, 23802 secureOptions, 23803 secureProtocol, 23804 servername, 23805 sessionIdContext, 23806 timeout: request.timeout, 23807 } 23808 } 23809 } 23810 23811 module.exports = Request 23812 23813 Object.defineProperties(Request.prototype, { 23814 method: { enumerable: true }, 23815 url: { enumerable: true }, 23816 headers: { enumerable: true }, 23817 redirect: { enumerable: true }, 23818 clone: { enumerable: true }, 23819 signal: { enumerable: true }, 23820 }) 23821 23822 23823 /***/ }), 23824 23825 /***/ 2587: 23826 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 23827 23828 "use strict"; 23829 23830 const http = __nccwpck_require__(3685) 23831 const { STATUS_CODES } = http 23832 23833 const Headers = __nccwpck_require__(1504) 23834 const Body = __nccwpck_require__(7223) 23835 const { clone, extractContentType } = Body 23836 23837 const INTERNALS = Symbol('Response internals') 23838 23839 class Response extends Body { 23840 constructor (body = null, opts = {}) { 23841 super(body, opts) 23842 23843 const status = opts.status || 200 23844 const headers = new Headers(opts.headers) 23845 23846 if (body !== null && body !== undefined && !headers.has('Content-Type')) { 23847 const contentType = extractContentType(body) 23848 if (contentType) { 23849 headers.append('Content-Type', contentType) 23850 } 23851 } 23852 23853 this[INTERNALS] = { 23854 url: opts.url, 23855 status, 23856 statusText: opts.statusText || STATUS_CODES[status], 23857 headers, 23858 counter: opts.counter, 23859 trailer: Promise.resolve(opts.trailer || new Headers()), 23860 } 23861 } 23862 23863 get trailer () { 23864 return this[INTERNALS].trailer 23865 } 23866 23867 get url () { 23868 return this[INTERNALS].url || '' 23869 } 23870 23871 get status () { 23872 return this[INTERNALS].status 23873 } 23874 23875 get ok () { 23876 return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300 23877 } 23878 23879 get redirected () { 23880 return this[INTERNALS].counter > 0 23881 } 23882 23883 get statusText () { 23884 return this[INTERNALS].statusText 23885 } 23886 23887 get headers () { 23888 return this[INTERNALS].headers 23889 } 23890 23891 clone () { 23892 return new Response(clone(this), { 23893 url: this.url, 23894 status: this.status, 23895 statusText: this.statusText, 23896 headers: this.headers, 23897 ok: this.ok, 23898 redirected: this.redirected, 23899 trailer: this.trailer, 23900 }) 23901 } 23902 23903 get [Symbol.toStringTag] () { 23904 return 'Response' 23905 } 23906 } 23907 23908 module.exports = Response 23909 23910 Object.defineProperties(Response.prototype, { 23911 url: { enumerable: true }, 23912 status: { enumerable: true }, 23913 ok: { enumerable: true }, 23914 redirected: { enumerable: true }, 23915 statusText: { enumerable: true }, 23916 headers: { enumerable: true }, 23917 clone: { enumerable: true }, 23918 }) 23919 23920 23921 /***/ }), 23922 23923 /***/ 4181: 23924 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 23925 23926 const Minipass = __nccwpck_require__(7818) 23927 const _flush = Symbol('_flush') 23928 const _flushed = Symbol('_flushed') 23929 const _flushing = Symbol('_flushing') 23930 class Flush extends Minipass { 23931 constructor (opt = {}) { 23932 if (typeof opt === 'function') 23933 opt = { flush: opt } 23934 23935 super(opt) 23936 23937 // or extend this class and provide a 'flush' method in your subclass 23938 if (typeof opt.flush !== 'function' && typeof this.flush !== 'function') 23939 throw new TypeError('must provide flush function in options') 23940 23941 this[_flush] = opt.flush || this.flush 23942 } 23943 23944 emit (ev, ...data) { 23945 if ((ev !== 'end' && ev !== 'finish') || this[_flushed]) 23946 return super.emit(ev, ...data) 23947 23948 if (this[_flushing]) 23949 return 23950 23951 this[_flushing] = true 23952 23953 const afterFlush = er => { 23954 this[_flushed] = true 23955 er ? super.emit('error', er) : super.emit('end') 23956 } 23957 23958 const ret = this[_flush](afterFlush) 23959 if (ret && ret.then) 23960 ret.then(() => afterFlush(), er => afterFlush(er)) 23961 } 23962 } 23963 23964 module.exports = Flush 23965 23966 23967 /***/ }), 23968 23969 /***/ 7818: 23970 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 23971 23972 "use strict"; 23973 23974 const proc = typeof process === 'object' && process ? process : { 23975 stdout: null, 23976 stderr: null, 23977 } 23978 const EE = __nccwpck_require__(2361) 23979 const Stream = __nccwpck_require__(2781) 23980 const SD = (__nccwpck_require__(1576).StringDecoder) 23981 23982 const EOF = Symbol('EOF') 23983 const MAYBE_EMIT_END = Symbol('maybeEmitEnd') 23984 const EMITTED_END = Symbol('emittedEnd') 23985 const EMITTING_END = Symbol('emittingEnd') 23986 const EMITTED_ERROR = Symbol('emittedError') 23987 const CLOSED = Symbol('closed') 23988 const READ = Symbol('read') 23989 const FLUSH = Symbol('flush') 23990 const FLUSHCHUNK = Symbol('flushChunk') 23991 const ENCODING = Symbol('encoding') 23992 const DECODER = Symbol('decoder') 23993 const FLOWING = Symbol('flowing') 23994 const PAUSED = Symbol('paused') 23995 const RESUME = Symbol('resume') 23996 const BUFFERLENGTH = Symbol('bufferLength') 23997 const BUFFERPUSH = Symbol('bufferPush') 23998 const BUFFERSHIFT = Symbol('bufferShift') 23999 const OBJECTMODE = Symbol('objectMode') 24000 const DESTROYED = Symbol('destroyed') 24001 const EMITDATA = Symbol('emitData') 24002 const EMITEND = Symbol('emitEnd') 24003 const EMITEND2 = Symbol('emitEnd2') 24004 const ASYNC = Symbol('async') 24005 24006 const defer = fn => Promise.resolve().then(fn) 24007 24008 // TODO remove when Node v8 support drops 24009 const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' 24010 const ASYNCITERATOR = doIter && Symbol.asyncIterator 24011 || Symbol('asyncIterator not implemented') 24012 const ITERATOR = doIter && Symbol.iterator 24013 || Symbol('iterator not implemented') 24014 24015 // events that mean 'the stream is over' 24016 // these are treated specially, and re-emitted 24017 // if they are listened for after emitting. 24018 const isEndish = ev => 24019 ev === 'end' || 24020 ev === 'finish' || 24021 ev === 'prefinish' 24022 24023 const isArrayBuffer = b => b instanceof ArrayBuffer || 24024 typeof b === 'object' && 24025 b.constructor && 24026 b.constructor.name === 'ArrayBuffer' && 24027 b.byteLength >= 0 24028 24029 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) 24030 24031 class Pipe { 24032 constructor (src, dest, opts) { 24033 this.src = src 24034 this.dest = dest 24035 this.opts = opts 24036 this.ondrain = () => src[RESUME]() 24037 dest.on('drain', this.ondrain) 24038 } 24039 unpipe () { 24040 this.dest.removeListener('drain', this.ondrain) 24041 } 24042 // istanbul ignore next - only here for the prototype 24043 proxyErrors () {} 24044 end () { 24045 this.unpipe() 24046 if (this.opts.end) 24047 this.dest.end() 24048 } 24049 } 24050 24051 class PipeProxyErrors extends Pipe { 24052 unpipe () { 24053 this.src.removeListener('error', this.proxyErrors) 24054 super.unpipe() 24055 } 24056 constructor (src, dest, opts) { 24057 super(src, dest, opts) 24058 this.proxyErrors = er => dest.emit('error', er) 24059 src.on('error', this.proxyErrors) 24060 } 24061 } 24062 24063 module.exports = class Minipass extends Stream { 24064 constructor (options) { 24065 super() 24066 this[FLOWING] = false 24067 // whether we're explicitly paused 24068 this[PAUSED] = false 24069 this.pipes = [] 24070 this.buffer = [] 24071 this[OBJECTMODE] = options && options.objectMode || false 24072 if (this[OBJECTMODE]) 24073 this[ENCODING] = null 24074 else 24075 this[ENCODING] = options && options.encoding || null 24076 if (this[ENCODING] === 'buffer') 24077 this[ENCODING] = null 24078 this[ASYNC] = options && !!options.async || false 24079 this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null 24080 this[EOF] = false 24081 this[EMITTED_END] = false 24082 this[EMITTING_END] = false 24083 this[CLOSED] = false 24084 this[EMITTED_ERROR] = null 24085 this.writable = true 24086 this.readable = true 24087 this[BUFFERLENGTH] = 0 24088 this[DESTROYED] = false 24089 } 24090 24091 get bufferLength () { return this[BUFFERLENGTH] } 24092 24093 get encoding () { return this[ENCODING] } 24094 set encoding (enc) { 24095 if (this[OBJECTMODE]) 24096 throw new Error('cannot set encoding in objectMode') 24097 24098 if (this[ENCODING] && enc !== this[ENCODING] && 24099 (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) 24100 throw new Error('cannot change encoding') 24101 24102 if (this[ENCODING] !== enc) { 24103 this[DECODER] = enc ? new SD(enc) : null 24104 if (this.buffer.length) 24105 this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) 24106 } 24107 24108 this[ENCODING] = enc 24109 } 24110 24111 setEncoding (enc) { 24112 this.encoding = enc 24113 } 24114 24115 get objectMode () { return this[OBJECTMODE] } 24116 set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } 24117 24118 get ['async'] () { return this[ASYNC] } 24119 set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } 24120 24121 write (chunk, encoding, cb) { 24122 if (this[EOF]) 24123 throw new Error('write after end') 24124 24125 if (this[DESTROYED]) { 24126 this.emit('error', Object.assign( 24127 new Error('Cannot call write after a stream was destroyed'), 24128 { code: 'ERR_STREAM_DESTROYED' } 24129 )) 24130 return true 24131 } 24132 24133 if (typeof encoding === 'function') 24134 cb = encoding, encoding = 'utf8' 24135 24136 if (!encoding) 24137 encoding = 'utf8' 24138 24139 const fn = this[ASYNC] ? defer : f => f() 24140 24141 // convert array buffers and typed array views into buffers 24142 // at some point in the future, we may want to do the opposite! 24143 // leave strings and buffers as-is 24144 // anything else switches us into object mode 24145 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { 24146 if (isArrayBufferView(chunk)) 24147 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) 24148 else if (isArrayBuffer(chunk)) 24149 chunk = Buffer.from(chunk) 24150 else if (typeof chunk !== 'string') 24151 // use the setter so we throw if we have encoding set 24152 this.objectMode = true 24153 } 24154 24155 // handle object mode up front, since it's simpler 24156 // this yields better performance, fewer checks later. 24157 if (this[OBJECTMODE]) { 24158 /* istanbul ignore if - maybe impossible? */ 24159 if (this.flowing && this[BUFFERLENGTH] !== 0) 24160 this[FLUSH](true) 24161 24162 if (this.flowing) 24163 this.emit('data', chunk) 24164 else 24165 this[BUFFERPUSH](chunk) 24166 24167 if (this[BUFFERLENGTH] !== 0) 24168 this.emit('readable') 24169 24170 if (cb) 24171 fn(cb) 24172 24173 return this.flowing 24174 } 24175 24176 // at this point the chunk is a buffer or string 24177 // don't buffer it up or send it to the decoder 24178 if (!chunk.length) { 24179 if (this[BUFFERLENGTH] !== 0) 24180 this.emit('readable') 24181 if (cb) 24182 fn(cb) 24183 return this.flowing 24184 } 24185 24186 // fast-path writing strings of same encoding to a stream with 24187 // an empty buffer, skipping the buffer/decoder dance 24188 if (typeof chunk === 'string' && 24189 // unless it is a string already ready for us to use 24190 !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { 24191 chunk = Buffer.from(chunk, encoding) 24192 } 24193 24194 if (Buffer.isBuffer(chunk) && this[ENCODING]) 24195 chunk = this[DECODER].write(chunk) 24196 24197 // Note: flushing CAN potentially switch us into not-flowing mode 24198 if (this.flowing && this[BUFFERLENGTH] !== 0) 24199 this[FLUSH](true) 24200 24201 if (this.flowing) 24202 this.emit('data', chunk) 24203 else 24204 this[BUFFERPUSH](chunk) 24205 24206 if (this[BUFFERLENGTH] !== 0) 24207 this.emit('readable') 24208 24209 if (cb) 24210 fn(cb) 24211 24212 return this.flowing 24213 } 24214 24215 read (n) { 24216 if (this[DESTROYED]) 24217 return null 24218 24219 if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { 24220 this[MAYBE_EMIT_END]() 24221 return null 24222 } 24223 24224 if (this[OBJECTMODE]) 24225 n = null 24226 24227 if (this.buffer.length > 1 && !this[OBJECTMODE]) { 24228 if (this.encoding) 24229 this.buffer = [this.buffer.join('')] 24230 else 24231 this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] 24232 } 24233 24234 const ret = this[READ](n || null, this.buffer[0]) 24235 this[MAYBE_EMIT_END]() 24236 return ret 24237 } 24238 24239 [READ] (n, chunk) { 24240 if (n === chunk.length || n === null) 24241 this[BUFFERSHIFT]() 24242 else { 24243 this.buffer[0] = chunk.slice(n) 24244 chunk = chunk.slice(0, n) 24245 this[BUFFERLENGTH] -= n 24246 } 24247 24248 this.emit('data', chunk) 24249 24250 if (!this.buffer.length && !this[EOF]) 24251 this.emit('drain') 24252 24253 return chunk 24254 } 24255 24256 end (chunk, encoding, cb) { 24257 if (typeof chunk === 'function') 24258 cb = chunk, chunk = null 24259 if (typeof encoding === 'function') 24260 cb = encoding, encoding = 'utf8' 24261 if (chunk) 24262 this.write(chunk, encoding) 24263 if (cb) 24264 this.once('end', cb) 24265 this[EOF] = true 24266 this.writable = false 24267 24268 // if we haven't written anything, then go ahead and emit, 24269 // even if we're not reading. 24270 // we'll re-emit if a new 'end' listener is added anyway. 24271 // This makes MP more suitable to write-only use cases. 24272 if (this.flowing || !this[PAUSED]) 24273 this[MAYBE_EMIT_END]() 24274 return this 24275 } 24276 24277 // don't let the internal resume be overwritten 24278 [RESUME] () { 24279 if (this[DESTROYED]) 24280 return 24281 24282 this[PAUSED] = false 24283 this[FLOWING] = true 24284 this.emit('resume') 24285 if (this.buffer.length) 24286 this[FLUSH]() 24287 else if (this[EOF]) 24288 this[MAYBE_EMIT_END]() 24289 else 24290 this.emit('drain') 24291 } 24292 24293 resume () { 24294 return this[RESUME]() 24295 } 24296 24297 pause () { 24298 this[FLOWING] = false 24299 this[PAUSED] = true 24300 } 24301 24302 get destroyed () { 24303 return this[DESTROYED] 24304 } 24305 24306 get flowing () { 24307 return this[FLOWING] 24308 } 24309 24310 get paused () { 24311 return this[PAUSED] 24312 } 24313 24314 [BUFFERPUSH] (chunk) { 24315 if (this[OBJECTMODE]) 24316 this[BUFFERLENGTH] += 1 24317 else 24318 this[BUFFERLENGTH] += chunk.length 24319 this.buffer.push(chunk) 24320 } 24321 24322 [BUFFERSHIFT] () { 24323 if (this.buffer.length) { 24324 if (this[OBJECTMODE]) 24325 this[BUFFERLENGTH] -= 1 24326 else 24327 this[BUFFERLENGTH] -= this.buffer[0].length 24328 } 24329 return this.buffer.shift() 24330 } 24331 24332 [FLUSH] (noDrain) { 24333 do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) 24334 24335 if (!noDrain && !this.buffer.length && !this[EOF]) 24336 this.emit('drain') 24337 } 24338 24339 [FLUSHCHUNK] (chunk) { 24340 return chunk ? (this.emit('data', chunk), this.flowing) : false 24341 } 24342 24343 pipe (dest, opts) { 24344 if (this[DESTROYED]) 24345 return 24346 24347 const ended = this[EMITTED_END] 24348 opts = opts || {} 24349 if (dest === proc.stdout || dest === proc.stderr) 24350 opts.end = false 24351 else 24352 opts.end = opts.end !== false 24353 opts.proxyErrors = !!opts.proxyErrors 24354 24355 // piping an ended stream ends immediately 24356 if (ended) { 24357 if (opts.end) 24358 dest.end() 24359 } else { 24360 this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) 24361 : new PipeProxyErrors(this, dest, opts)) 24362 if (this[ASYNC]) 24363 defer(() => this[RESUME]()) 24364 else 24365 this[RESUME]() 24366 } 24367 24368 return dest 24369 } 24370 24371 unpipe (dest) { 24372 const p = this.pipes.find(p => p.dest === dest) 24373 if (p) { 24374 this.pipes.splice(this.pipes.indexOf(p), 1) 24375 p.unpipe() 24376 } 24377 } 24378 24379 addListener (ev, fn) { 24380 return this.on(ev, fn) 24381 } 24382 24383 on (ev, fn) { 24384 const ret = super.on(ev, fn) 24385 if (ev === 'data' && !this.pipes.length && !this.flowing) 24386 this[RESUME]() 24387 else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) 24388 super.emit('readable') 24389 else if (isEndish(ev) && this[EMITTED_END]) { 24390 super.emit(ev) 24391 this.removeAllListeners(ev) 24392 } else if (ev === 'error' && this[EMITTED_ERROR]) { 24393 if (this[ASYNC]) 24394 defer(() => fn.call(this, this[EMITTED_ERROR])) 24395 else 24396 fn.call(this, this[EMITTED_ERROR]) 24397 } 24398 return ret 24399 } 24400 24401 get emittedEnd () { 24402 return this[EMITTED_END] 24403 } 24404 24405 [MAYBE_EMIT_END] () { 24406 if (!this[EMITTING_END] && 24407 !this[EMITTED_END] && 24408 !this[DESTROYED] && 24409 this.buffer.length === 0 && 24410 this[EOF]) { 24411 this[EMITTING_END] = true 24412 this.emit('end') 24413 this.emit('prefinish') 24414 this.emit('finish') 24415 if (this[CLOSED]) 24416 this.emit('close') 24417 this[EMITTING_END] = false 24418 } 24419 } 24420 24421 emit (ev, data, ...extra) { 24422 // error and close are only events allowed after calling destroy() 24423 if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) 24424 return 24425 else if (ev === 'data') { 24426 return !data ? false 24427 : this[ASYNC] ? defer(() => this[EMITDATA](data)) 24428 : this[EMITDATA](data) 24429 } else if (ev === 'end') { 24430 return this[EMITEND]() 24431 } else if (ev === 'close') { 24432 this[CLOSED] = true 24433 // don't emit close before 'end' and 'finish' 24434 if (!this[EMITTED_END] && !this[DESTROYED]) 24435 return 24436 const ret = super.emit('close') 24437 this.removeAllListeners('close') 24438 return ret 24439 } else if (ev === 'error') { 24440 this[EMITTED_ERROR] = data 24441 const ret = super.emit('error', data) 24442 this[MAYBE_EMIT_END]() 24443 return ret 24444 } else if (ev === 'resume') { 24445 const ret = super.emit('resume') 24446 this[MAYBE_EMIT_END]() 24447 return ret 24448 } else if (ev === 'finish' || ev === 'prefinish') { 24449 const ret = super.emit(ev) 24450 this.removeAllListeners(ev) 24451 return ret 24452 } 24453 24454 // Some other unknown event 24455 const ret = super.emit(ev, data, ...extra) 24456 this[MAYBE_EMIT_END]() 24457 return ret 24458 } 24459 24460 [EMITDATA] (data) { 24461 for (const p of this.pipes) { 24462 if (p.dest.write(data) === false) 24463 this.pause() 24464 } 24465 const ret = super.emit('data', data) 24466 this[MAYBE_EMIT_END]() 24467 return ret 24468 } 24469 24470 [EMITEND] () { 24471 if (this[EMITTED_END]) 24472 return 24473 24474 this[EMITTED_END] = true 24475 this.readable = false 24476 if (this[ASYNC]) 24477 defer(() => this[EMITEND2]()) 24478 else 24479 this[EMITEND2]() 24480 } 24481 24482 [EMITEND2] () { 24483 if (this[DECODER]) { 24484 const data = this[DECODER].end() 24485 if (data) { 24486 for (const p of this.pipes) { 24487 p.dest.write(data) 24488 } 24489 super.emit('data', data) 24490 } 24491 } 24492 24493 for (const p of this.pipes) { 24494 p.end() 24495 } 24496 const ret = super.emit('end') 24497 this.removeAllListeners('end') 24498 return ret 24499 } 24500 24501 // const all = await stream.collect() 24502 collect () { 24503 const buf = [] 24504 if (!this[OBJECTMODE]) 24505 buf.dataLength = 0 24506 // set the promise first, in case an error is raised 24507 // by triggering the flow here. 24508 const p = this.promise() 24509 this.on('data', c => { 24510 buf.push(c) 24511 if (!this[OBJECTMODE]) 24512 buf.dataLength += c.length 24513 }) 24514 return p.then(() => buf) 24515 } 24516 24517 // const data = await stream.concat() 24518 concat () { 24519 return this[OBJECTMODE] 24520 ? Promise.reject(new Error('cannot concat in objectMode')) 24521 : this.collect().then(buf => 24522 this[OBJECTMODE] 24523 ? Promise.reject(new Error('cannot concat in objectMode')) 24524 : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) 24525 } 24526 24527 // stream.promise().then(() => done, er => emitted error) 24528 promise () { 24529 return new Promise((resolve, reject) => { 24530 this.on(DESTROYED, () => reject(new Error('stream destroyed'))) 24531 this.on('error', er => reject(er)) 24532 this.on('end', () => resolve()) 24533 }) 24534 } 24535 24536 // for await (let chunk of stream) 24537 [ASYNCITERATOR] () { 24538 const next = () => { 24539 const res = this.read() 24540 if (res !== null) 24541 return Promise.resolve({ done: false, value: res }) 24542 24543 if (this[EOF]) 24544 return Promise.resolve({ done: true }) 24545 24546 let resolve = null 24547 let reject = null 24548 const onerr = er => { 24549 this.removeListener('data', ondata) 24550 this.removeListener('end', onend) 24551 reject(er) 24552 } 24553 const ondata = value => { 24554 this.removeListener('error', onerr) 24555 this.removeListener('end', onend) 24556 this.pause() 24557 resolve({ value: value, done: !!this[EOF] }) 24558 } 24559 const onend = () => { 24560 this.removeListener('error', onerr) 24561 this.removeListener('data', ondata) 24562 resolve({ done: true }) 24563 } 24564 const ondestroy = () => onerr(new Error('stream destroyed')) 24565 return new Promise((res, rej) => { 24566 reject = rej 24567 resolve = res 24568 this.once(DESTROYED, ondestroy) 24569 this.once('error', onerr) 24570 this.once('end', onend) 24571 this.once('data', ondata) 24572 }) 24573 } 24574 24575 return { next } 24576 } 24577 24578 // for (let chunk of stream) 24579 [ITERATOR] () { 24580 const next = () => { 24581 const value = this.read() 24582 const done = value === null 24583 return { value, done } 24584 } 24585 return { next } 24586 } 24587 24588 destroy (er) { 24589 if (this[DESTROYED]) { 24590 if (er) 24591 this.emit('error', er) 24592 else 24593 this.emit(DESTROYED) 24594 return this 24595 } 24596 24597 this[DESTROYED] = true 24598 24599 // throw away all buffered data, it's never coming out 24600 this.buffer.length = 0 24601 this[BUFFERLENGTH] = 0 24602 24603 if (typeof this.close === 'function' && !this[CLOSED]) 24604 this.close() 24605 24606 if (er) 24607 this.emit('error', er) 24608 else // if no error to emit, still reject pending promises 24609 this.emit(DESTROYED) 24610 24611 return this 24612 } 24613 24614 static isStream (s) { 24615 return !!s && (s instanceof Minipass || s instanceof Stream || 24616 s instanceof EE && ( 24617 typeof s.pipe === 'function' || // readable 24618 (typeof s.write === 'function' && typeof s.end === 'function') // writable 24619 )) 24620 } 24621 } 24622 24623 24624 /***/ }), 24625 24626 /***/ 9891: 24627 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 24628 24629 const Minipass = __nccwpck_require__(3392) 24630 const EE = __nccwpck_require__(2361) 24631 const isStream = s => s && s instanceof EE && ( 24632 typeof s.pipe === 'function' || // readable 24633 (typeof s.write === 'function' && typeof s.end === 'function') // writable 24634 ) 24635 24636 const _head = Symbol('_head') 24637 const _tail = Symbol('_tail') 24638 const _linkStreams = Symbol('_linkStreams') 24639 const _setHead = Symbol('_setHead') 24640 const _setTail = Symbol('_setTail') 24641 const _onError = Symbol('_onError') 24642 const _onData = Symbol('_onData') 24643 const _onEnd = Symbol('_onEnd') 24644 const _onDrain = Symbol('_onDrain') 24645 const _streams = Symbol('_streams') 24646 class Pipeline extends Minipass { 24647 constructor (opts, ...streams) { 24648 if (isStream(opts)) { 24649 streams.unshift(opts) 24650 opts = {} 24651 } 24652 24653 super(opts) 24654 this[_streams] = [] 24655 if (streams.length) 24656 this.push(...streams) 24657 } 24658 24659 [_linkStreams] (streams) { 24660 // reduce takes (left,right), and we return right to make it the 24661 // new left value. 24662 return streams.reduce((src, dest) => { 24663 src.on('error', er => dest.emit('error', er)) 24664 src.pipe(dest) 24665 return dest 24666 }) 24667 } 24668 24669 push (...streams) { 24670 this[_streams].push(...streams) 24671 if (this[_tail]) 24672 streams.unshift(this[_tail]) 24673 24674 const linkRet = this[_linkStreams](streams) 24675 24676 this[_setTail](linkRet) 24677 if (!this[_head]) 24678 this[_setHead](streams[0]) 24679 } 24680 24681 unshift (...streams) { 24682 this[_streams].unshift(...streams) 24683 if (this[_head]) 24684 streams.push(this[_head]) 24685 24686 const linkRet = this[_linkStreams](streams) 24687 this[_setHead](streams[0]) 24688 if (!this[_tail]) 24689 this[_setTail](linkRet) 24690 } 24691 24692 destroy (er) { 24693 // set fire to the whole thing. 24694 this[_streams].forEach(s => 24695 typeof s.destroy === 'function' && s.destroy()) 24696 return super.destroy(er) 24697 } 24698 24699 // readable interface -> tail 24700 [_setTail] (stream) { 24701 this[_tail] = stream 24702 stream.on('error', er => this[_onError](stream, er)) 24703 stream.on('data', chunk => this[_onData](stream, chunk)) 24704 stream.on('end', () => this[_onEnd](stream)) 24705 stream.on('finish', () => this[_onEnd](stream)) 24706 } 24707 24708 // errors proxied down the pipeline 24709 // they're considered part of the "read" interface 24710 [_onError] (stream, er) { 24711 if (stream === this[_tail]) 24712 this.emit('error', er) 24713 } 24714 [_onData] (stream, chunk) { 24715 if (stream === this[_tail]) 24716 super.write(chunk) 24717 } 24718 [_onEnd] (stream) { 24719 if (stream === this[_tail]) 24720 super.end() 24721 } 24722 pause () { 24723 super.pause() 24724 return this[_tail] && this[_tail].pause && this[_tail].pause() 24725 } 24726 24727 // NB: Minipass calls its internal private [RESUME] method during 24728 // pipe drains, to avoid hazards where stream.resume() is overridden. 24729 // Thus, we need to listen to the resume *event*, not override the 24730 // resume() method, and proxy *that* to the tail. 24731 emit (ev, ...args) { 24732 if (ev === 'resume' && this[_tail] && this[_tail].resume) 24733 this[_tail].resume() 24734 return super.emit(ev, ...args) 24735 } 24736 24737 // writable interface -> head 24738 [_setHead] (stream) { 24739 this[_head] = stream 24740 stream.on('drain', () => this[_onDrain](stream)) 24741 } 24742 [_onDrain] (stream) { 24743 if (stream === this[_head]) 24744 this.emit('drain') 24745 } 24746 write (chunk, enc, cb) { 24747 return this[_head].write(chunk, enc, cb) && 24748 (this.flowing || this.buffer.length === 0) 24749 } 24750 end (chunk, enc, cb) { 24751 this[_head].end(chunk, enc, cb) 24752 return this 24753 } 24754 } 24755 24756 module.exports = Pipeline 24757 24758 24759 /***/ }), 24760 24761 /***/ 3392: 24762 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 24763 24764 "use strict"; 24765 24766 const proc = typeof process === 'object' && process ? process : { 24767 stdout: null, 24768 stderr: null, 24769 } 24770 const EE = __nccwpck_require__(2361) 24771 const Stream = __nccwpck_require__(2781) 24772 const SD = (__nccwpck_require__(1576).StringDecoder) 24773 24774 const EOF = Symbol('EOF') 24775 const MAYBE_EMIT_END = Symbol('maybeEmitEnd') 24776 const EMITTED_END = Symbol('emittedEnd') 24777 const EMITTING_END = Symbol('emittingEnd') 24778 const EMITTED_ERROR = Symbol('emittedError') 24779 const CLOSED = Symbol('closed') 24780 const READ = Symbol('read') 24781 const FLUSH = Symbol('flush') 24782 const FLUSHCHUNK = Symbol('flushChunk') 24783 const ENCODING = Symbol('encoding') 24784 const DECODER = Symbol('decoder') 24785 const FLOWING = Symbol('flowing') 24786 const PAUSED = Symbol('paused') 24787 const RESUME = Symbol('resume') 24788 const BUFFERLENGTH = Symbol('bufferLength') 24789 const BUFFERPUSH = Symbol('bufferPush') 24790 const BUFFERSHIFT = Symbol('bufferShift') 24791 const OBJECTMODE = Symbol('objectMode') 24792 const DESTROYED = Symbol('destroyed') 24793 const EMITDATA = Symbol('emitData') 24794 const EMITEND = Symbol('emitEnd') 24795 const EMITEND2 = Symbol('emitEnd2') 24796 const ASYNC = Symbol('async') 24797 24798 const defer = fn => Promise.resolve().then(fn) 24799 24800 // TODO remove when Node v8 support drops 24801 const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' 24802 const ASYNCITERATOR = doIter && Symbol.asyncIterator 24803 || Symbol('asyncIterator not implemented') 24804 const ITERATOR = doIter && Symbol.iterator 24805 || Symbol('iterator not implemented') 24806 24807 // events that mean 'the stream is over' 24808 // these are treated specially, and re-emitted 24809 // if they are listened for after emitting. 24810 const isEndish = ev => 24811 ev === 'end' || 24812 ev === 'finish' || 24813 ev === 'prefinish' 24814 24815 const isArrayBuffer = b => b instanceof ArrayBuffer || 24816 typeof b === 'object' && 24817 b.constructor && 24818 b.constructor.name === 'ArrayBuffer' && 24819 b.byteLength >= 0 24820 24821 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) 24822 24823 class Pipe { 24824 constructor (src, dest, opts) { 24825 this.src = src 24826 this.dest = dest 24827 this.opts = opts 24828 this.ondrain = () => src[RESUME]() 24829 dest.on('drain', this.ondrain) 24830 } 24831 unpipe () { 24832 this.dest.removeListener('drain', this.ondrain) 24833 } 24834 // istanbul ignore next - only here for the prototype 24835 proxyErrors () {} 24836 end () { 24837 this.unpipe() 24838 if (this.opts.end) 24839 this.dest.end() 24840 } 24841 } 24842 24843 class PipeProxyErrors extends Pipe { 24844 unpipe () { 24845 this.src.removeListener('error', this.proxyErrors) 24846 super.unpipe() 24847 } 24848 constructor (src, dest, opts) { 24849 super(src, dest, opts) 24850 this.proxyErrors = er => dest.emit('error', er) 24851 src.on('error', this.proxyErrors) 24852 } 24853 } 24854 24855 module.exports = class Minipass extends Stream { 24856 constructor (options) { 24857 super() 24858 this[FLOWING] = false 24859 // whether we're explicitly paused 24860 this[PAUSED] = false 24861 this.pipes = [] 24862 this.buffer = [] 24863 this[OBJECTMODE] = options && options.objectMode || false 24864 if (this[OBJECTMODE]) 24865 this[ENCODING] = null 24866 else 24867 this[ENCODING] = options && options.encoding || null 24868 if (this[ENCODING] === 'buffer') 24869 this[ENCODING] = null 24870 this[ASYNC] = options && !!options.async || false 24871 this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null 24872 this[EOF] = false 24873 this[EMITTED_END] = false 24874 this[EMITTING_END] = false 24875 this[CLOSED] = false 24876 this[EMITTED_ERROR] = null 24877 this.writable = true 24878 this.readable = true 24879 this[BUFFERLENGTH] = 0 24880 this[DESTROYED] = false 24881 } 24882 24883 get bufferLength () { return this[BUFFERLENGTH] } 24884 24885 get encoding () { return this[ENCODING] } 24886 set encoding (enc) { 24887 if (this[OBJECTMODE]) 24888 throw new Error('cannot set encoding in objectMode') 24889 24890 if (this[ENCODING] && enc !== this[ENCODING] && 24891 (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) 24892 throw new Error('cannot change encoding') 24893 24894 if (this[ENCODING] !== enc) { 24895 this[DECODER] = enc ? new SD(enc) : null 24896 if (this.buffer.length) 24897 this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) 24898 } 24899 24900 this[ENCODING] = enc 24901 } 24902 24903 setEncoding (enc) { 24904 this.encoding = enc 24905 } 24906 24907 get objectMode () { return this[OBJECTMODE] } 24908 set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } 24909 24910 get ['async'] () { return this[ASYNC] } 24911 set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } 24912 24913 write (chunk, encoding, cb) { 24914 if (this[EOF]) 24915 throw new Error('write after end') 24916 24917 if (this[DESTROYED]) { 24918 this.emit('error', Object.assign( 24919 new Error('Cannot call write after a stream was destroyed'), 24920 { code: 'ERR_STREAM_DESTROYED' } 24921 )) 24922 return true 24923 } 24924 24925 if (typeof encoding === 'function') 24926 cb = encoding, encoding = 'utf8' 24927 24928 if (!encoding) 24929 encoding = 'utf8' 24930 24931 const fn = this[ASYNC] ? defer : f => f() 24932 24933 // convert array buffers and typed array views into buffers 24934 // at some point in the future, we may want to do the opposite! 24935 // leave strings and buffers as-is 24936 // anything else switches us into object mode 24937 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { 24938 if (isArrayBufferView(chunk)) 24939 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) 24940 else if (isArrayBuffer(chunk)) 24941 chunk = Buffer.from(chunk) 24942 else if (typeof chunk !== 'string') 24943 // use the setter so we throw if we have encoding set 24944 this.objectMode = true 24945 } 24946 24947 // handle object mode up front, since it's simpler 24948 // this yields better performance, fewer checks later. 24949 if (this[OBJECTMODE]) { 24950 /* istanbul ignore if - maybe impossible? */ 24951 if (this.flowing && this[BUFFERLENGTH] !== 0) 24952 this[FLUSH](true) 24953 24954 if (this.flowing) 24955 this.emit('data', chunk) 24956 else 24957 this[BUFFERPUSH](chunk) 24958 24959 if (this[BUFFERLENGTH] !== 0) 24960 this.emit('readable') 24961 24962 if (cb) 24963 fn(cb) 24964 24965 return this.flowing 24966 } 24967 24968 // at this point the chunk is a buffer or string 24969 // don't buffer it up or send it to the decoder 24970 if (!chunk.length) { 24971 if (this[BUFFERLENGTH] !== 0) 24972 this.emit('readable') 24973 if (cb) 24974 fn(cb) 24975 return this.flowing 24976 } 24977 24978 // fast-path writing strings of same encoding to a stream with 24979 // an empty buffer, skipping the buffer/decoder dance 24980 if (typeof chunk === 'string' && 24981 // unless it is a string already ready for us to use 24982 !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { 24983 chunk = Buffer.from(chunk, encoding) 24984 } 24985 24986 if (Buffer.isBuffer(chunk) && this[ENCODING]) 24987 chunk = this[DECODER].write(chunk) 24988 24989 // Note: flushing CAN potentially switch us into not-flowing mode 24990 if (this.flowing && this[BUFFERLENGTH] !== 0) 24991 this[FLUSH](true) 24992 24993 if (this.flowing) 24994 this.emit('data', chunk) 24995 else 24996 this[BUFFERPUSH](chunk) 24997 24998 if (this[BUFFERLENGTH] !== 0) 24999 this.emit('readable') 25000 25001 if (cb) 25002 fn(cb) 25003 25004 return this.flowing 25005 } 25006 25007 read (n) { 25008 if (this[DESTROYED]) 25009 return null 25010 25011 if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { 25012 this[MAYBE_EMIT_END]() 25013 return null 25014 } 25015 25016 if (this[OBJECTMODE]) 25017 n = null 25018 25019 if (this.buffer.length > 1 && !this[OBJECTMODE]) { 25020 if (this.encoding) 25021 this.buffer = [this.buffer.join('')] 25022 else 25023 this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] 25024 } 25025 25026 const ret = this[READ](n || null, this.buffer[0]) 25027 this[MAYBE_EMIT_END]() 25028 return ret 25029 } 25030 25031 [READ] (n, chunk) { 25032 if (n === chunk.length || n === null) 25033 this[BUFFERSHIFT]() 25034 else { 25035 this.buffer[0] = chunk.slice(n) 25036 chunk = chunk.slice(0, n) 25037 this[BUFFERLENGTH] -= n 25038 } 25039 25040 this.emit('data', chunk) 25041 25042 if (!this.buffer.length && !this[EOF]) 25043 this.emit('drain') 25044 25045 return chunk 25046 } 25047 25048 end (chunk, encoding, cb) { 25049 if (typeof chunk === 'function') 25050 cb = chunk, chunk = null 25051 if (typeof encoding === 'function') 25052 cb = encoding, encoding = 'utf8' 25053 if (chunk) 25054 this.write(chunk, encoding) 25055 if (cb) 25056 this.once('end', cb) 25057 this[EOF] = true 25058 this.writable = false 25059 25060 // if we haven't written anything, then go ahead and emit, 25061 // even if we're not reading. 25062 // we'll re-emit if a new 'end' listener is added anyway. 25063 // This makes MP more suitable to write-only use cases. 25064 if (this.flowing || !this[PAUSED]) 25065 this[MAYBE_EMIT_END]() 25066 return this 25067 } 25068 25069 // don't let the internal resume be overwritten 25070 [RESUME] () { 25071 if (this[DESTROYED]) 25072 return 25073 25074 this[PAUSED] = false 25075 this[FLOWING] = true 25076 this.emit('resume') 25077 if (this.buffer.length) 25078 this[FLUSH]() 25079 else if (this[EOF]) 25080 this[MAYBE_EMIT_END]() 25081 else 25082 this.emit('drain') 25083 } 25084 25085 resume () { 25086 return this[RESUME]() 25087 } 25088 25089 pause () { 25090 this[FLOWING] = false 25091 this[PAUSED] = true 25092 } 25093 25094 get destroyed () { 25095 return this[DESTROYED] 25096 } 25097 25098 get flowing () { 25099 return this[FLOWING] 25100 } 25101 25102 get paused () { 25103 return this[PAUSED] 25104 } 25105 25106 [BUFFERPUSH] (chunk) { 25107 if (this[OBJECTMODE]) 25108 this[BUFFERLENGTH] += 1 25109 else 25110 this[BUFFERLENGTH] += chunk.length 25111 this.buffer.push(chunk) 25112 } 25113 25114 [BUFFERSHIFT] () { 25115 if (this.buffer.length) { 25116 if (this[OBJECTMODE]) 25117 this[BUFFERLENGTH] -= 1 25118 else 25119 this[BUFFERLENGTH] -= this.buffer[0].length 25120 } 25121 return this.buffer.shift() 25122 } 25123 25124 [FLUSH] (noDrain) { 25125 do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) 25126 25127 if (!noDrain && !this.buffer.length && !this[EOF]) 25128 this.emit('drain') 25129 } 25130 25131 [FLUSHCHUNK] (chunk) { 25132 return chunk ? (this.emit('data', chunk), this.flowing) : false 25133 } 25134 25135 pipe (dest, opts) { 25136 if (this[DESTROYED]) 25137 return 25138 25139 const ended = this[EMITTED_END] 25140 opts = opts || {} 25141 if (dest === proc.stdout || dest === proc.stderr) 25142 opts.end = false 25143 else 25144 opts.end = opts.end !== false 25145 opts.proxyErrors = !!opts.proxyErrors 25146 25147 // piping an ended stream ends immediately 25148 if (ended) { 25149 if (opts.end) 25150 dest.end() 25151 } else { 25152 this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) 25153 : new PipeProxyErrors(this, dest, opts)) 25154 if (this[ASYNC]) 25155 defer(() => this[RESUME]()) 25156 else 25157 this[RESUME]() 25158 } 25159 25160 return dest 25161 } 25162 25163 unpipe (dest) { 25164 const p = this.pipes.find(p => p.dest === dest) 25165 if (p) { 25166 this.pipes.splice(this.pipes.indexOf(p), 1) 25167 p.unpipe() 25168 } 25169 } 25170 25171 addListener (ev, fn) { 25172 return this.on(ev, fn) 25173 } 25174 25175 on (ev, fn) { 25176 const ret = super.on(ev, fn) 25177 if (ev === 'data' && !this.pipes.length && !this.flowing) 25178 this[RESUME]() 25179 else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) 25180 super.emit('readable') 25181 else if (isEndish(ev) && this[EMITTED_END]) { 25182 super.emit(ev) 25183 this.removeAllListeners(ev) 25184 } else if (ev === 'error' && this[EMITTED_ERROR]) { 25185 if (this[ASYNC]) 25186 defer(() => fn.call(this, this[EMITTED_ERROR])) 25187 else 25188 fn.call(this, this[EMITTED_ERROR]) 25189 } 25190 return ret 25191 } 25192 25193 get emittedEnd () { 25194 return this[EMITTED_END] 25195 } 25196 25197 [MAYBE_EMIT_END] () { 25198 if (!this[EMITTING_END] && 25199 !this[EMITTED_END] && 25200 !this[DESTROYED] && 25201 this.buffer.length === 0 && 25202 this[EOF]) { 25203 this[EMITTING_END] = true 25204 this.emit('end') 25205 this.emit('prefinish') 25206 this.emit('finish') 25207 if (this[CLOSED]) 25208 this.emit('close') 25209 this[EMITTING_END] = false 25210 } 25211 } 25212 25213 emit (ev, data, ...extra) { 25214 // error and close are only events allowed after calling destroy() 25215 if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) 25216 return 25217 else if (ev === 'data') { 25218 return !data ? false 25219 : this[ASYNC] ? defer(() => this[EMITDATA](data)) 25220 : this[EMITDATA](data) 25221 } else if (ev === 'end') { 25222 return this[EMITEND]() 25223 } else if (ev === 'close') { 25224 this[CLOSED] = true 25225 // don't emit close before 'end' and 'finish' 25226 if (!this[EMITTED_END] && !this[DESTROYED]) 25227 return 25228 const ret = super.emit('close') 25229 this.removeAllListeners('close') 25230 return ret 25231 } else if (ev === 'error') { 25232 this[EMITTED_ERROR] = data 25233 const ret = super.emit('error', data) 25234 this[MAYBE_EMIT_END]() 25235 return ret 25236 } else if (ev === 'resume') { 25237 const ret = super.emit('resume') 25238 this[MAYBE_EMIT_END]() 25239 return ret 25240 } else if (ev === 'finish' || ev === 'prefinish') { 25241 const ret = super.emit(ev) 25242 this.removeAllListeners(ev) 25243 return ret 25244 } 25245 25246 // Some other unknown event 25247 const ret = super.emit(ev, data, ...extra) 25248 this[MAYBE_EMIT_END]() 25249 return ret 25250 } 25251 25252 [EMITDATA] (data) { 25253 for (const p of this.pipes) { 25254 if (p.dest.write(data) === false) 25255 this.pause() 25256 } 25257 const ret = super.emit('data', data) 25258 this[MAYBE_EMIT_END]() 25259 return ret 25260 } 25261 25262 [EMITEND] () { 25263 if (this[EMITTED_END]) 25264 return 25265 25266 this[EMITTED_END] = true 25267 this.readable = false 25268 if (this[ASYNC]) 25269 defer(() => this[EMITEND2]()) 25270 else 25271 this[EMITEND2]() 25272 } 25273 25274 [EMITEND2] () { 25275 if (this[DECODER]) { 25276 const data = this[DECODER].end() 25277 if (data) { 25278 for (const p of this.pipes) { 25279 p.dest.write(data) 25280 } 25281 super.emit('data', data) 25282 } 25283 } 25284 25285 for (const p of this.pipes) { 25286 p.end() 25287 } 25288 const ret = super.emit('end') 25289 this.removeAllListeners('end') 25290 return ret 25291 } 25292 25293 // const all = await stream.collect() 25294 collect () { 25295 const buf = [] 25296 if (!this[OBJECTMODE]) 25297 buf.dataLength = 0 25298 // set the promise first, in case an error is raised 25299 // by triggering the flow here. 25300 const p = this.promise() 25301 this.on('data', c => { 25302 buf.push(c) 25303 if (!this[OBJECTMODE]) 25304 buf.dataLength += c.length 25305 }) 25306 return p.then(() => buf) 25307 } 25308 25309 // const data = await stream.concat() 25310 concat () { 25311 return this[OBJECTMODE] 25312 ? Promise.reject(new Error('cannot concat in objectMode')) 25313 : this.collect().then(buf => 25314 this[OBJECTMODE] 25315 ? Promise.reject(new Error('cannot concat in objectMode')) 25316 : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) 25317 } 25318 25319 // stream.promise().then(() => done, er => emitted error) 25320 promise () { 25321 return new Promise((resolve, reject) => { 25322 this.on(DESTROYED, () => reject(new Error('stream destroyed'))) 25323 this.on('error', er => reject(er)) 25324 this.on('end', () => resolve()) 25325 }) 25326 } 25327 25328 // for await (let chunk of stream) 25329 [ASYNCITERATOR] () { 25330 const next = () => { 25331 const res = this.read() 25332 if (res !== null) 25333 return Promise.resolve({ done: false, value: res }) 25334 25335 if (this[EOF]) 25336 return Promise.resolve({ done: true }) 25337 25338 let resolve = null 25339 let reject = null 25340 const onerr = er => { 25341 this.removeListener('data', ondata) 25342 this.removeListener('end', onend) 25343 reject(er) 25344 } 25345 const ondata = value => { 25346 this.removeListener('error', onerr) 25347 this.removeListener('end', onend) 25348 this.pause() 25349 resolve({ value: value, done: !!this[EOF] }) 25350 } 25351 const onend = () => { 25352 this.removeListener('error', onerr) 25353 this.removeListener('data', ondata) 25354 resolve({ done: true }) 25355 } 25356 const ondestroy = () => onerr(new Error('stream destroyed')) 25357 return new Promise((res, rej) => { 25358 reject = rej 25359 resolve = res 25360 this.once(DESTROYED, ondestroy) 25361 this.once('error', onerr) 25362 this.once('end', onend) 25363 this.once('data', ondata) 25364 }) 25365 } 25366 25367 return { next } 25368 } 25369 25370 // for (let chunk of stream) 25371 [ITERATOR] () { 25372 const next = () => { 25373 const value = this.read() 25374 const done = value === null 25375 return { value, done } 25376 } 25377 return { next } 25378 } 25379 25380 destroy (er) { 25381 if (this[DESTROYED]) { 25382 if (er) 25383 this.emit('error', er) 25384 else 25385 this.emit(DESTROYED) 25386 return this 25387 } 25388 25389 this[DESTROYED] = true 25390 25391 // throw away all buffered data, it's never coming out 25392 this.buffer.length = 0 25393 this[BUFFERLENGTH] = 0 25394 25395 if (typeof this.close === 'function' && !this[CLOSED]) 25396 this.close() 25397 25398 if (er) 25399 this.emit('error', er) 25400 else // if no error to emit, still reject pending promises 25401 this.emit(DESTROYED) 25402 25403 return this 25404 } 25405 25406 static isStream (s) { 25407 return !!s && (s instanceof Minipass || s instanceof Stream || 25408 s instanceof EE && ( 25409 typeof s.pipe === 'function' || // readable 25410 (typeof s.write === 'function' && typeof s.end === 'function') // writable 25411 )) 25412 } 25413 } 25414 25415 25416 /***/ }), 25417 25418 /***/ 5952: 25419 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 25420 25421 const Minipass = __nccwpck_require__(8024) 25422 25423 class SizeError extends Error { 25424 constructor (found, expect) { 25425 super(`Bad data size: expected ${expect} bytes, but got ${found}`) 25426 this.expect = expect 25427 this.found = found 25428 this.code = 'EBADSIZE' 25429 Error.captureStackTrace(this, this.constructor) 25430 } 25431 get name () { 25432 return 'SizeError' 25433 } 25434 } 25435 25436 class MinipassSized extends Minipass { 25437 constructor (options = {}) { 25438 super(options) 25439 25440 if (options.objectMode) 25441 throw new TypeError(`${ 25442 this.constructor.name 25443 } streams only work with string and buffer data`) 25444 25445 this.found = 0 25446 this.expect = options.size 25447 if (typeof this.expect !== 'number' || 25448 this.expect > Number.MAX_SAFE_INTEGER || 25449 isNaN(this.expect) || 25450 this.expect < 0 || 25451 !isFinite(this.expect) || 25452 this.expect !== Math.floor(this.expect)) 25453 throw new Error('invalid expected size: ' + this.expect) 25454 } 25455 25456 write (chunk, encoding, cb) { 25457 const buffer = Buffer.isBuffer(chunk) ? chunk 25458 : typeof chunk === 'string' ? 25459 Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8') 25460 : chunk 25461 25462 if (!Buffer.isBuffer(buffer)) { 25463 this.emit('error', new TypeError(`${ 25464 this.constructor.name 25465 } streams only work with string and buffer data`)) 25466 return false 25467 } 25468 25469 this.found += buffer.length 25470 if (this.found > this.expect) 25471 this.emit('error', new SizeError(this.found, this.expect)) 25472 25473 return super.write(chunk, encoding, cb) 25474 } 25475 25476 emit (ev, ...data) { 25477 if (ev === 'end') { 25478 if (this.found !== this.expect) 25479 this.emit('error', new SizeError(this.found, this.expect)) 25480 } 25481 return super.emit(ev, ...data) 25482 } 25483 } 25484 25485 MinipassSized.SizeError = SizeError 25486 25487 module.exports = MinipassSized 25488 25489 25490 /***/ }), 25491 25492 /***/ 8024: 25493 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 25494 25495 "use strict"; 25496 25497 const proc = typeof process === 'object' && process ? process : { 25498 stdout: null, 25499 stderr: null, 25500 } 25501 const EE = __nccwpck_require__(2361) 25502 const Stream = __nccwpck_require__(2781) 25503 const SD = (__nccwpck_require__(1576).StringDecoder) 25504 25505 const EOF = Symbol('EOF') 25506 const MAYBE_EMIT_END = Symbol('maybeEmitEnd') 25507 const EMITTED_END = Symbol('emittedEnd') 25508 const EMITTING_END = Symbol('emittingEnd') 25509 const EMITTED_ERROR = Symbol('emittedError') 25510 const CLOSED = Symbol('closed') 25511 const READ = Symbol('read') 25512 const FLUSH = Symbol('flush') 25513 const FLUSHCHUNK = Symbol('flushChunk') 25514 const ENCODING = Symbol('encoding') 25515 const DECODER = Symbol('decoder') 25516 const FLOWING = Symbol('flowing') 25517 const PAUSED = Symbol('paused') 25518 const RESUME = Symbol('resume') 25519 const BUFFERLENGTH = Symbol('bufferLength') 25520 const BUFFERPUSH = Symbol('bufferPush') 25521 const BUFFERSHIFT = Symbol('bufferShift') 25522 const OBJECTMODE = Symbol('objectMode') 25523 const DESTROYED = Symbol('destroyed') 25524 const EMITDATA = Symbol('emitData') 25525 const EMITEND = Symbol('emitEnd') 25526 const EMITEND2 = Symbol('emitEnd2') 25527 const ASYNC = Symbol('async') 25528 25529 const defer = fn => Promise.resolve().then(fn) 25530 25531 // TODO remove when Node v8 support drops 25532 const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' 25533 const ASYNCITERATOR = doIter && Symbol.asyncIterator 25534 || Symbol('asyncIterator not implemented') 25535 const ITERATOR = doIter && Symbol.iterator 25536 || Symbol('iterator not implemented') 25537 25538 // events that mean 'the stream is over' 25539 // these are treated specially, and re-emitted 25540 // if they are listened for after emitting. 25541 const isEndish = ev => 25542 ev === 'end' || 25543 ev === 'finish' || 25544 ev === 'prefinish' 25545 25546 const isArrayBuffer = b => b instanceof ArrayBuffer || 25547 typeof b === 'object' && 25548 b.constructor && 25549 b.constructor.name === 'ArrayBuffer' && 25550 b.byteLength >= 0 25551 25552 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) 25553 25554 class Pipe { 25555 constructor (src, dest, opts) { 25556 this.src = src 25557 this.dest = dest 25558 this.opts = opts 25559 this.ondrain = () => src[RESUME]() 25560 dest.on('drain', this.ondrain) 25561 } 25562 unpipe () { 25563 this.dest.removeListener('drain', this.ondrain) 25564 } 25565 // istanbul ignore next - only here for the prototype 25566 proxyErrors () {} 25567 end () { 25568 this.unpipe() 25569 if (this.opts.end) 25570 this.dest.end() 25571 } 25572 } 25573 25574 class PipeProxyErrors extends Pipe { 25575 unpipe () { 25576 this.src.removeListener('error', this.proxyErrors) 25577 super.unpipe() 25578 } 25579 constructor (src, dest, opts) { 25580 super(src, dest, opts) 25581 this.proxyErrors = er => dest.emit('error', er) 25582 src.on('error', this.proxyErrors) 25583 } 25584 } 25585 25586 module.exports = class Minipass extends Stream { 25587 constructor (options) { 25588 super() 25589 this[FLOWING] = false 25590 // whether we're explicitly paused 25591 this[PAUSED] = false 25592 this.pipes = [] 25593 this.buffer = [] 25594 this[OBJECTMODE] = options && options.objectMode || false 25595 if (this[OBJECTMODE]) 25596 this[ENCODING] = null 25597 else 25598 this[ENCODING] = options && options.encoding || null 25599 if (this[ENCODING] === 'buffer') 25600 this[ENCODING] = null 25601 this[ASYNC] = options && !!options.async || false 25602 this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null 25603 this[EOF] = false 25604 this[EMITTED_END] = false 25605 this[EMITTING_END] = false 25606 this[CLOSED] = false 25607 this[EMITTED_ERROR] = null 25608 this.writable = true 25609 this.readable = true 25610 this[BUFFERLENGTH] = 0 25611 this[DESTROYED] = false 25612 } 25613 25614 get bufferLength () { return this[BUFFERLENGTH] } 25615 25616 get encoding () { return this[ENCODING] } 25617 set encoding (enc) { 25618 if (this[OBJECTMODE]) 25619 throw new Error('cannot set encoding in objectMode') 25620 25621 if (this[ENCODING] && enc !== this[ENCODING] && 25622 (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) 25623 throw new Error('cannot change encoding') 25624 25625 if (this[ENCODING] !== enc) { 25626 this[DECODER] = enc ? new SD(enc) : null 25627 if (this.buffer.length) 25628 this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) 25629 } 25630 25631 this[ENCODING] = enc 25632 } 25633 25634 setEncoding (enc) { 25635 this.encoding = enc 25636 } 25637 25638 get objectMode () { return this[OBJECTMODE] } 25639 set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } 25640 25641 get ['async'] () { return this[ASYNC] } 25642 set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } 25643 25644 write (chunk, encoding, cb) { 25645 if (this[EOF]) 25646 throw new Error('write after end') 25647 25648 if (this[DESTROYED]) { 25649 this.emit('error', Object.assign( 25650 new Error('Cannot call write after a stream was destroyed'), 25651 { code: 'ERR_STREAM_DESTROYED' } 25652 )) 25653 return true 25654 } 25655 25656 if (typeof encoding === 'function') 25657 cb = encoding, encoding = 'utf8' 25658 25659 if (!encoding) 25660 encoding = 'utf8' 25661 25662 const fn = this[ASYNC] ? defer : f => f() 25663 25664 // convert array buffers and typed array views into buffers 25665 // at some point in the future, we may want to do the opposite! 25666 // leave strings and buffers as-is 25667 // anything else switches us into object mode 25668 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { 25669 if (isArrayBufferView(chunk)) 25670 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) 25671 else if (isArrayBuffer(chunk)) 25672 chunk = Buffer.from(chunk) 25673 else if (typeof chunk !== 'string') 25674 // use the setter so we throw if we have encoding set 25675 this.objectMode = true 25676 } 25677 25678 // handle object mode up front, since it's simpler 25679 // this yields better performance, fewer checks later. 25680 if (this[OBJECTMODE]) { 25681 /* istanbul ignore if - maybe impossible? */ 25682 if (this.flowing && this[BUFFERLENGTH] !== 0) 25683 this[FLUSH](true) 25684 25685 if (this.flowing) 25686 this.emit('data', chunk) 25687 else 25688 this[BUFFERPUSH](chunk) 25689 25690 if (this[BUFFERLENGTH] !== 0) 25691 this.emit('readable') 25692 25693 if (cb) 25694 fn(cb) 25695 25696 return this.flowing 25697 } 25698 25699 // at this point the chunk is a buffer or string 25700 // don't buffer it up or send it to the decoder 25701 if (!chunk.length) { 25702 if (this[BUFFERLENGTH] !== 0) 25703 this.emit('readable') 25704 if (cb) 25705 fn(cb) 25706 return this.flowing 25707 } 25708 25709 // fast-path writing strings of same encoding to a stream with 25710 // an empty buffer, skipping the buffer/decoder dance 25711 if (typeof chunk === 'string' && 25712 // unless it is a string already ready for us to use 25713 !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { 25714 chunk = Buffer.from(chunk, encoding) 25715 } 25716 25717 if (Buffer.isBuffer(chunk) && this[ENCODING]) 25718 chunk = this[DECODER].write(chunk) 25719 25720 // Note: flushing CAN potentially switch us into not-flowing mode 25721 if (this.flowing && this[BUFFERLENGTH] !== 0) 25722 this[FLUSH](true) 25723 25724 if (this.flowing) 25725 this.emit('data', chunk) 25726 else 25727 this[BUFFERPUSH](chunk) 25728 25729 if (this[BUFFERLENGTH] !== 0) 25730 this.emit('readable') 25731 25732 if (cb) 25733 fn(cb) 25734 25735 return this.flowing 25736 } 25737 25738 read (n) { 25739 if (this[DESTROYED]) 25740 return null 25741 25742 if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { 25743 this[MAYBE_EMIT_END]() 25744 return null 25745 } 25746 25747 if (this[OBJECTMODE]) 25748 n = null 25749 25750 if (this.buffer.length > 1 && !this[OBJECTMODE]) { 25751 if (this.encoding) 25752 this.buffer = [this.buffer.join('')] 25753 else 25754 this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] 25755 } 25756 25757 const ret = this[READ](n || null, this.buffer[0]) 25758 this[MAYBE_EMIT_END]() 25759 return ret 25760 } 25761 25762 [READ] (n, chunk) { 25763 if (n === chunk.length || n === null) 25764 this[BUFFERSHIFT]() 25765 else { 25766 this.buffer[0] = chunk.slice(n) 25767 chunk = chunk.slice(0, n) 25768 this[BUFFERLENGTH] -= n 25769 } 25770 25771 this.emit('data', chunk) 25772 25773 if (!this.buffer.length && !this[EOF]) 25774 this.emit('drain') 25775 25776 return chunk 25777 } 25778 25779 end (chunk, encoding, cb) { 25780 if (typeof chunk === 'function') 25781 cb = chunk, chunk = null 25782 if (typeof encoding === 'function') 25783 cb = encoding, encoding = 'utf8' 25784 if (chunk) 25785 this.write(chunk, encoding) 25786 if (cb) 25787 this.once('end', cb) 25788 this[EOF] = true 25789 this.writable = false 25790 25791 // if we haven't written anything, then go ahead and emit, 25792 // even if we're not reading. 25793 // we'll re-emit if a new 'end' listener is added anyway. 25794 // This makes MP more suitable to write-only use cases. 25795 if (this.flowing || !this[PAUSED]) 25796 this[MAYBE_EMIT_END]() 25797 return this 25798 } 25799 25800 // don't let the internal resume be overwritten 25801 [RESUME] () { 25802 if (this[DESTROYED]) 25803 return 25804 25805 this[PAUSED] = false 25806 this[FLOWING] = true 25807 this.emit('resume') 25808 if (this.buffer.length) 25809 this[FLUSH]() 25810 else if (this[EOF]) 25811 this[MAYBE_EMIT_END]() 25812 else 25813 this.emit('drain') 25814 } 25815 25816 resume () { 25817 return this[RESUME]() 25818 } 25819 25820 pause () { 25821 this[FLOWING] = false 25822 this[PAUSED] = true 25823 } 25824 25825 get destroyed () { 25826 return this[DESTROYED] 25827 } 25828 25829 get flowing () { 25830 return this[FLOWING] 25831 } 25832 25833 get paused () { 25834 return this[PAUSED] 25835 } 25836 25837 [BUFFERPUSH] (chunk) { 25838 if (this[OBJECTMODE]) 25839 this[BUFFERLENGTH] += 1 25840 else 25841 this[BUFFERLENGTH] += chunk.length 25842 this.buffer.push(chunk) 25843 } 25844 25845 [BUFFERSHIFT] () { 25846 if (this.buffer.length) { 25847 if (this[OBJECTMODE]) 25848 this[BUFFERLENGTH] -= 1 25849 else 25850 this[BUFFERLENGTH] -= this.buffer[0].length 25851 } 25852 return this.buffer.shift() 25853 } 25854 25855 [FLUSH] (noDrain) { 25856 do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) 25857 25858 if (!noDrain && !this.buffer.length && !this[EOF]) 25859 this.emit('drain') 25860 } 25861 25862 [FLUSHCHUNK] (chunk) { 25863 return chunk ? (this.emit('data', chunk), this.flowing) : false 25864 } 25865 25866 pipe (dest, opts) { 25867 if (this[DESTROYED]) 25868 return 25869 25870 const ended = this[EMITTED_END] 25871 opts = opts || {} 25872 if (dest === proc.stdout || dest === proc.stderr) 25873 opts.end = false 25874 else 25875 opts.end = opts.end !== false 25876 opts.proxyErrors = !!opts.proxyErrors 25877 25878 // piping an ended stream ends immediately 25879 if (ended) { 25880 if (opts.end) 25881 dest.end() 25882 } else { 25883 this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) 25884 : new PipeProxyErrors(this, dest, opts)) 25885 if (this[ASYNC]) 25886 defer(() => this[RESUME]()) 25887 else 25888 this[RESUME]() 25889 } 25890 25891 return dest 25892 } 25893 25894 unpipe (dest) { 25895 const p = this.pipes.find(p => p.dest === dest) 25896 if (p) { 25897 this.pipes.splice(this.pipes.indexOf(p), 1) 25898 p.unpipe() 25899 } 25900 } 25901 25902 addListener (ev, fn) { 25903 return this.on(ev, fn) 25904 } 25905 25906 on (ev, fn) { 25907 const ret = super.on(ev, fn) 25908 if (ev === 'data' && !this.pipes.length && !this.flowing) 25909 this[RESUME]() 25910 else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) 25911 super.emit('readable') 25912 else if (isEndish(ev) && this[EMITTED_END]) { 25913 super.emit(ev) 25914 this.removeAllListeners(ev) 25915 } else if (ev === 'error' && this[EMITTED_ERROR]) { 25916 if (this[ASYNC]) 25917 defer(() => fn.call(this, this[EMITTED_ERROR])) 25918 else 25919 fn.call(this, this[EMITTED_ERROR]) 25920 } 25921 return ret 25922 } 25923 25924 get emittedEnd () { 25925 return this[EMITTED_END] 25926 } 25927 25928 [MAYBE_EMIT_END] () { 25929 if (!this[EMITTING_END] && 25930 !this[EMITTED_END] && 25931 !this[DESTROYED] && 25932 this.buffer.length === 0 && 25933 this[EOF]) { 25934 this[EMITTING_END] = true 25935 this.emit('end') 25936 this.emit('prefinish') 25937 this.emit('finish') 25938 if (this[CLOSED]) 25939 this.emit('close') 25940 this[EMITTING_END] = false 25941 } 25942 } 25943 25944 emit (ev, data, ...extra) { 25945 // error and close are only events allowed after calling destroy() 25946 if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) 25947 return 25948 else if (ev === 'data') { 25949 return !data ? false 25950 : this[ASYNC] ? defer(() => this[EMITDATA](data)) 25951 : this[EMITDATA](data) 25952 } else if (ev === 'end') { 25953 return this[EMITEND]() 25954 } else if (ev === 'close') { 25955 this[CLOSED] = true 25956 // don't emit close before 'end' and 'finish' 25957 if (!this[EMITTED_END] && !this[DESTROYED]) 25958 return 25959 const ret = super.emit('close') 25960 this.removeAllListeners('close') 25961 return ret 25962 } else if (ev === 'error') { 25963 this[EMITTED_ERROR] = data 25964 const ret = super.emit('error', data) 25965 this[MAYBE_EMIT_END]() 25966 return ret 25967 } else if (ev === 'resume') { 25968 const ret = super.emit('resume') 25969 this[MAYBE_EMIT_END]() 25970 return ret 25971 } else if (ev === 'finish' || ev === 'prefinish') { 25972 const ret = super.emit(ev) 25973 this.removeAllListeners(ev) 25974 return ret 25975 } 25976 25977 // Some other unknown event 25978 const ret = super.emit(ev, data, ...extra) 25979 this[MAYBE_EMIT_END]() 25980 return ret 25981 } 25982 25983 [EMITDATA] (data) { 25984 for (const p of this.pipes) { 25985 if (p.dest.write(data) === false) 25986 this.pause() 25987 } 25988 const ret = super.emit('data', data) 25989 this[MAYBE_EMIT_END]() 25990 return ret 25991 } 25992 25993 [EMITEND] () { 25994 if (this[EMITTED_END]) 25995 return 25996 25997 this[EMITTED_END] = true 25998 this.readable = false 25999 if (this[ASYNC]) 26000 defer(() => this[EMITEND2]()) 26001 else 26002 this[EMITEND2]() 26003 } 26004 26005 [EMITEND2] () { 26006 if (this[DECODER]) { 26007 const data = this[DECODER].end() 26008 if (data) { 26009 for (const p of this.pipes) { 26010 p.dest.write(data) 26011 } 26012 super.emit('data', data) 26013 } 26014 } 26015 26016 for (const p of this.pipes) { 26017 p.end() 26018 } 26019 const ret = super.emit('end') 26020 this.removeAllListeners('end') 26021 return ret 26022 } 26023 26024 // const all = await stream.collect() 26025 collect () { 26026 const buf = [] 26027 if (!this[OBJECTMODE]) 26028 buf.dataLength = 0 26029 // set the promise first, in case an error is raised 26030 // by triggering the flow here. 26031 const p = this.promise() 26032 this.on('data', c => { 26033 buf.push(c) 26034 if (!this[OBJECTMODE]) 26035 buf.dataLength += c.length 26036 }) 26037 return p.then(() => buf) 26038 } 26039 26040 // const data = await stream.concat() 26041 concat () { 26042 return this[OBJECTMODE] 26043 ? Promise.reject(new Error('cannot concat in objectMode')) 26044 : this.collect().then(buf => 26045 this[OBJECTMODE] 26046 ? Promise.reject(new Error('cannot concat in objectMode')) 26047 : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) 26048 } 26049 26050 // stream.promise().then(() => done, er => emitted error) 26051 promise () { 26052 return new Promise((resolve, reject) => { 26053 this.on(DESTROYED, () => reject(new Error('stream destroyed'))) 26054 this.on('error', er => reject(er)) 26055 this.on('end', () => resolve()) 26056 }) 26057 } 26058 26059 // for await (let chunk of stream) 26060 [ASYNCITERATOR] () { 26061 const next = () => { 26062 const res = this.read() 26063 if (res !== null) 26064 return Promise.resolve({ done: false, value: res }) 26065 26066 if (this[EOF]) 26067 return Promise.resolve({ done: true }) 26068 26069 let resolve = null 26070 let reject = null 26071 const onerr = er => { 26072 this.removeListener('data', ondata) 26073 this.removeListener('end', onend) 26074 reject(er) 26075 } 26076 const ondata = value => { 26077 this.removeListener('error', onerr) 26078 this.removeListener('end', onend) 26079 this.pause() 26080 resolve({ value: value, done: !!this[EOF] }) 26081 } 26082 const onend = () => { 26083 this.removeListener('error', onerr) 26084 this.removeListener('data', ondata) 26085 resolve({ done: true }) 26086 } 26087 const ondestroy = () => onerr(new Error('stream destroyed')) 26088 return new Promise((res, rej) => { 26089 reject = rej 26090 resolve = res 26091 this.once(DESTROYED, ondestroy) 26092 this.once('error', onerr) 26093 this.once('end', onend) 26094 this.once('data', ondata) 26095 }) 26096 } 26097 26098 return { next } 26099 } 26100 26101 // for (let chunk of stream) 26102 [ITERATOR] () { 26103 const next = () => { 26104 const value = this.read() 26105 const done = value === null 26106 return { value, done } 26107 } 26108 return { next } 26109 } 26110 26111 destroy (er) { 26112 if (this[DESTROYED]) { 26113 if (er) 26114 this.emit('error', er) 26115 else 26116 this.emit(DESTROYED) 26117 return this 26118 } 26119 26120 this[DESTROYED] = true 26121 26122 // throw away all buffered data, it's never coming out 26123 this.buffer.length = 0 26124 this[BUFFERLENGTH] = 0 26125 26126 if (typeof this.close === 'function' && !this[CLOSED]) 26127 this.close() 26128 26129 if (er) 26130 this.emit('error', er) 26131 else // if no error to emit, still reject pending promises 26132 this.emit(DESTROYED) 26133 26134 return this 26135 } 26136 26137 static isStream (s) { 26138 return !!s && (s instanceof Minipass || s instanceof Stream || 26139 s instanceof EE && ( 26140 typeof s.pipe === 'function' || // readable 26141 (typeof s.write === 'function' && typeof s.end === 'function') // writable 26142 )) 26143 } 26144 } 26145 26146 26147 /***/ }), 26148 26149 /***/ 6769: 26150 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 26151 26152 // Update with any zlib constants that are added or changed in the future. 26153 // Node v6 didn't export this, so we just hard code the version and rely 26154 // on all the other hard-coded values from zlib v4736. When node v6 26155 // support drops, we can just export the realZlibConstants object. 26156 const realZlibConstants = (__nccwpck_require__(9796).constants) || 26157 /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } 26158 26159 module.exports = Object.freeze(Object.assign(Object.create(null), { 26160 Z_NO_FLUSH: 0, 26161 Z_PARTIAL_FLUSH: 1, 26162 Z_SYNC_FLUSH: 2, 26163 Z_FULL_FLUSH: 3, 26164 Z_FINISH: 4, 26165 Z_BLOCK: 5, 26166 Z_OK: 0, 26167 Z_STREAM_END: 1, 26168 Z_NEED_DICT: 2, 26169 Z_ERRNO: -1, 26170 Z_STREAM_ERROR: -2, 26171 Z_DATA_ERROR: -3, 26172 Z_MEM_ERROR: -4, 26173 Z_BUF_ERROR: -5, 26174 Z_VERSION_ERROR: -6, 26175 Z_NO_COMPRESSION: 0, 26176 Z_BEST_SPEED: 1, 26177 Z_BEST_COMPRESSION: 9, 26178 Z_DEFAULT_COMPRESSION: -1, 26179 Z_FILTERED: 1, 26180 Z_HUFFMAN_ONLY: 2, 26181 Z_RLE: 3, 26182 Z_FIXED: 4, 26183 Z_DEFAULT_STRATEGY: 0, 26184 DEFLATE: 1, 26185 INFLATE: 2, 26186 GZIP: 3, 26187 GUNZIP: 4, 26188 DEFLATERAW: 5, 26189 INFLATERAW: 6, 26190 UNZIP: 7, 26191 BROTLI_DECODE: 8, 26192 BROTLI_ENCODE: 9, 26193 Z_MIN_WINDOWBITS: 8, 26194 Z_MAX_WINDOWBITS: 15, 26195 Z_DEFAULT_WINDOWBITS: 15, 26196 Z_MIN_CHUNK: 64, 26197 Z_MAX_CHUNK: Infinity, 26198 Z_DEFAULT_CHUNK: 16384, 26199 Z_MIN_MEMLEVEL: 1, 26200 Z_MAX_MEMLEVEL: 9, 26201 Z_DEFAULT_MEMLEVEL: 8, 26202 Z_MIN_LEVEL: -1, 26203 Z_MAX_LEVEL: 9, 26204 Z_DEFAULT_LEVEL: -1, 26205 BROTLI_OPERATION_PROCESS: 0, 26206 BROTLI_OPERATION_FLUSH: 1, 26207 BROTLI_OPERATION_FINISH: 2, 26208 BROTLI_OPERATION_EMIT_METADATA: 3, 26209 BROTLI_MODE_GENERIC: 0, 26210 BROTLI_MODE_TEXT: 1, 26211 BROTLI_MODE_FONT: 2, 26212 BROTLI_DEFAULT_MODE: 0, 26213 BROTLI_MIN_QUALITY: 0, 26214 BROTLI_MAX_QUALITY: 11, 26215 BROTLI_DEFAULT_QUALITY: 11, 26216 BROTLI_MIN_WINDOW_BITS: 10, 26217 BROTLI_MAX_WINDOW_BITS: 24, 26218 BROTLI_LARGE_MAX_WINDOW_BITS: 30, 26219 BROTLI_DEFAULT_WINDOW: 22, 26220 BROTLI_MIN_INPUT_BLOCK_BITS: 16, 26221 BROTLI_MAX_INPUT_BLOCK_BITS: 24, 26222 BROTLI_PARAM_MODE: 0, 26223 BROTLI_PARAM_QUALITY: 1, 26224 BROTLI_PARAM_LGWIN: 2, 26225 BROTLI_PARAM_LGBLOCK: 3, 26226 BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, 26227 BROTLI_PARAM_SIZE_HINT: 5, 26228 BROTLI_PARAM_LARGE_WINDOW: 6, 26229 BROTLI_PARAM_NPOSTFIX: 7, 26230 BROTLI_PARAM_NDIRECT: 8, 26231 BROTLI_DECODER_RESULT_ERROR: 0, 26232 BROTLI_DECODER_RESULT_SUCCESS: 1, 26233 BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, 26234 BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, 26235 BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, 26236 BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, 26237 BROTLI_DECODER_NO_ERROR: 0, 26238 BROTLI_DECODER_SUCCESS: 1, 26239 BROTLI_DECODER_NEEDS_MORE_INPUT: 2, 26240 BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, 26241 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, 26242 BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, 26243 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, 26244 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, 26245 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, 26246 BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, 26247 BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, 26248 BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, 26249 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, 26250 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, 26251 BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, 26252 BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, 26253 BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, 26254 BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, 26255 BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, 26256 BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, 26257 BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, 26258 BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, 26259 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, 26260 BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, 26261 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, 26262 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, 26263 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, 26264 BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, 26265 BROTLI_DECODER_ERROR_UNREACHABLE: -31, 26266 }, realZlibConstants)) 26267 26268 26269 /***/ }), 26270 26271 /***/ 3486: 26272 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 26273 26274 "use strict"; 26275 26276 26277 const assert = __nccwpck_require__(9491) 26278 const Buffer = (__nccwpck_require__(4300).Buffer) 26279 const realZlib = __nccwpck_require__(9796) 26280 26281 const constants = exports.constants = __nccwpck_require__(6769) 26282 const Minipass = __nccwpck_require__(7557) 26283 26284 const OriginalBufferConcat = Buffer.concat 26285 26286 const _superWrite = Symbol('_superWrite') 26287 class ZlibError extends Error { 26288 constructor (err) { 26289 super('zlib: ' + err.message) 26290 this.code = err.code 26291 this.errno = err.errno 26292 /* istanbul ignore if */ 26293 if (!this.code) 26294 this.code = 'ZLIB_ERROR' 26295 26296 this.message = 'zlib: ' + err.message 26297 Error.captureStackTrace(this, this.constructor) 26298 } 26299 26300 get name () { 26301 return 'ZlibError' 26302 } 26303 } 26304 26305 // the Zlib class they all inherit from 26306 // This thing manages the queue of requests, and returns 26307 // true or false if there is anything in the queue when 26308 // you call the .write() method. 26309 const _opts = Symbol('opts') 26310 const _flushFlag = Symbol('flushFlag') 26311 const _finishFlushFlag = Symbol('finishFlushFlag') 26312 const _fullFlushFlag = Symbol('fullFlushFlag') 26313 const _handle = Symbol('handle') 26314 const _onError = Symbol('onError') 26315 const _sawError = Symbol('sawError') 26316 const _level = Symbol('level') 26317 const _strategy = Symbol('strategy') 26318 const _ended = Symbol('ended') 26319 const _defaultFullFlush = Symbol('_defaultFullFlush') 26320 26321 class ZlibBase extends Minipass { 26322 constructor (opts, mode) { 26323 if (!opts || typeof opts !== 'object') 26324 throw new TypeError('invalid options for ZlibBase constructor') 26325 26326 super(opts) 26327 this[_sawError] = false 26328 this[_ended] = false 26329 this[_opts] = opts 26330 26331 this[_flushFlag] = opts.flush 26332 this[_finishFlushFlag] = opts.finishFlush 26333 // this will throw if any options are invalid for the class selected 26334 try { 26335 this[_handle] = new realZlib[mode](opts) 26336 } catch (er) { 26337 // make sure that all errors get decorated properly 26338 throw new ZlibError(er) 26339 } 26340 26341 this[_onError] = (err) => { 26342 // no sense raising multiple errors, since we abort on the first one. 26343 if (this[_sawError]) 26344 return 26345 26346 this[_sawError] = true 26347 26348 // there is no way to cleanly recover. 26349 // continuing only obscures problems. 26350 this.close() 26351 this.emit('error', err) 26352 } 26353 26354 this[_handle].on('error', er => this[_onError](new ZlibError(er))) 26355 this.once('end', () => this.close) 26356 } 26357 26358 close () { 26359 if (this[_handle]) { 26360 this[_handle].close() 26361 this[_handle] = null 26362 this.emit('close') 26363 } 26364 } 26365 26366 reset () { 26367 if (!this[_sawError]) { 26368 assert(this[_handle], 'zlib binding closed') 26369 return this[_handle].reset() 26370 } 26371 } 26372 26373 flush (flushFlag) { 26374 if (this.ended) 26375 return 26376 26377 if (typeof flushFlag !== 'number') 26378 flushFlag = this[_fullFlushFlag] 26379 this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) 26380 } 26381 26382 end (chunk, encoding, cb) { 26383 if (chunk) 26384 this.write(chunk, encoding) 26385 this.flush(this[_finishFlushFlag]) 26386 this[_ended] = true 26387 return super.end(null, null, cb) 26388 } 26389 26390 get ended () { 26391 return this[_ended] 26392 } 26393 26394 write (chunk, encoding, cb) { 26395 // process the chunk using the sync process 26396 // then super.write() all the outputted chunks 26397 if (typeof encoding === 'function') 26398 cb = encoding, encoding = 'utf8' 26399 26400 if (typeof chunk === 'string') 26401 chunk = Buffer.from(chunk, encoding) 26402 26403 if (this[_sawError]) 26404 return 26405 assert(this[_handle], 'zlib binding closed') 26406 26407 // _processChunk tries to .close() the native handle after it's done, so we 26408 // intercept that by temporarily making it a no-op. 26409 const nativeHandle = this[_handle]._handle 26410 const originalNativeClose = nativeHandle.close 26411 nativeHandle.close = () => {} 26412 const originalClose = this[_handle].close 26413 this[_handle].close = () => {} 26414 // It also calls `Buffer.concat()` at the end, which may be convenient 26415 // for some, but which we are not interested in as it slows us down. 26416 Buffer.concat = (args) => args 26417 let result 26418 try { 26419 const flushFlag = typeof chunk[_flushFlag] === 'number' 26420 ? chunk[_flushFlag] : this[_flushFlag] 26421 result = this[_handle]._processChunk(chunk, flushFlag) 26422 // if we don't throw, reset it back how it was 26423 Buffer.concat = OriginalBufferConcat 26424 } catch (err) { 26425 // or if we do, put Buffer.concat() back before we emit error 26426 // Error events call into user code, which may call Buffer.concat() 26427 Buffer.concat = OriginalBufferConcat 26428 this[_onError](new ZlibError(err)) 26429 } finally { 26430 if (this[_handle]) { 26431 // Core zlib resets `_handle` to null after attempting to close the 26432 // native handle. Our no-op handler prevented actual closure, but we 26433 // need to restore the `._handle` property. 26434 this[_handle]._handle = nativeHandle 26435 nativeHandle.close = originalNativeClose 26436 this[_handle].close = originalClose 26437 // `_processChunk()` adds an 'error' listener. If we don't remove it 26438 // after each call, these handlers start piling up. 26439 this[_handle].removeAllListeners('error') 26440 // make sure OUR error listener is still attached tho 26441 } 26442 } 26443 26444 if (this[_handle]) 26445 this[_handle].on('error', er => this[_onError](new ZlibError(er))) 26446 26447 let writeReturn 26448 if (result) { 26449 if (Array.isArray(result) && result.length > 0) { 26450 // The first buffer is always `handle._outBuffer`, which would be 26451 // re-used for later invocations; so, we always have to copy that one. 26452 writeReturn = this[_superWrite](Buffer.from(result[0])) 26453 for (let i = 1; i < result.length; i++) { 26454 writeReturn = this[_superWrite](result[i]) 26455 } 26456 } else { 26457 writeReturn = this[_superWrite](Buffer.from(result)) 26458 } 26459 } 26460 26461 if (cb) 26462 cb() 26463 return writeReturn 26464 } 26465 26466 [_superWrite] (data) { 26467 return super.write(data) 26468 } 26469 } 26470 26471 class Zlib extends ZlibBase { 26472 constructor (opts, mode) { 26473 opts = opts || {} 26474 26475 opts.flush = opts.flush || constants.Z_NO_FLUSH 26476 opts.finishFlush = opts.finishFlush || constants.Z_FINISH 26477 super(opts, mode) 26478 26479 this[_fullFlushFlag] = constants.Z_FULL_FLUSH 26480 this[_level] = opts.level 26481 this[_strategy] = opts.strategy 26482 } 26483 26484 params (level, strategy) { 26485 if (this[_sawError]) 26486 return 26487 26488 if (!this[_handle]) 26489 throw new Error('cannot switch params when binding is closed') 26490 26491 // no way to test this without also not supporting params at all 26492 /* istanbul ignore if */ 26493 if (!this[_handle].params) 26494 throw new Error('not supported in this implementation') 26495 26496 if (this[_level] !== level || this[_strategy] !== strategy) { 26497 this.flush(constants.Z_SYNC_FLUSH) 26498 assert(this[_handle], 'zlib binding closed') 26499 // .params() calls .flush(), but the latter is always async in the 26500 // core zlib. We override .flush() temporarily to intercept that and 26501 // flush synchronously. 26502 const origFlush = this[_handle].flush 26503 this[_handle].flush = (flushFlag, cb) => { 26504 this.flush(flushFlag) 26505 cb() 26506 } 26507 try { 26508 this[_handle].params(level, strategy) 26509 } finally { 26510 this[_handle].flush = origFlush 26511 } 26512 /* istanbul ignore else */ 26513 if (this[_handle]) { 26514 this[_level] = level 26515 this[_strategy] = strategy 26516 } 26517 } 26518 } 26519 } 26520 26521 // minimal 2-byte header 26522 class Deflate extends Zlib { 26523 constructor (opts) { 26524 super(opts, 'Deflate') 26525 } 26526 } 26527 26528 class Inflate extends Zlib { 26529 constructor (opts) { 26530 super(opts, 'Inflate') 26531 } 26532 } 26533 26534 // gzip - bigger header, same deflate compression 26535 const _portable = Symbol('_portable') 26536 class Gzip extends Zlib { 26537 constructor (opts) { 26538 super(opts, 'Gzip') 26539 this[_portable] = opts && !!opts.portable 26540 } 26541 26542 [_superWrite] (data) { 26543 if (!this[_portable]) 26544 return super[_superWrite](data) 26545 26546 // we'll always get the header emitted in one first chunk 26547 // overwrite the OS indicator byte with 0xFF 26548 this[_portable] = false 26549 data[9] = 255 26550 return super[_superWrite](data) 26551 } 26552 } 26553 26554 class Gunzip extends Zlib { 26555 constructor (opts) { 26556 super(opts, 'Gunzip') 26557 } 26558 } 26559 26560 // raw - no header 26561 class DeflateRaw extends Zlib { 26562 constructor (opts) { 26563 super(opts, 'DeflateRaw') 26564 } 26565 } 26566 26567 class InflateRaw extends Zlib { 26568 constructor (opts) { 26569 super(opts, 'InflateRaw') 26570 } 26571 } 26572 26573 // auto-detect header. 26574 class Unzip extends Zlib { 26575 constructor (opts) { 26576 super(opts, 'Unzip') 26577 } 26578 } 26579 26580 class Brotli extends ZlibBase { 26581 constructor (opts, mode) { 26582 opts = opts || {} 26583 26584 opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS 26585 opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH 26586 26587 super(opts, mode) 26588 26589 this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH 26590 } 26591 } 26592 26593 class BrotliCompress extends Brotli { 26594 constructor (opts) { 26595 super(opts, 'BrotliCompress') 26596 } 26597 } 26598 26599 class BrotliDecompress extends Brotli { 26600 constructor (opts) { 26601 super(opts, 'BrotliDecompress') 26602 } 26603 } 26604 26605 exports.Deflate = Deflate 26606 exports.Inflate = Inflate 26607 exports.Gzip = Gzip 26608 exports.Gunzip = Gunzip 26609 exports.DeflateRaw = DeflateRaw 26610 exports.InflateRaw = InflateRaw 26611 exports.Unzip = Unzip 26612 /* istanbul ignore else */ 26613 if (typeof realZlib.BrotliCompress === 'function') { 26614 exports.BrotliCompress = BrotliCompress 26615 exports.BrotliDecompress = BrotliDecompress 26616 } else { 26617 exports.BrotliCompress = exports.BrotliDecompress = class { 26618 constructor () { 26619 throw new Error('Brotli is not supported in this version of Node.js') 26620 } 26621 } 26622 } 26623 26624 26625 /***/ }), 26626 26627 /***/ 7557: 26628 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 26629 26630 "use strict"; 26631 26632 const proc = typeof process === 'object' && process ? process : { 26633 stdout: null, 26634 stderr: null, 26635 } 26636 const EE = __nccwpck_require__(2361) 26637 const Stream = __nccwpck_require__(2781) 26638 const SD = (__nccwpck_require__(1576).StringDecoder) 26639 26640 const EOF = Symbol('EOF') 26641 const MAYBE_EMIT_END = Symbol('maybeEmitEnd') 26642 const EMITTED_END = Symbol('emittedEnd') 26643 const EMITTING_END = Symbol('emittingEnd') 26644 const EMITTED_ERROR = Symbol('emittedError') 26645 const CLOSED = Symbol('closed') 26646 const READ = Symbol('read') 26647 const FLUSH = Symbol('flush') 26648 const FLUSHCHUNK = Symbol('flushChunk') 26649 const ENCODING = Symbol('encoding') 26650 const DECODER = Symbol('decoder') 26651 const FLOWING = Symbol('flowing') 26652 const PAUSED = Symbol('paused') 26653 const RESUME = Symbol('resume') 26654 const BUFFERLENGTH = Symbol('bufferLength') 26655 const BUFFERPUSH = Symbol('bufferPush') 26656 const BUFFERSHIFT = Symbol('bufferShift') 26657 const OBJECTMODE = Symbol('objectMode') 26658 const DESTROYED = Symbol('destroyed') 26659 const EMITDATA = Symbol('emitData') 26660 const EMITEND = Symbol('emitEnd') 26661 const EMITEND2 = Symbol('emitEnd2') 26662 const ASYNC = Symbol('async') 26663 26664 const defer = fn => Promise.resolve().then(fn) 26665 26666 // TODO remove when Node v8 support drops 26667 const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' 26668 const ASYNCITERATOR = doIter && Symbol.asyncIterator 26669 || Symbol('asyncIterator not implemented') 26670 const ITERATOR = doIter && Symbol.iterator 26671 || Symbol('iterator not implemented') 26672 26673 // events that mean 'the stream is over' 26674 // these are treated specially, and re-emitted 26675 // if they are listened for after emitting. 26676 const isEndish = ev => 26677 ev === 'end' || 26678 ev === 'finish' || 26679 ev === 'prefinish' 26680 26681 const isArrayBuffer = b => b instanceof ArrayBuffer || 26682 typeof b === 'object' && 26683 b.constructor && 26684 b.constructor.name === 'ArrayBuffer' && 26685 b.byteLength >= 0 26686 26687 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) 26688 26689 class Pipe { 26690 constructor (src, dest, opts) { 26691 this.src = src 26692 this.dest = dest 26693 this.opts = opts 26694 this.ondrain = () => src[RESUME]() 26695 dest.on('drain', this.ondrain) 26696 } 26697 unpipe () { 26698 this.dest.removeListener('drain', this.ondrain) 26699 } 26700 // istanbul ignore next - only here for the prototype 26701 proxyErrors () {} 26702 end () { 26703 this.unpipe() 26704 if (this.opts.end) 26705 this.dest.end() 26706 } 26707 } 26708 26709 class PipeProxyErrors extends Pipe { 26710 unpipe () { 26711 this.src.removeListener('error', this.proxyErrors) 26712 super.unpipe() 26713 } 26714 constructor (src, dest, opts) { 26715 super(src, dest, opts) 26716 this.proxyErrors = er => dest.emit('error', er) 26717 src.on('error', this.proxyErrors) 26718 } 26719 } 26720 26721 module.exports = class Minipass extends Stream { 26722 constructor (options) { 26723 super() 26724 this[FLOWING] = false 26725 // whether we're explicitly paused 26726 this[PAUSED] = false 26727 this.pipes = [] 26728 this.buffer = [] 26729 this[OBJECTMODE] = options && options.objectMode || false 26730 if (this[OBJECTMODE]) 26731 this[ENCODING] = null 26732 else 26733 this[ENCODING] = options && options.encoding || null 26734 if (this[ENCODING] === 'buffer') 26735 this[ENCODING] = null 26736 this[ASYNC] = options && !!options.async || false 26737 this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null 26738 this[EOF] = false 26739 this[EMITTED_END] = false 26740 this[EMITTING_END] = false 26741 this[CLOSED] = false 26742 this[EMITTED_ERROR] = null 26743 this.writable = true 26744 this.readable = true 26745 this[BUFFERLENGTH] = 0 26746 this[DESTROYED] = false 26747 } 26748 26749 get bufferLength () { return this[BUFFERLENGTH] } 26750 26751 get encoding () { return this[ENCODING] } 26752 set encoding (enc) { 26753 if (this[OBJECTMODE]) 26754 throw new Error('cannot set encoding in objectMode') 26755 26756 if (this[ENCODING] && enc !== this[ENCODING] && 26757 (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) 26758 throw new Error('cannot change encoding') 26759 26760 if (this[ENCODING] !== enc) { 26761 this[DECODER] = enc ? new SD(enc) : null 26762 if (this.buffer.length) 26763 this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) 26764 } 26765 26766 this[ENCODING] = enc 26767 } 26768 26769 setEncoding (enc) { 26770 this.encoding = enc 26771 } 26772 26773 get objectMode () { return this[OBJECTMODE] } 26774 set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } 26775 26776 get ['async'] () { return this[ASYNC] } 26777 set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } 26778 26779 write (chunk, encoding, cb) { 26780 if (this[EOF]) 26781 throw new Error('write after end') 26782 26783 if (this[DESTROYED]) { 26784 this.emit('error', Object.assign( 26785 new Error('Cannot call write after a stream was destroyed'), 26786 { code: 'ERR_STREAM_DESTROYED' } 26787 )) 26788 return true 26789 } 26790 26791 if (typeof encoding === 'function') 26792 cb = encoding, encoding = 'utf8' 26793 26794 if (!encoding) 26795 encoding = 'utf8' 26796 26797 const fn = this[ASYNC] ? defer : f => f() 26798 26799 // convert array buffers and typed array views into buffers 26800 // at some point in the future, we may want to do the opposite! 26801 // leave strings and buffers as-is 26802 // anything else switches us into object mode 26803 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { 26804 if (isArrayBufferView(chunk)) 26805 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) 26806 else if (isArrayBuffer(chunk)) 26807 chunk = Buffer.from(chunk) 26808 else if (typeof chunk !== 'string') 26809 // use the setter so we throw if we have encoding set 26810 this.objectMode = true 26811 } 26812 26813 // handle object mode up front, since it's simpler 26814 // this yields better performance, fewer checks later. 26815 if (this[OBJECTMODE]) { 26816 /* istanbul ignore if - maybe impossible? */ 26817 if (this.flowing && this[BUFFERLENGTH] !== 0) 26818 this[FLUSH](true) 26819 26820 if (this.flowing) 26821 this.emit('data', chunk) 26822 else 26823 this[BUFFERPUSH](chunk) 26824 26825 if (this[BUFFERLENGTH] !== 0) 26826 this.emit('readable') 26827 26828 if (cb) 26829 fn(cb) 26830 26831 return this.flowing 26832 } 26833 26834 // at this point the chunk is a buffer or string 26835 // don't buffer it up or send it to the decoder 26836 if (!chunk.length) { 26837 if (this[BUFFERLENGTH] !== 0) 26838 this.emit('readable') 26839 if (cb) 26840 fn(cb) 26841 return this.flowing 26842 } 26843 26844 // fast-path writing strings of same encoding to a stream with 26845 // an empty buffer, skipping the buffer/decoder dance 26846 if (typeof chunk === 'string' && 26847 // unless it is a string already ready for us to use 26848 !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { 26849 chunk = Buffer.from(chunk, encoding) 26850 } 26851 26852 if (Buffer.isBuffer(chunk) && this[ENCODING]) 26853 chunk = this[DECODER].write(chunk) 26854 26855 // Note: flushing CAN potentially switch us into not-flowing mode 26856 if (this.flowing && this[BUFFERLENGTH] !== 0) 26857 this[FLUSH](true) 26858 26859 if (this.flowing) 26860 this.emit('data', chunk) 26861 else 26862 this[BUFFERPUSH](chunk) 26863 26864 if (this[BUFFERLENGTH] !== 0) 26865 this.emit('readable') 26866 26867 if (cb) 26868 fn(cb) 26869 26870 return this.flowing 26871 } 26872 26873 read (n) { 26874 if (this[DESTROYED]) 26875 return null 26876 26877 if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { 26878 this[MAYBE_EMIT_END]() 26879 return null 26880 } 26881 26882 if (this[OBJECTMODE]) 26883 n = null 26884 26885 if (this.buffer.length > 1 && !this[OBJECTMODE]) { 26886 if (this.encoding) 26887 this.buffer = [this.buffer.join('')] 26888 else 26889 this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] 26890 } 26891 26892 const ret = this[READ](n || null, this.buffer[0]) 26893 this[MAYBE_EMIT_END]() 26894 return ret 26895 } 26896 26897 [READ] (n, chunk) { 26898 if (n === chunk.length || n === null) 26899 this[BUFFERSHIFT]() 26900 else { 26901 this.buffer[0] = chunk.slice(n) 26902 chunk = chunk.slice(0, n) 26903 this[BUFFERLENGTH] -= n 26904 } 26905 26906 this.emit('data', chunk) 26907 26908 if (!this.buffer.length && !this[EOF]) 26909 this.emit('drain') 26910 26911 return chunk 26912 } 26913 26914 end (chunk, encoding, cb) { 26915 if (typeof chunk === 'function') 26916 cb = chunk, chunk = null 26917 if (typeof encoding === 'function') 26918 cb = encoding, encoding = 'utf8' 26919 if (chunk) 26920 this.write(chunk, encoding) 26921 if (cb) 26922 this.once('end', cb) 26923 this[EOF] = true 26924 this.writable = false 26925 26926 // if we haven't written anything, then go ahead and emit, 26927 // even if we're not reading. 26928 // we'll re-emit if a new 'end' listener is added anyway. 26929 // This makes MP more suitable to write-only use cases. 26930 if (this.flowing || !this[PAUSED]) 26931 this[MAYBE_EMIT_END]() 26932 return this 26933 } 26934 26935 // don't let the internal resume be overwritten 26936 [RESUME] () { 26937 if (this[DESTROYED]) 26938 return 26939 26940 this[PAUSED] = false 26941 this[FLOWING] = true 26942 this.emit('resume') 26943 if (this.buffer.length) 26944 this[FLUSH]() 26945 else if (this[EOF]) 26946 this[MAYBE_EMIT_END]() 26947 else 26948 this.emit('drain') 26949 } 26950 26951 resume () { 26952 return this[RESUME]() 26953 } 26954 26955 pause () { 26956 this[FLOWING] = false 26957 this[PAUSED] = true 26958 } 26959 26960 get destroyed () { 26961 return this[DESTROYED] 26962 } 26963 26964 get flowing () { 26965 return this[FLOWING] 26966 } 26967 26968 get paused () { 26969 return this[PAUSED] 26970 } 26971 26972 [BUFFERPUSH] (chunk) { 26973 if (this[OBJECTMODE]) 26974 this[BUFFERLENGTH] += 1 26975 else 26976 this[BUFFERLENGTH] += chunk.length 26977 this.buffer.push(chunk) 26978 } 26979 26980 [BUFFERSHIFT] () { 26981 if (this.buffer.length) { 26982 if (this[OBJECTMODE]) 26983 this[BUFFERLENGTH] -= 1 26984 else 26985 this[BUFFERLENGTH] -= this.buffer[0].length 26986 } 26987 return this.buffer.shift() 26988 } 26989 26990 [FLUSH] (noDrain) { 26991 do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) 26992 26993 if (!noDrain && !this.buffer.length && !this[EOF]) 26994 this.emit('drain') 26995 } 26996 26997 [FLUSHCHUNK] (chunk) { 26998 return chunk ? (this.emit('data', chunk), this.flowing) : false 26999 } 27000 27001 pipe (dest, opts) { 27002 if (this[DESTROYED]) 27003 return 27004 27005 const ended = this[EMITTED_END] 27006 opts = opts || {} 27007 if (dest === proc.stdout || dest === proc.stderr) 27008 opts.end = false 27009 else 27010 opts.end = opts.end !== false 27011 opts.proxyErrors = !!opts.proxyErrors 27012 27013 // piping an ended stream ends immediately 27014 if (ended) { 27015 if (opts.end) 27016 dest.end() 27017 } else { 27018 this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) 27019 : new PipeProxyErrors(this, dest, opts)) 27020 if (this[ASYNC]) 27021 defer(() => this[RESUME]()) 27022 else 27023 this[RESUME]() 27024 } 27025 27026 return dest 27027 } 27028 27029 unpipe (dest) { 27030 const p = this.pipes.find(p => p.dest === dest) 27031 if (p) { 27032 this.pipes.splice(this.pipes.indexOf(p), 1) 27033 p.unpipe() 27034 } 27035 } 27036 27037 addListener (ev, fn) { 27038 return this.on(ev, fn) 27039 } 27040 27041 on (ev, fn) { 27042 const ret = super.on(ev, fn) 27043 if (ev === 'data' && !this.pipes.length && !this.flowing) 27044 this[RESUME]() 27045 else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) 27046 super.emit('readable') 27047 else if (isEndish(ev) && this[EMITTED_END]) { 27048 super.emit(ev) 27049 this.removeAllListeners(ev) 27050 } else if (ev === 'error' && this[EMITTED_ERROR]) { 27051 if (this[ASYNC]) 27052 defer(() => fn.call(this, this[EMITTED_ERROR])) 27053 else 27054 fn.call(this, this[EMITTED_ERROR]) 27055 } 27056 return ret 27057 } 27058 27059 get emittedEnd () { 27060 return this[EMITTED_END] 27061 } 27062 27063 [MAYBE_EMIT_END] () { 27064 if (!this[EMITTING_END] && 27065 !this[EMITTED_END] && 27066 !this[DESTROYED] && 27067 this.buffer.length === 0 && 27068 this[EOF]) { 27069 this[EMITTING_END] = true 27070 this.emit('end') 27071 this.emit('prefinish') 27072 this.emit('finish') 27073 if (this[CLOSED]) 27074 this.emit('close') 27075 this[EMITTING_END] = false 27076 } 27077 } 27078 27079 emit (ev, data, ...extra) { 27080 // error and close are only events allowed after calling destroy() 27081 if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) 27082 return 27083 else if (ev === 'data') { 27084 return !data ? false 27085 : this[ASYNC] ? defer(() => this[EMITDATA](data)) 27086 : this[EMITDATA](data) 27087 } else if (ev === 'end') { 27088 return this[EMITEND]() 27089 } else if (ev === 'close') { 27090 this[CLOSED] = true 27091 // don't emit close before 'end' and 'finish' 27092 if (!this[EMITTED_END] && !this[DESTROYED]) 27093 return 27094 const ret = super.emit('close') 27095 this.removeAllListeners('close') 27096 return ret 27097 } else if (ev === 'error') { 27098 this[EMITTED_ERROR] = data 27099 const ret = super.emit('error', data) 27100 this[MAYBE_EMIT_END]() 27101 return ret 27102 } else if (ev === 'resume') { 27103 const ret = super.emit('resume') 27104 this[MAYBE_EMIT_END]() 27105 return ret 27106 } else if (ev === 'finish' || ev === 'prefinish') { 27107 const ret = super.emit(ev) 27108 this.removeAllListeners(ev) 27109 return ret 27110 } 27111 27112 // Some other unknown event 27113 const ret = super.emit(ev, data, ...extra) 27114 this[MAYBE_EMIT_END]() 27115 return ret 27116 } 27117 27118 [EMITDATA] (data) { 27119 for (const p of this.pipes) { 27120 if (p.dest.write(data) === false) 27121 this.pause() 27122 } 27123 const ret = super.emit('data', data) 27124 this[MAYBE_EMIT_END]() 27125 return ret 27126 } 27127 27128 [EMITEND] () { 27129 if (this[EMITTED_END]) 27130 return 27131 27132 this[EMITTED_END] = true 27133 this.readable = false 27134 if (this[ASYNC]) 27135 defer(() => this[EMITEND2]()) 27136 else 27137 this[EMITEND2]() 27138 } 27139 27140 [EMITEND2] () { 27141 if (this[DECODER]) { 27142 const data = this[DECODER].end() 27143 if (data) { 27144 for (const p of this.pipes) { 27145 p.dest.write(data) 27146 } 27147 super.emit('data', data) 27148 } 27149 } 27150 27151 for (const p of this.pipes) { 27152 p.end() 27153 } 27154 const ret = super.emit('end') 27155 this.removeAllListeners('end') 27156 return ret 27157 } 27158 27159 // const all = await stream.collect() 27160 collect () { 27161 const buf = [] 27162 if (!this[OBJECTMODE]) 27163 buf.dataLength = 0 27164 // set the promise first, in case an error is raised 27165 // by triggering the flow here. 27166 const p = this.promise() 27167 this.on('data', c => { 27168 buf.push(c) 27169 if (!this[OBJECTMODE]) 27170 buf.dataLength += c.length 27171 }) 27172 return p.then(() => buf) 27173 } 27174 27175 // const data = await stream.concat() 27176 concat () { 27177 return this[OBJECTMODE] 27178 ? Promise.reject(new Error('cannot concat in objectMode')) 27179 : this.collect().then(buf => 27180 this[OBJECTMODE] 27181 ? Promise.reject(new Error('cannot concat in objectMode')) 27182 : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) 27183 } 27184 27185 // stream.promise().then(() => done, er => emitted error) 27186 promise () { 27187 return new Promise((resolve, reject) => { 27188 this.on(DESTROYED, () => reject(new Error('stream destroyed'))) 27189 this.on('error', er => reject(er)) 27190 this.on('end', () => resolve()) 27191 }) 27192 } 27193 27194 // for await (let chunk of stream) 27195 [ASYNCITERATOR] () { 27196 const next = () => { 27197 const res = this.read() 27198 if (res !== null) 27199 return Promise.resolve({ done: false, value: res }) 27200 27201 if (this[EOF]) 27202 return Promise.resolve({ done: true }) 27203 27204 let resolve = null 27205 let reject = null 27206 const onerr = er => { 27207 this.removeListener('data', ondata) 27208 this.removeListener('end', onend) 27209 reject(er) 27210 } 27211 const ondata = value => { 27212 this.removeListener('error', onerr) 27213 this.removeListener('end', onend) 27214 this.pause() 27215 resolve({ value: value, done: !!this[EOF] }) 27216 } 27217 const onend = () => { 27218 this.removeListener('error', onerr) 27219 this.removeListener('data', ondata) 27220 resolve({ done: true }) 27221 } 27222 const ondestroy = () => onerr(new Error('stream destroyed')) 27223 return new Promise((res, rej) => { 27224 reject = rej 27225 resolve = res 27226 this.once(DESTROYED, ondestroy) 27227 this.once('error', onerr) 27228 this.once('end', onend) 27229 this.once('data', ondata) 27230 }) 27231 } 27232 27233 return { next } 27234 } 27235 27236 // for (let chunk of stream) 27237 [ITERATOR] () { 27238 const next = () => { 27239 const value = this.read() 27240 const done = value === null 27241 return { value, done } 27242 } 27243 return { next } 27244 } 27245 27246 destroy (er) { 27247 if (this[DESTROYED]) { 27248 if (er) 27249 this.emit('error', er) 27250 else 27251 this.emit(DESTROYED) 27252 return this 27253 } 27254 27255 this[DESTROYED] = true 27256 27257 // throw away all buffered data, it's never coming out 27258 this.buffer.length = 0 27259 this[BUFFERLENGTH] = 0 27260 27261 if (typeof this.close === 'function' && !this[CLOSED]) 27262 this.close() 27263 27264 if (er) 27265 this.emit('error', er) 27266 else // if no error to emit, still reject pending promises 27267 this.emit(DESTROYED) 27268 27269 return this 27270 } 27271 27272 static isStream (s) { 27273 return !!s && (s instanceof Minipass || s instanceof Stream || 27274 s instanceof EE && ( 27275 typeof s.pipe === 'function' || // readable 27276 (typeof s.write === 'function' && typeof s.end === 'function') // writable 27277 )) 27278 } 27279 } 27280 27281 27282 /***/ }), 27283 27284 /***/ 9992: 27285 /***/ ((module) => { 27286 27287 /** 27288 * Helpers. 27289 */ 27290 27291 var s = 1000; 27292 var m = s * 60; 27293 var h = m * 60; 27294 var d = h * 24; 27295 var w = d * 7; 27296 var y = d * 365.25; 27297 27298 /** 27299 * Parse or format the given `val`. 27300 * 27301 * Options: 27302 * 27303 * - `long` verbose formatting [false] 27304 * 27305 * @param {String|Number} val 27306 * @param {Object} [options] 27307 * @throws {Error} throw an error if val is not a non-empty string or a number 27308 * @return {String|Number} 27309 * @api public 27310 */ 27311 27312 module.exports = function(val, options) { 27313 options = options || {}; 27314 var type = typeof val; 27315 if (type === 'string' && val.length > 0) { 27316 return parse(val); 27317 } else if (type === 'number' && isFinite(val)) { 27318 return options.long ? fmtLong(val) : fmtShort(val); 27319 } 27320 throw new Error( 27321 'val is not a non-empty string or a valid number. val=' + 27322 JSON.stringify(val) 27323 ); 27324 }; 27325 27326 /** 27327 * Parse the given `str` and return milliseconds. 27328 * 27329 * @param {String} str 27330 * @return {Number} 27331 * @api private 27332 */ 27333 27334 function parse(str) { 27335 str = String(str); 27336 if (str.length > 100) { 27337 return; 27338 } 27339 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( 27340 str 27341 ); 27342 if (!match) { 27343 return; 27344 } 27345 var n = parseFloat(match[1]); 27346 var type = (match[2] || 'ms').toLowerCase(); 27347 switch (type) { 27348 case 'years': 27349 case 'year': 27350 case 'yrs': 27351 case 'yr': 27352 case 'y': 27353 return n * y; 27354 case 'weeks': 27355 case 'week': 27356 case 'w': 27357 return n * w; 27358 case 'days': 27359 case 'day': 27360 case 'd': 27361 return n * d; 27362 case 'hours': 27363 case 'hour': 27364 case 'hrs': 27365 case 'hr': 27366 case 'h': 27367 return n * h; 27368 case 'minutes': 27369 case 'minute': 27370 case 'mins': 27371 case 'min': 27372 case 'm': 27373 return n * m; 27374 case 'seconds': 27375 case 'second': 27376 case 'secs': 27377 case 'sec': 27378 case 's': 27379 return n * s; 27380 case 'milliseconds': 27381 case 'millisecond': 27382 case 'msecs': 27383 case 'msec': 27384 case 'ms': 27385 return n; 27386 default: 27387 return undefined; 27388 } 27389 } 27390 27391 /** 27392 * Short format for `ms`. 27393 * 27394 * @param {Number} ms 27395 * @return {String} 27396 * @api private 27397 */ 27398 27399 function fmtShort(ms) { 27400 var msAbs = Math.abs(ms); 27401 if (msAbs >= d) { 27402 return Math.round(ms / d) + 'd'; 27403 } 27404 if (msAbs >= h) { 27405 return Math.round(ms / h) + 'h'; 27406 } 27407 if (msAbs >= m) { 27408 return Math.round(ms / m) + 'm'; 27409 } 27410 if (msAbs >= s) { 27411 return Math.round(ms / s) + 's'; 27412 } 27413 return ms + 'ms'; 27414 } 27415 27416 /** 27417 * Long format for `ms`. 27418 * 27419 * @param {Number} ms 27420 * @return {String} 27421 * @api private 27422 */ 27423 27424 function fmtLong(ms) { 27425 var msAbs = Math.abs(ms); 27426 if (msAbs >= d) { 27427 return plural(ms, msAbs, d, 'day'); 27428 } 27429 if (msAbs >= h) { 27430 return plural(ms, msAbs, h, 'hour'); 27431 } 27432 if (msAbs >= m) { 27433 return plural(ms, msAbs, m, 'minute'); 27434 } 27435 if (msAbs >= s) { 27436 return plural(ms, msAbs, s, 'second'); 27437 } 27438 return ms + ' ms'; 27439 } 27440 27441 /** 27442 * Pluralization helper. 27443 */ 27444 27445 function plural(ms, msAbs, n, name) { 27446 var isPlural = msAbs >= n * 1.5; 27447 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); 27448 } 27449 27450 27451 /***/ }), 27452 27453 /***/ 5385: 27454 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 27455 27456 "use strict"; 27457 /*! 27458 * negotiator 27459 * Copyright(c) 2012 Federico Romero 27460 * Copyright(c) 2012-2014 Isaac Z. Schlueter 27461 * Copyright(c) 2015 Douglas Christopher Wilson 27462 * MIT Licensed 27463 */ 27464 27465 27466 27467 var preferredCharsets = __nccwpck_require__(9296) 27468 var preferredEncodings = __nccwpck_require__(5297) 27469 var preferredLanguages = __nccwpck_require__(9722) 27470 var preferredMediaTypes = __nccwpck_require__(2563) 27471 27472 /** 27473 * Module exports. 27474 * @public 27475 */ 27476 27477 module.exports = Negotiator; 27478 module.exports.Negotiator = Negotiator; 27479 27480 /** 27481 * Create a Negotiator instance from a request. 27482 * @param {object} request 27483 * @public 27484 */ 27485 27486 function Negotiator(request) { 27487 if (!(this instanceof Negotiator)) { 27488 return new Negotiator(request); 27489 } 27490 27491 this.request = request; 27492 } 27493 27494 Negotiator.prototype.charset = function charset(available) { 27495 var set = this.charsets(available); 27496 return set && set[0]; 27497 }; 27498 27499 Negotiator.prototype.charsets = function charsets(available) { 27500 return preferredCharsets(this.request.headers['accept-charset'], available); 27501 }; 27502 27503 Negotiator.prototype.encoding = function encoding(available) { 27504 var set = this.encodings(available); 27505 return set && set[0]; 27506 }; 27507 27508 Negotiator.prototype.encodings = function encodings(available) { 27509 return preferredEncodings(this.request.headers['accept-encoding'], available); 27510 }; 27511 27512 Negotiator.prototype.language = function language(available) { 27513 var set = this.languages(available); 27514 return set && set[0]; 27515 }; 27516 27517 Negotiator.prototype.languages = function languages(available) { 27518 return preferredLanguages(this.request.headers['accept-language'], available); 27519 }; 27520 27521 Negotiator.prototype.mediaType = function mediaType(available) { 27522 var set = this.mediaTypes(available); 27523 return set && set[0]; 27524 }; 27525 27526 Negotiator.prototype.mediaTypes = function mediaTypes(available) { 27527 return preferredMediaTypes(this.request.headers.accept, available); 27528 }; 27529 27530 // Backwards compatibility 27531 Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; 27532 Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; 27533 Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; 27534 Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; 27535 Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; 27536 Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; 27537 Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; 27538 Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; 27539 27540 27541 /***/ }), 27542 27543 /***/ 9296: 27544 /***/ ((module) => { 27545 27546 "use strict"; 27547 /** 27548 * negotiator 27549 * Copyright(c) 2012 Isaac Z. Schlueter 27550 * Copyright(c) 2014 Federico Romero 27551 * Copyright(c) 2014-2015 Douglas Christopher Wilson 27552 * MIT Licensed 27553 */ 27554 27555 27556 27557 /** 27558 * Module exports. 27559 * @public 27560 */ 27561 27562 module.exports = preferredCharsets; 27563 module.exports.preferredCharsets = preferredCharsets; 27564 27565 /** 27566 * Module variables. 27567 * @private 27568 */ 27569 27570 var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; 27571 27572 /** 27573 * Parse the Accept-Charset header. 27574 * @private 27575 */ 27576 27577 function parseAcceptCharset(accept) { 27578 var accepts = accept.split(','); 27579 27580 for (var i = 0, j = 0; i < accepts.length; i++) { 27581 var charset = parseCharset(accepts[i].trim(), i); 27582 27583 if (charset) { 27584 accepts[j++] = charset; 27585 } 27586 } 27587 27588 // trim accepts 27589 accepts.length = j; 27590 27591 return accepts; 27592 } 27593 27594 /** 27595 * Parse a charset from the Accept-Charset header. 27596 * @private 27597 */ 27598 27599 function parseCharset(str, i) { 27600 var match = simpleCharsetRegExp.exec(str); 27601 if (!match) return null; 27602 27603 var charset = match[1]; 27604 var q = 1; 27605 if (match[2]) { 27606 var params = match[2].split(';') 27607 for (var j = 0; j < params.length; j++) { 27608 var p = params[j].trim().split('='); 27609 if (p[0] === 'q') { 27610 q = parseFloat(p[1]); 27611 break; 27612 } 27613 } 27614 } 27615 27616 return { 27617 charset: charset, 27618 q: q, 27619 i: i 27620 }; 27621 } 27622 27623 /** 27624 * Get the priority of a charset. 27625 * @private 27626 */ 27627 27628 function getCharsetPriority(charset, accepted, index) { 27629 var priority = {o: -1, q: 0, s: 0}; 27630 27631 for (var i = 0; i < accepted.length; i++) { 27632 var spec = specify(charset, accepted[i], index); 27633 27634 if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { 27635 priority = spec; 27636 } 27637 } 27638 27639 return priority; 27640 } 27641 27642 /** 27643 * Get the specificity of the charset. 27644 * @private 27645 */ 27646 27647 function specify(charset, spec, index) { 27648 var s = 0; 27649 if(spec.charset.toLowerCase() === charset.toLowerCase()){ 27650 s |= 1; 27651 } else if (spec.charset !== '*' ) { 27652 return null 27653 } 27654 27655 return { 27656 i: index, 27657 o: spec.i, 27658 q: spec.q, 27659 s: s 27660 } 27661 } 27662 27663 /** 27664 * Get the preferred charsets from an Accept-Charset header. 27665 * @public 27666 */ 27667 27668 function preferredCharsets(accept, provided) { 27669 // RFC 2616 sec 14.2: no header = * 27670 var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); 27671 27672 if (!provided) { 27673 // sorted list of all charsets 27674 return accepts 27675 .filter(isQuality) 27676 .sort(compareSpecs) 27677 .map(getFullCharset); 27678 } 27679 27680 var priorities = provided.map(function getPriority(type, index) { 27681 return getCharsetPriority(type, accepts, index); 27682 }); 27683 27684 // sorted list of accepted charsets 27685 return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { 27686 return provided[priorities.indexOf(priority)]; 27687 }); 27688 } 27689 27690 /** 27691 * Compare two specs. 27692 * @private 27693 */ 27694 27695 function compareSpecs(a, b) { 27696 return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; 27697 } 27698 27699 /** 27700 * Get full charset string. 27701 * @private 27702 */ 27703 27704 function getFullCharset(spec) { 27705 return spec.charset; 27706 } 27707 27708 /** 27709 * Check if a spec has any quality. 27710 * @private 27711 */ 27712 27713 function isQuality(spec) { 27714 return spec.q > 0; 27715 } 27716 27717 27718 /***/ }), 27719 27720 /***/ 5297: 27721 /***/ ((module) => { 27722 27723 "use strict"; 27724 /** 27725 * negotiator 27726 * Copyright(c) 2012 Isaac Z. Schlueter 27727 * Copyright(c) 2014 Federico Romero 27728 * Copyright(c) 2014-2015 Douglas Christopher Wilson 27729 * MIT Licensed 27730 */ 27731 27732 27733 27734 /** 27735 * Module exports. 27736 * @public 27737 */ 27738 27739 module.exports = preferredEncodings; 27740 module.exports.preferredEncodings = preferredEncodings; 27741 27742 /** 27743 * Module variables. 27744 * @private 27745 */ 27746 27747 var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; 27748 27749 /** 27750 * Parse the Accept-Encoding header. 27751 * @private 27752 */ 27753 27754 function parseAcceptEncoding(accept) { 27755 var accepts = accept.split(','); 27756 var hasIdentity = false; 27757 var minQuality = 1; 27758 27759 for (var i = 0, j = 0; i < accepts.length; i++) { 27760 var encoding = parseEncoding(accepts[i].trim(), i); 27761 27762 if (encoding) { 27763 accepts[j++] = encoding; 27764 hasIdentity = hasIdentity || specify('identity', encoding); 27765 minQuality = Math.min(minQuality, encoding.q || 1); 27766 } 27767 } 27768 27769 if (!hasIdentity) { 27770 /* 27771 * If identity doesn't explicitly appear in the accept-encoding header, 27772 * it's added to the list of acceptable encoding with the lowest q 27773 */ 27774 accepts[j++] = { 27775 encoding: 'identity', 27776 q: minQuality, 27777 i: i 27778 }; 27779 } 27780 27781 // trim accepts 27782 accepts.length = j; 27783 27784 return accepts; 27785 } 27786 27787 /** 27788 * Parse an encoding from the Accept-Encoding header. 27789 * @private 27790 */ 27791 27792 function parseEncoding(str, i) { 27793 var match = simpleEncodingRegExp.exec(str); 27794 if (!match) return null; 27795 27796 var encoding = match[1]; 27797 var q = 1; 27798 if (match[2]) { 27799 var params = match[2].split(';'); 27800 for (var j = 0; j < params.length; j++) { 27801 var p = params[j].trim().split('='); 27802 if (p[0] === 'q') { 27803 q = parseFloat(p[1]); 27804 break; 27805 } 27806 } 27807 } 27808 27809 return { 27810 encoding: encoding, 27811 q: q, 27812 i: i 27813 }; 27814 } 27815 27816 /** 27817 * Get the priority of an encoding. 27818 * @private 27819 */ 27820 27821 function getEncodingPriority(encoding, accepted, index) { 27822 var priority = {o: -1, q: 0, s: 0}; 27823 27824 for (var i = 0; i < accepted.length; i++) { 27825 var spec = specify(encoding, accepted[i], index); 27826 27827 if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { 27828 priority = spec; 27829 } 27830 } 27831 27832 return priority; 27833 } 27834 27835 /** 27836 * Get the specificity of the encoding. 27837 * @private 27838 */ 27839 27840 function specify(encoding, spec, index) { 27841 var s = 0; 27842 if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ 27843 s |= 1; 27844 } else if (spec.encoding !== '*' ) { 27845 return null 27846 } 27847 27848 return { 27849 i: index, 27850 o: spec.i, 27851 q: spec.q, 27852 s: s 27853 } 27854 }; 27855 27856 /** 27857 * Get the preferred encodings from an Accept-Encoding header. 27858 * @public 27859 */ 27860 27861 function preferredEncodings(accept, provided) { 27862 var accepts = parseAcceptEncoding(accept || ''); 27863 27864 if (!provided) { 27865 // sorted list of all encodings 27866 return accepts 27867 .filter(isQuality) 27868 .sort(compareSpecs) 27869 .map(getFullEncoding); 27870 } 27871 27872 var priorities = provided.map(function getPriority(type, index) { 27873 return getEncodingPriority(type, accepts, index); 27874 }); 27875 27876 // sorted list of accepted encodings 27877 return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { 27878 return provided[priorities.indexOf(priority)]; 27879 }); 27880 } 27881 27882 /** 27883 * Compare two specs. 27884 * @private 27885 */ 27886 27887 function compareSpecs(a, b) { 27888 return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; 27889 } 27890 27891 /** 27892 * Get full encoding string. 27893 * @private 27894 */ 27895 27896 function getFullEncoding(spec) { 27897 return spec.encoding; 27898 } 27899 27900 /** 27901 * Check if a spec has any quality. 27902 * @private 27903 */ 27904 27905 function isQuality(spec) { 27906 return spec.q > 0; 27907 } 27908 27909 27910 /***/ }), 27911 27912 /***/ 9722: 27913 /***/ ((module) => { 27914 27915 "use strict"; 27916 /** 27917 * negotiator 27918 * Copyright(c) 2012 Isaac Z. Schlueter 27919 * Copyright(c) 2014 Federico Romero 27920 * Copyright(c) 2014-2015 Douglas Christopher Wilson 27921 * MIT Licensed 27922 */ 27923 27924 27925 27926 /** 27927 * Module exports. 27928 * @public 27929 */ 27930 27931 module.exports = preferredLanguages; 27932 module.exports.preferredLanguages = preferredLanguages; 27933 27934 /** 27935 * Module variables. 27936 * @private 27937 */ 27938 27939 var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; 27940 27941 /** 27942 * Parse the Accept-Language header. 27943 * @private 27944 */ 27945 27946 function parseAcceptLanguage(accept) { 27947 var accepts = accept.split(','); 27948 27949 for (var i = 0, j = 0; i < accepts.length; i++) { 27950 var language = parseLanguage(accepts[i].trim(), i); 27951 27952 if (language) { 27953 accepts[j++] = language; 27954 } 27955 } 27956 27957 // trim accepts 27958 accepts.length = j; 27959 27960 return accepts; 27961 } 27962 27963 /** 27964 * Parse a language from the Accept-Language header. 27965 * @private 27966 */ 27967 27968 function parseLanguage(str, i) { 27969 var match = simpleLanguageRegExp.exec(str); 27970 if (!match) return null; 27971 27972 var prefix = match[1] 27973 var suffix = match[2] 27974 var full = prefix 27975 27976 if (suffix) full += "-" + suffix; 27977 27978 var q = 1; 27979 if (match[3]) { 27980 var params = match[3].split(';') 27981 for (var j = 0; j < params.length; j++) { 27982 var p = params[j].split('='); 27983 if (p[0] === 'q') q = parseFloat(p[1]); 27984 } 27985 } 27986 27987 return { 27988 prefix: prefix, 27989 suffix: suffix, 27990 q: q, 27991 i: i, 27992 full: full 27993 }; 27994 } 27995 27996 /** 27997 * Get the priority of a language. 27998 * @private 27999 */ 28000 28001 function getLanguagePriority(language, accepted, index) { 28002 var priority = {o: -1, q: 0, s: 0}; 28003 28004 for (var i = 0; i < accepted.length; i++) { 28005 var spec = specify(language, accepted[i], index); 28006 28007 if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { 28008 priority = spec; 28009 } 28010 } 28011 28012 return priority; 28013 } 28014 28015 /** 28016 * Get the specificity of the language. 28017 * @private 28018 */ 28019 28020 function specify(language, spec, index) { 28021 var p = parseLanguage(language) 28022 if (!p) return null; 28023 var s = 0; 28024 if(spec.full.toLowerCase() === p.full.toLowerCase()){ 28025 s |= 4; 28026 } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { 28027 s |= 2; 28028 } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { 28029 s |= 1; 28030 } else if (spec.full !== '*' ) { 28031 return null 28032 } 28033 28034 return { 28035 i: index, 28036 o: spec.i, 28037 q: spec.q, 28038 s: s 28039 } 28040 }; 28041 28042 /** 28043 * Get the preferred languages from an Accept-Language header. 28044 * @public 28045 */ 28046 28047 function preferredLanguages(accept, provided) { 28048 // RFC 2616 sec 14.4: no header = * 28049 var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); 28050 28051 if (!provided) { 28052 // sorted list of all languages 28053 return accepts 28054 .filter(isQuality) 28055 .sort(compareSpecs) 28056 .map(getFullLanguage); 28057 } 28058 28059 var priorities = provided.map(function getPriority(type, index) { 28060 return getLanguagePriority(type, accepts, index); 28061 }); 28062 28063 // sorted list of accepted languages 28064 return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { 28065 return provided[priorities.indexOf(priority)]; 28066 }); 28067 } 28068 28069 /** 28070 * Compare two specs. 28071 * @private 28072 */ 28073 28074 function compareSpecs(a, b) { 28075 return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; 28076 } 28077 28078 /** 28079 * Get full language string. 28080 * @private 28081 */ 28082 28083 function getFullLanguage(spec) { 28084 return spec.full; 28085 } 28086 28087 /** 28088 * Check if a spec has any quality. 28089 * @private 28090 */ 28091 28092 function isQuality(spec) { 28093 return spec.q > 0; 28094 } 28095 28096 28097 /***/ }), 28098 28099 /***/ 2563: 28100 /***/ ((module) => { 28101 28102 "use strict"; 28103 /** 28104 * negotiator 28105 * Copyright(c) 2012 Isaac Z. Schlueter 28106 * Copyright(c) 2014 Federico Romero 28107 * Copyright(c) 2014-2015 Douglas Christopher Wilson 28108 * MIT Licensed 28109 */ 28110 28111 28112 28113 /** 28114 * Module exports. 28115 * @public 28116 */ 28117 28118 module.exports = preferredMediaTypes; 28119 module.exports.preferredMediaTypes = preferredMediaTypes; 28120 28121 /** 28122 * Module variables. 28123 * @private 28124 */ 28125 28126 var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; 28127 28128 /** 28129 * Parse the Accept header. 28130 * @private 28131 */ 28132 28133 function parseAccept(accept) { 28134 var accepts = splitMediaTypes(accept); 28135 28136 for (var i = 0, j = 0; i < accepts.length; i++) { 28137 var mediaType = parseMediaType(accepts[i].trim(), i); 28138 28139 if (mediaType) { 28140 accepts[j++] = mediaType; 28141 } 28142 } 28143 28144 // trim accepts 28145 accepts.length = j; 28146 28147 return accepts; 28148 } 28149 28150 /** 28151 * Parse a media type from the Accept header. 28152 * @private 28153 */ 28154 28155 function parseMediaType(str, i) { 28156 var match = simpleMediaTypeRegExp.exec(str); 28157 if (!match) return null; 28158 28159 var params = Object.create(null); 28160 var q = 1; 28161 var subtype = match[2]; 28162 var type = match[1]; 28163 28164 if (match[3]) { 28165 var kvps = splitParameters(match[3]).map(splitKeyValuePair); 28166 28167 for (var j = 0; j < kvps.length; j++) { 28168 var pair = kvps[j]; 28169 var key = pair[0].toLowerCase(); 28170 var val = pair[1]; 28171 28172 // get the value, unwrapping quotes 28173 var value = val && val[0] === '"' && val[val.length - 1] === '"' 28174 ? val.substr(1, val.length - 2) 28175 : val; 28176 28177 if (key === 'q') { 28178 q = parseFloat(value); 28179 break; 28180 } 28181 28182 // store parameter 28183 params[key] = value; 28184 } 28185 } 28186 28187 return { 28188 type: type, 28189 subtype: subtype, 28190 params: params, 28191 q: q, 28192 i: i 28193 }; 28194 } 28195 28196 /** 28197 * Get the priority of a media type. 28198 * @private 28199 */ 28200 28201 function getMediaTypePriority(type, accepted, index) { 28202 var priority = {o: -1, q: 0, s: 0}; 28203 28204 for (var i = 0; i < accepted.length; i++) { 28205 var spec = specify(type, accepted[i], index); 28206 28207 if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { 28208 priority = spec; 28209 } 28210 } 28211 28212 return priority; 28213 } 28214 28215 /** 28216 * Get the specificity of the media type. 28217 * @private 28218 */ 28219 28220 function specify(type, spec, index) { 28221 var p = parseMediaType(type); 28222 var s = 0; 28223 28224 if (!p) { 28225 return null; 28226 } 28227 28228 if(spec.type.toLowerCase() == p.type.toLowerCase()) { 28229 s |= 4 28230 } else if(spec.type != '*') { 28231 return null; 28232 } 28233 28234 if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { 28235 s |= 2 28236 } else if(spec.subtype != '*') { 28237 return null; 28238 } 28239 28240 var keys = Object.keys(spec.params); 28241 if (keys.length > 0) { 28242 if (keys.every(function (k) { 28243 return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); 28244 })) { 28245 s |= 1 28246 } else { 28247 return null 28248 } 28249 } 28250 28251 return { 28252 i: index, 28253 o: spec.i, 28254 q: spec.q, 28255 s: s, 28256 } 28257 } 28258 28259 /** 28260 * Get the preferred media types from an Accept header. 28261 * @public 28262 */ 28263 28264 function preferredMediaTypes(accept, provided) { 28265 // RFC 2616 sec 14.2: no header = */* 28266 var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); 28267 28268 if (!provided) { 28269 // sorted list of all types 28270 return accepts 28271 .filter(isQuality) 28272 .sort(compareSpecs) 28273 .map(getFullType); 28274 } 28275 28276 var priorities = provided.map(function getPriority(type, index) { 28277 return getMediaTypePriority(type, accepts, index); 28278 }); 28279 28280 // sorted list of accepted types 28281 return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { 28282 return provided[priorities.indexOf(priority)]; 28283 }); 28284 } 28285 28286 /** 28287 * Compare two specs. 28288 * @private 28289 */ 28290 28291 function compareSpecs(a, b) { 28292 return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; 28293 } 28294 28295 /** 28296 * Get full type string. 28297 * @private 28298 */ 28299 28300 function getFullType(spec) { 28301 return spec.type + '/' + spec.subtype; 28302 } 28303 28304 /** 28305 * Check if a spec has any quality. 28306 * @private 28307 */ 28308 28309 function isQuality(spec) { 28310 return spec.q > 0; 28311 } 28312 28313 /** 28314 * Count the number of quotes in a string. 28315 * @private 28316 */ 28317 28318 function quoteCount(string) { 28319 var count = 0; 28320 var index = 0; 28321 28322 while ((index = string.indexOf('"', index)) !== -1) { 28323 count++; 28324 index++; 28325 } 28326 28327 return count; 28328 } 28329 28330 /** 28331 * Split a key value pair. 28332 * @private 28333 */ 28334 28335 function splitKeyValuePair(str) { 28336 var index = str.indexOf('='); 28337 var key; 28338 var val; 28339 28340 if (index === -1) { 28341 key = str; 28342 } else { 28343 key = str.substr(0, index); 28344 val = str.substr(index + 1); 28345 } 28346 28347 return [key, val]; 28348 } 28349 28350 /** 28351 * Split an Accept header into media types. 28352 * @private 28353 */ 28354 28355 function splitMediaTypes(accept) { 28356 var accepts = accept.split(','); 28357 28358 for (var i = 1, j = 0; i < accepts.length; i++) { 28359 if (quoteCount(accepts[j]) % 2 == 0) { 28360 accepts[++j] = accepts[i]; 28361 } else { 28362 accepts[j] += ',' + accepts[i]; 28363 } 28364 } 28365 28366 // trim accepts 28367 accepts.length = j + 1; 28368 28369 return accepts; 28370 } 28371 28372 /** 28373 * Split a string of parameters. 28374 * @private 28375 */ 28376 28377 function splitParameters(str) { 28378 var parameters = str.split(';'); 28379 28380 for (var i = 1, j = 0; i < parameters.length; i++) { 28381 if (quoteCount(parameters[j]) % 2 == 0) { 28382 parameters[++j] = parameters[i]; 28383 } else { 28384 parameters[j] += ';' + parameters[i]; 28385 } 28386 } 28387 28388 // trim parameters 28389 parameters.length = j + 1; 28390 28391 for (var i = 0; i < parameters.length; i++) { 28392 parameters[i] = parameters[i].trim(); 28393 } 28394 28395 return parameters; 28396 } 28397 28398 28399 /***/ }), 28400 28401 /***/ 1855: 28402 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 28403 28404 "use strict"; 28405 28406 const AggregateError = __nccwpck_require__(1231); 28407 28408 module.exports = async ( 28409 iterable, 28410 mapper, 28411 { 28412 concurrency = Infinity, 28413 stopOnError = true 28414 } = {} 28415 ) => { 28416 return new Promise((resolve, reject) => { 28417 if (typeof mapper !== 'function') { 28418 throw new TypeError('Mapper function is required'); 28419 } 28420 28421 if (!((Number.isSafeInteger(concurrency) || concurrency === Infinity) && concurrency >= 1)) { 28422 throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`); 28423 } 28424 28425 const result = []; 28426 const errors = []; 28427 const iterator = iterable[Symbol.iterator](); 28428 let isRejected = false; 28429 let isIterableDone = false; 28430 let resolvingCount = 0; 28431 let currentIndex = 0; 28432 28433 const next = () => { 28434 if (isRejected) { 28435 return; 28436 } 28437 28438 const nextItem = iterator.next(); 28439 const index = currentIndex; 28440 currentIndex++; 28441 28442 if (nextItem.done) { 28443 isIterableDone = true; 28444 28445 if (resolvingCount === 0) { 28446 if (!stopOnError && errors.length !== 0) { 28447 reject(new AggregateError(errors)); 28448 } else { 28449 resolve(result); 28450 } 28451 } 28452 28453 return; 28454 } 28455 28456 resolvingCount++; 28457 28458 (async () => { 28459 try { 28460 const element = await nextItem.value; 28461 result[index] = await mapper(element, index); 28462 resolvingCount--; 28463 next(); 28464 } catch (error) { 28465 if (stopOnError) { 28466 isRejected = true; 28467 reject(error); 28468 } else { 28469 errors.push(error); 28470 resolvingCount--; 28471 next(); 28472 } 28473 } 28474 })(); 28475 }; 28476 28477 for (let i = 0; i < concurrency; i++) { 28478 next(); 28479 28480 if (isIterableDone) { 28481 break; 28482 } 28483 } 28484 }); 28485 }; 28486 28487 28488 /***/ }), 28489 28490 /***/ 6528: 28491 /***/ ((module) => { 28492 28493 const META = Symbol('proc-log.meta') 28494 module.exports = { 28495 META: META, 28496 output: { 28497 LEVELS: [ 28498 'standard', 28499 'error', 28500 'buffer', 28501 'flush', 28502 ], 28503 KEYS: { 28504 standard: 'standard', 28505 error: 'error', 28506 buffer: 'buffer', 28507 flush: 'flush', 28508 }, 28509 standard: function (...args) { 28510 return process.emit('output', 'standard', ...args) 28511 }, 28512 error: function (...args) { 28513 return process.emit('output', 'error', ...args) 28514 }, 28515 buffer: function (...args) { 28516 return process.emit('output', 'buffer', ...args) 28517 }, 28518 flush: function (...args) { 28519 return process.emit('output', 'flush', ...args) 28520 }, 28521 }, 28522 log: { 28523 LEVELS: [ 28524 'notice', 28525 'error', 28526 'warn', 28527 'info', 28528 'verbose', 28529 'http', 28530 'silly', 28531 'timing', 28532 'pause', 28533 'resume', 28534 ], 28535 KEYS: { 28536 notice: 'notice', 28537 error: 'error', 28538 warn: 'warn', 28539 info: 'info', 28540 verbose: 'verbose', 28541 http: 'http', 28542 silly: 'silly', 28543 timing: 'timing', 28544 pause: 'pause', 28545 resume: 'resume', 28546 }, 28547 error: function (...args) { 28548 return process.emit('log', 'error', ...args) 28549 }, 28550 notice: function (...args) { 28551 return process.emit('log', 'notice', ...args) 28552 }, 28553 warn: function (...args) { 28554 return process.emit('log', 'warn', ...args) 28555 }, 28556 info: function (...args) { 28557 return process.emit('log', 'info', ...args) 28558 }, 28559 verbose: function (...args) { 28560 return process.emit('log', 'verbose', ...args) 28561 }, 28562 http: function (...args) { 28563 return process.emit('log', 'http', ...args) 28564 }, 28565 silly: function (...args) { 28566 return process.emit('log', 'silly', ...args) 28567 }, 28568 timing: function (...args) { 28569 return process.emit('log', 'timing', ...args) 28570 }, 28571 pause: function () { 28572 return process.emit('log', 'pause') 28573 }, 28574 resume: function () { 28575 return process.emit('log', 'resume') 28576 }, 28577 }, 28578 time: { 28579 LEVELS: [ 28580 'start', 28581 'end', 28582 ], 28583 KEYS: { 28584 start: 'start', 28585 end: 'end', 28586 }, 28587 start: function (name, fn) { 28588 process.emit('time', 'start', name) 28589 function end () { 28590 return process.emit('time', 'end', name) 28591 } 28592 if (typeof fn === 'function') { 28593 const res = fn() 28594 if (res && res.finally) { 28595 return res.finally(end) 28596 } 28597 end() 28598 return res 28599 } 28600 return end 28601 }, 28602 end: function (name) { 28603 return process.emit('time', 'end', name) 28604 }, 28605 }, 28606 input: { 28607 LEVELS: [ 28608 'start', 28609 'end', 28610 'read', 28611 ], 28612 KEYS: { 28613 start: 'start', 28614 end: 'end', 28615 read: 'read', 28616 }, 28617 start: function (fn) { 28618 process.emit('input', 'start') 28619 function end () { 28620 return process.emit('input', 'end') 28621 } 28622 if (typeof fn === 'function') { 28623 const res = fn() 28624 if (res && res.finally) { 28625 return res.finally(end) 28626 } 28627 end() 28628 return res 28629 } 28630 return end 28631 }, 28632 end: function () { 28633 return process.emit('input', 'end') 28634 }, 28635 read: function (...args) { 28636 let resolve, reject 28637 const promise = new Promise((_resolve, _reject) => { 28638 resolve = _resolve 28639 reject = _reject 28640 }) 28641 process.emit('input', 'read', resolve, reject, ...args) 28642 return promise 28643 }, 28644 }, 28645 } 28646 28647 28648 /***/ }), 28649 28650 /***/ 4742: 28651 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 28652 28653 "use strict"; 28654 28655 28656 var errcode = __nccwpck_require__(2997); 28657 var retry = __nccwpck_require__(1604); 28658 28659 var hasOwn = Object.prototype.hasOwnProperty; 28660 28661 function isRetryError(err) { 28662 return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); 28663 } 28664 28665 function promiseRetry(fn, options) { 28666 var temp; 28667 var operation; 28668 28669 if (typeof fn === 'object' && typeof options === 'function') { 28670 // Swap options and fn when using alternate signature (options, fn) 28671 temp = options; 28672 options = fn; 28673 fn = temp; 28674 } 28675 28676 operation = retry.operation(options); 28677 28678 return new Promise(function (resolve, reject) { 28679 operation.attempt(function (number) { 28680 Promise.resolve() 28681 .then(function () { 28682 return fn(function (err) { 28683 if (isRetryError(err)) { 28684 err = err.retried; 28685 } 28686 28687 throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err }); 28688 }, number); 28689 }) 28690 .then(resolve, function (err) { 28691 if (isRetryError(err)) { 28692 err = err.retried; 28693 28694 if (operation.retry(err || new Error())) { 28695 return; 28696 } 28697 } 28698 28699 reject(err); 28700 }); 28701 }); 28702 }); 28703 } 28704 28705 module.exports = promiseRetry; 28706 28707 28708 /***/ }), 28709 28710 /***/ 1604: 28711 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 28712 28713 module.exports = __nccwpck_require__(6244); 28714 28715 /***/ }), 28716 28717 /***/ 6244: 28718 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 28719 28720 var RetryOperation = __nccwpck_require__(5369); 28721 28722 exports.operation = function(options) { 28723 var timeouts = exports.timeouts(options); 28724 return new RetryOperation(timeouts, { 28725 forever: options && options.forever, 28726 unref: options && options.unref, 28727 maxRetryTime: options && options.maxRetryTime 28728 }); 28729 }; 28730 28731 exports.timeouts = function(options) { 28732 if (options instanceof Array) { 28733 return [].concat(options); 28734 } 28735 28736 var opts = { 28737 retries: 10, 28738 factor: 2, 28739 minTimeout: 1 * 1000, 28740 maxTimeout: Infinity, 28741 randomize: false 28742 }; 28743 for (var key in options) { 28744 opts[key] = options[key]; 28745 } 28746 28747 if (opts.minTimeout > opts.maxTimeout) { 28748 throw new Error('minTimeout is greater than maxTimeout'); 28749 } 28750 28751 var timeouts = []; 28752 for (var i = 0; i < opts.retries; i++) { 28753 timeouts.push(this.createTimeout(i, opts)); 28754 } 28755 28756 if (options && options.forever && !timeouts.length) { 28757 timeouts.push(this.createTimeout(i, opts)); 28758 } 28759 28760 // sort the array numerically ascending 28761 timeouts.sort(function(a,b) { 28762 return a - b; 28763 }); 28764 28765 return timeouts; 28766 }; 28767 28768 exports.createTimeout = function(attempt, opts) { 28769 var random = (opts.randomize) 28770 ? (Math.random() + 1) 28771 : 1; 28772 28773 var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt)); 28774 timeout = Math.min(timeout, opts.maxTimeout); 28775 28776 return timeout; 28777 }; 28778 28779 exports.wrap = function(obj, options, methods) { 28780 if (options instanceof Array) { 28781 methods = options; 28782 options = null; 28783 } 28784 28785 if (!methods) { 28786 methods = []; 28787 for (var key in obj) { 28788 if (typeof obj[key] === 'function') { 28789 methods.push(key); 28790 } 28791 } 28792 } 28793 28794 for (var i = 0; i < methods.length; i++) { 28795 var method = methods[i]; 28796 var original = obj[method]; 28797 28798 obj[method] = function retryWrapper(original) { 28799 var op = exports.operation(options); 28800 var args = Array.prototype.slice.call(arguments, 1); 28801 var callback = args.pop(); 28802 28803 args.push(function(err) { 28804 if (op.retry(err)) { 28805 return; 28806 } 28807 if (err) { 28808 arguments[0] = op.mainError(); 28809 } 28810 callback.apply(this, arguments); 28811 }); 28812 28813 op.attempt(function() { 28814 original.apply(obj, args); 28815 }); 28816 }.bind(obj, original); 28817 obj[method].options = options; 28818 } 28819 }; 28820 28821 28822 /***/ }), 28823 28824 /***/ 5369: 28825 /***/ ((module) => { 28826 28827 function RetryOperation(timeouts, options) { 28828 // Compatibility for the old (timeouts, retryForever) signature 28829 if (typeof options === 'boolean') { 28830 options = { forever: options }; 28831 } 28832 28833 this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); 28834 this._timeouts = timeouts; 28835 this._options = options || {}; 28836 this._maxRetryTime = options && options.maxRetryTime || Infinity; 28837 this._fn = null; 28838 this._errors = []; 28839 this._attempts = 1; 28840 this._operationTimeout = null; 28841 this._operationTimeoutCb = null; 28842 this._timeout = null; 28843 this._operationStart = null; 28844 28845 if (this._options.forever) { 28846 this._cachedTimeouts = this._timeouts.slice(0); 28847 } 28848 } 28849 module.exports = RetryOperation; 28850 28851 RetryOperation.prototype.reset = function() { 28852 this._attempts = 1; 28853 this._timeouts = this._originalTimeouts; 28854 } 28855 28856 RetryOperation.prototype.stop = function() { 28857 if (this._timeout) { 28858 clearTimeout(this._timeout); 28859 } 28860 28861 this._timeouts = []; 28862 this._cachedTimeouts = null; 28863 }; 28864 28865 RetryOperation.prototype.retry = function(err) { 28866 if (this._timeout) { 28867 clearTimeout(this._timeout); 28868 } 28869 28870 if (!err) { 28871 return false; 28872 } 28873 var currentTime = new Date().getTime(); 28874 if (err && currentTime - this._operationStart >= this._maxRetryTime) { 28875 this._errors.unshift(new Error('RetryOperation timeout occurred')); 28876 return false; 28877 } 28878 28879 this._errors.push(err); 28880 28881 var timeout = this._timeouts.shift(); 28882 if (timeout === undefined) { 28883 if (this._cachedTimeouts) { 28884 // retry forever, only keep last error 28885 this._errors.splice(this._errors.length - 1, this._errors.length); 28886 this._timeouts = this._cachedTimeouts.slice(0); 28887 timeout = this._timeouts.shift(); 28888 } else { 28889 return false; 28890 } 28891 } 28892 28893 var self = this; 28894 var timer = setTimeout(function() { 28895 self._attempts++; 28896 28897 if (self._operationTimeoutCb) { 28898 self._timeout = setTimeout(function() { 28899 self._operationTimeoutCb(self._attempts); 28900 }, self._operationTimeout); 28901 28902 if (self._options.unref) { 28903 self._timeout.unref(); 28904 } 28905 } 28906 28907 self._fn(self._attempts); 28908 }, timeout); 28909 28910 if (this._options.unref) { 28911 timer.unref(); 28912 } 28913 28914 return true; 28915 }; 28916 28917 RetryOperation.prototype.attempt = function(fn, timeoutOps) { 28918 this._fn = fn; 28919 28920 if (timeoutOps) { 28921 if (timeoutOps.timeout) { 28922 this._operationTimeout = timeoutOps.timeout; 28923 } 28924 if (timeoutOps.cb) { 28925 this._operationTimeoutCb = timeoutOps.cb; 28926 } 28927 } 28928 28929 var self = this; 28930 if (this._operationTimeoutCb) { 28931 this._timeout = setTimeout(function() { 28932 self._operationTimeoutCb(); 28933 }, self._operationTimeout); 28934 } 28935 28936 this._operationStart = new Date().getTime(); 28937 28938 this._fn(this._attempts); 28939 }; 28940 28941 RetryOperation.prototype.try = function(fn) { 28942 console.log('Using RetryOperation.try() is deprecated'); 28943 this.attempt(fn); 28944 }; 28945 28946 RetryOperation.prototype.start = function(fn) { 28947 console.log('Using RetryOperation.start() is deprecated'); 28948 this.attempt(fn); 28949 }; 28950 28951 RetryOperation.prototype.start = RetryOperation.prototype.try; 28952 28953 RetryOperation.prototype.errors = function() { 28954 return this._errors; 28955 }; 28956 28957 RetryOperation.prototype.attempts = function() { 28958 return this._attempts; 28959 }; 28960 28961 RetryOperation.prototype.mainError = function() { 28962 if (this._errors.length === 0) { 28963 return null; 28964 } 28965 28966 var counts = {}; 28967 var mainError = null; 28968 var mainErrorCount = 0; 28969 28970 for (var i = 0; i < this._errors.length; i++) { 28971 var error = this._errors[i]; 28972 var message = error.message; 28973 var count = (counts[message] || 0) + 1; 28974 28975 counts[message] = count; 28976 28977 if (count >= mainErrorCount) { 28978 mainError = error; 28979 mainErrorCount = count; 28980 } 28981 } 28982 28983 return mainError; 28984 }; 28985 28986 28987 /***/ }), 28988 28989 /***/ 1532: 28990 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 28991 28992 const ANY = Symbol('SemVer ANY') 28993 // hoisted class for cyclic dependency 28994 class Comparator { 28995 static get ANY () { 28996 return ANY 28997 } 28998 28999 constructor (comp, options) { 29000 options = parseOptions(options) 29001 29002 if (comp instanceof Comparator) { 29003 if (comp.loose === !!options.loose) { 29004 return comp 29005 } else { 29006 comp = comp.value 29007 } 29008 } 29009 29010 comp = comp.trim().split(/\s+/).join(' ') 29011 debug('comparator', comp, options) 29012 this.options = options 29013 this.loose = !!options.loose 29014 this.parse(comp) 29015 29016 if (this.semver === ANY) { 29017 this.value = '' 29018 } else { 29019 this.value = this.operator + this.semver.version 29020 } 29021 29022 debug('comp', this) 29023 } 29024 29025 parse (comp) { 29026 const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] 29027 const m = comp.match(r) 29028 29029 if (!m) { 29030 throw new TypeError(`Invalid comparator: ${comp}`) 29031 } 29032 29033 this.operator = m[1] !== undefined ? m[1] : '' 29034 if (this.operator === '=') { 29035 this.operator = '' 29036 } 29037 29038 // if it literally is just '>' or '' then allow anything. 29039 if (!m[2]) { 29040 this.semver = ANY 29041 } else { 29042 this.semver = new SemVer(m[2], this.options.loose) 29043 } 29044 } 29045 29046 toString () { 29047 return this.value 29048 } 29049 29050 test (version) { 29051 debug('Comparator.test', version, this.options.loose) 29052 29053 if (this.semver === ANY || version === ANY) { 29054 return true 29055 } 29056 29057 if (typeof version === 'string') { 29058 try { 29059 version = new SemVer(version, this.options) 29060 } catch (er) { 29061 return false 29062 } 29063 } 29064 29065 return cmp(version, this.operator, this.semver, this.options) 29066 } 29067 29068 intersects (comp, options) { 29069 if (!(comp instanceof Comparator)) { 29070 throw new TypeError('a Comparator is required') 29071 } 29072 29073 if (this.operator === '') { 29074 if (this.value === '') { 29075 return true 29076 } 29077 return new Range(comp.value, options).test(this.value) 29078 } else if (comp.operator === '') { 29079 if (comp.value === '') { 29080 return true 29081 } 29082 return new Range(this.value, options).test(comp.semver) 29083 } 29084 29085 options = parseOptions(options) 29086 29087 // Special cases where nothing can possibly be lower 29088 if (options.includePrerelease && 29089 (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { 29090 return false 29091 } 29092 if (!options.includePrerelease && 29093 (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { 29094 return false 29095 } 29096 29097 // Same direction increasing (> or >=) 29098 if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { 29099 return true 29100 } 29101 // Same direction decreasing (< or <=) 29102 if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { 29103 return true 29104 } 29105 // same SemVer and both sides are inclusive (<= or >=) 29106 if ( 29107 (this.semver.version === comp.semver.version) && 29108 this.operator.includes('=') && comp.operator.includes('=')) { 29109 return true 29110 } 29111 // opposite directions less than 29112 if (cmp(this.semver, '<', comp.semver, options) && 29113 this.operator.startsWith('>') && comp.operator.startsWith('<')) { 29114 return true 29115 } 29116 // opposite directions greater than 29117 if (cmp(this.semver, '>', comp.semver, options) && 29118 this.operator.startsWith('<') && comp.operator.startsWith('>')) { 29119 return true 29120 } 29121 return false 29122 } 29123 } 29124 29125 module.exports = Comparator 29126 29127 const parseOptions = __nccwpck_require__(785) 29128 const { safeRe: re, t } = __nccwpck_require__(2566) 29129 const cmp = __nccwpck_require__(5098) 29130 const debug = __nccwpck_require__(427) 29131 const SemVer = __nccwpck_require__(8088) 29132 const Range = __nccwpck_require__(9828) 29133 29134 29135 /***/ }), 29136 29137 /***/ 9828: 29138 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 29139 29140 // hoisted class for cyclic dependency 29141 class Range { 29142 constructor (range, options) { 29143 options = parseOptions(options) 29144 29145 if (range instanceof Range) { 29146 if ( 29147 range.loose === !!options.loose && 29148 range.includePrerelease === !!options.includePrerelease 29149 ) { 29150 return range 29151 } else { 29152 return new Range(range.raw, options) 29153 } 29154 } 29155 29156 if (range instanceof Comparator) { 29157 // just put it in the set and return 29158 this.raw = range.value 29159 this.set = [[range]] 29160 this.format() 29161 return this 29162 } 29163 29164 this.options = options 29165 this.loose = !!options.loose 29166 this.includePrerelease = !!options.includePrerelease 29167 29168 // First reduce all whitespace as much as possible so we do not have to rely 29169 // on potentially slow regexes like \s*. This is then stored and used for 29170 // future error messages as well. 29171 this.raw = range 29172 .trim() 29173 .split(/\s+/) 29174 .join(' ') 29175 29176 // First, split on || 29177 this.set = this.raw 29178 .split('||') 29179 // map the range to a 2d array of comparators 29180 .map(r => this.parseRange(r.trim())) 29181 // throw out any comparator lists that are empty 29182 // this generally means that it was not a valid range, which is allowed 29183 // in loose mode, but will still throw if the WHOLE range is invalid. 29184 .filter(c => c.length) 29185 29186 if (!this.set.length) { 29187 throw new TypeError(`Invalid SemVer Range: ${this.raw}`) 29188 } 29189 29190 // if we have any that are not the null set, throw out null sets. 29191 if (this.set.length > 1) { 29192 // keep the first one, in case they're all null sets 29193 const first = this.set[0] 29194 this.set = this.set.filter(c => !isNullSet(c[0])) 29195 if (this.set.length === 0) { 29196 this.set = [first] 29197 } else if (this.set.length > 1) { 29198 // if we have any that are *, then the range is just * 29199 for (const c of this.set) { 29200 if (c.length === 1 && isAny(c[0])) { 29201 this.set = [c] 29202 break 29203 } 29204 } 29205 } 29206 } 29207 29208 this.format() 29209 } 29210 29211 format () { 29212 this.range = this.set 29213 .map((comps) => comps.join(' ').trim()) 29214 .join('||') 29215 .trim() 29216 return this.range 29217 } 29218 29219 toString () { 29220 return this.range 29221 } 29222 29223 parseRange (range) { 29224 // memoize range parsing for performance. 29225 // this is a very hot path, and fully deterministic. 29226 const memoOpts = 29227 (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | 29228 (this.options.loose && FLAG_LOOSE) 29229 const memoKey = memoOpts + ':' + range 29230 const cached = cache.get(memoKey) 29231 if (cached) { 29232 return cached 29233 } 29234 29235 const loose = this.options.loose 29236 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` 29237 const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] 29238 range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) 29239 debug('hyphen replace', range) 29240 29241 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` 29242 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) 29243 debug('comparator trim', range) 29244 29245 // `~ 1.2.3` => `~1.2.3` 29246 range = range.replace(re[t.TILDETRIM], tildeTrimReplace) 29247 debug('tilde trim', range) 29248 29249 // `^ 1.2.3` => `^1.2.3` 29250 range = range.replace(re[t.CARETTRIM], caretTrimReplace) 29251 debug('caret trim', range) 29252 29253 // At this point, the range is completely trimmed and 29254 // ready to be split into comparators. 29255 29256 let rangeList = range 29257 .split(' ') 29258 .map(comp => parseComparator(comp, this.options)) 29259 .join(' ') 29260 .split(/\s+/) 29261 // >=0.0.0 is equivalent to * 29262 .map(comp => replaceGTE0(comp, this.options)) 29263 29264 if (loose) { 29265 // in loose mode, throw out any that are not valid comparators 29266 rangeList = rangeList.filter(comp => { 29267 debug('loose invalid filter', comp, this.options) 29268 return !!comp.match(re[t.COMPARATORLOOSE]) 29269 }) 29270 } 29271 debug('range list', rangeList) 29272 29273 // if any comparators are the null set, then replace with JUST null set 29274 // if more than one comparator, remove any * comparators 29275 // also, don't include the same comparator more than once 29276 const rangeMap = new Map() 29277 const comparators = rangeList.map(comp => new Comparator(comp, this.options)) 29278 for (const comp of comparators) { 29279 if (isNullSet(comp)) { 29280 return [comp] 29281 } 29282 rangeMap.set(comp.value, comp) 29283 } 29284 if (rangeMap.size > 1 && rangeMap.has('')) { 29285 rangeMap.delete('') 29286 } 29287 29288 const result = [...rangeMap.values()] 29289 cache.set(memoKey, result) 29290 return result 29291 } 29292 29293 intersects (range, options) { 29294 if (!(range instanceof Range)) { 29295 throw new TypeError('a Range is required') 29296 } 29297 29298 return this.set.some((thisComparators) => { 29299 return ( 29300 isSatisfiable(thisComparators, options) && 29301 range.set.some((rangeComparators) => { 29302 return ( 29303 isSatisfiable(rangeComparators, options) && 29304 thisComparators.every((thisComparator) => { 29305 return rangeComparators.every((rangeComparator) => { 29306 return thisComparator.intersects(rangeComparator, options) 29307 }) 29308 }) 29309 ) 29310 }) 29311 ) 29312 }) 29313 } 29314 29315 // if ANY of the sets match ALL of its comparators, then pass 29316 test (version) { 29317 if (!version) { 29318 return false 29319 } 29320 29321 if (typeof version === 'string') { 29322 try { 29323 version = new SemVer(version, this.options) 29324 } catch (er) { 29325 return false 29326 } 29327 } 29328 29329 for (let i = 0; i < this.set.length; i++) { 29330 if (testSet(this.set[i], version, this.options)) { 29331 return true 29332 } 29333 } 29334 return false 29335 } 29336 } 29337 29338 module.exports = Range 29339 29340 const LRU = __nccwpck_require__(7129) 29341 const cache = new LRU({ max: 1000 }) 29342 29343 const parseOptions = __nccwpck_require__(785) 29344 const Comparator = __nccwpck_require__(1532) 29345 const debug = __nccwpck_require__(427) 29346 const SemVer = __nccwpck_require__(8088) 29347 const { 29348 safeRe: re, 29349 t, 29350 comparatorTrimReplace, 29351 tildeTrimReplace, 29352 caretTrimReplace, 29353 } = __nccwpck_require__(2566) 29354 const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(2293) 29355 29356 const isNullSet = c => c.value === '<0.0.0-0' 29357 const isAny = c => c.value === '' 29358 29359 // take a set of comparators and determine whether there 29360 // exists a version which can satisfy it 29361 const isSatisfiable = (comparators, options) => { 29362 let result = true 29363 const remainingComparators = comparators.slice() 29364 let testComparator = remainingComparators.pop() 29365 29366 while (result && remainingComparators.length) { 29367 result = remainingComparators.every((otherComparator) => { 29368 return testComparator.intersects(otherComparator, options) 29369 }) 29370 29371 testComparator = remainingComparators.pop() 29372 } 29373 29374 return result 29375 } 29376 29377 // comprised of xranges, tildes, stars, and gtlt's at this point. 29378 // already replaced the hyphen ranges 29379 // turn into a set of JUST comparators. 29380 const parseComparator = (comp, options) => { 29381 debug('comp', comp, options) 29382 comp = replaceCarets(comp, options) 29383 debug('caret', comp) 29384 comp = replaceTildes(comp, options) 29385 debug('tildes', comp) 29386 comp = replaceXRanges(comp, options) 29387 debug('xrange', comp) 29388 comp = replaceStars(comp, options) 29389 debug('stars', comp) 29390 return comp 29391 } 29392 29393 const isX = id => !id || id.toLowerCase() === 'x' || id === '*' 29394 29395 // ~, ~> --> * (any, kinda silly) 29396 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 29397 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 29398 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 29399 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 29400 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 29401 // ~0.0.1 --> >=0.0.1 <0.1.0-0 29402 const replaceTildes = (comp, options) => { 29403 return comp 29404 .trim() 29405 .split(/\s+/) 29406 .map((c) => replaceTilde(c, options)) 29407 .join(' ') 29408 } 29409 29410 const replaceTilde = (comp, options) => { 29411 const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] 29412 return comp.replace(r, (_, M, m, p, pr) => { 29413 debug('tilde', comp, _, M, m, p, pr) 29414 let ret 29415 29416 if (isX(M)) { 29417 ret = '' 29418 } else if (isX(m)) { 29419 ret = `>=${M}.0.0 <${+M + 1}.0.0-0` 29420 } else if (isX(p)) { 29421 // ~1.2 == >=1.2.0 <1.3.0-0 29422 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` 29423 } else if (pr) { 29424 debug('replaceTilde pr', pr) 29425 ret = `>=${M}.${m}.${p}-${pr 29426 } <${M}.${+m + 1}.0-0` 29427 } else { 29428 // ~1.2.3 == >=1.2.3 <1.3.0-0 29429 ret = `>=${M}.${m}.${p 29430 } <${M}.${+m + 1}.0-0` 29431 } 29432 29433 debug('tilde return', ret) 29434 return ret 29435 }) 29436 } 29437 29438 // ^ --> * (any, kinda silly) 29439 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 29440 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 29441 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 29442 // ^1.2.3 --> >=1.2.3 <2.0.0-0 29443 // ^1.2.0 --> >=1.2.0 <2.0.0-0 29444 // ^0.0.1 --> >=0.0.1 <0.0.2-0 29445 // ^0.1.0 --> >=0.1.0 <0.2.0-0 29446 const replaceCarets = (comp, options) => { 29447 return comp 29448 .trim() 29449 .split(/\s+/) 29450 .map((c) => replaceCaret(c, options)) 29451 .join(' ') 29452 } 29453 29454 const replaceCaret = (comp, options) => { 29455 debug('caret', comp, options) 29456 const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] 29457 const z = options.includePrerelease ? '-0' : '' 29458 return comp.replace(r, (_, M, m, p, pr) => { 29459 debug('caret', comp, _, M, m, p, pr) 29460 let ret 29461 29462 if (isX(M)) { 29463 ret = '' 29464 } else if (isX(m)) { 29465 ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` 29466 } else if (isX(p)) { 29467 if (M === '0') { 29468 ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` 29469 } else { 29470 ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` 29471 } 29472 } else if (pr) { 29473 debug('replaceCaret pr', pr) 29474 if (M === '0') { 29475 if (m === '0') { 29476 ret = `>=${M}.${m}.${p}-${pr 29477 } <${M}.${m}.${+p + 1}-0` 29478 } else { 29479 ret = `>=${M}.${m}.${p}-${pr 29480 } <${M}.${+m + 1}.0-0` 29481 } 29482 } else { 29483 ret = `>=${M}.${m}.${p}-${pr 29484 } <${+M + 1}.0.0-0` 29485 } 29486 } else { 29487 debug('no pr') 29488 if (M === '0') { 29489 if (m === '0') { 29490 ret = `>=${M}.${m}.${p 29491 }${z} <${M}.${m}.${+p + 1}-0` 29492 } else { 29493 ret = `>=${M}.${m}.${p 29494 }${z} <${M}.${+m + 1}.0-0` 29495 } 29496 } else { 29497 ret = `>=${M}.${m}.${p 29498 } <${+M + 1}.0.0-0` 29499 } 29500 } 29501 29502 debug('caret return', ret) 29503 return ret 29504 }) 29505 } 29506 29507 const replaceXRanges = (comp, options) => { 29508 debug('replaceXRanges', comp, options) 29509 return comp 29510 .split(/\s+/) 29511 .map((c) => replaceXRange(c, options)) 29512 .join(' ') 29513 } 29514 29515 const replaceXRange = (comp, options) => { 29516 comp = comp.trim() 29517 const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] 29518 return comp.replace(r, (ret, gtlt, M, m, p, pr) => { 29519 debug('xRange', comp, ret, gtlt, M, m, p, pr) 29520 const xM = isX(M) 29521 const xm = xM || isX(m) 29522 const xp = xm || isX(p) 29523 const anyX = xp 29524 29525 if (gtlt === '=' && anyX) { 29526 gtlt = '' 29527 } 29528 29529 // if we're including prereleases in the match, then we need 29530 // to fix this to -0, the lowest possible prerelease value 29531 pr = options.includePrerelease ? '-0' : '' 29532 29533 if (xM) { 29534 if (gtlt === '>' || gtlt === '<') { 29535 // nothing is allowed 29536 ret = '<0.0.0-0' 29537 } else { 29538 // nothing is forbidden 29539 ret = '*' 29540 } 29541 } else if (gtlt && anyX) { 29542 // we know patch is an x, because we have any x at all. 29543 // replace X with 0 29544 if (xm) { 29545 m = 0 29546 } 29547 p = 0 29548 29549 if (gtlt === '>') { 29550 // >1 => >=2.0.0 29551 // >1.2 => >=1.3.0 29552 gtlt = '>=' 29553 if (xm) { 29554 M = +M + 1 29555 m = 0 29556 p = 0 29557 } else { 29558 m = +m + 1 29559 p = 0 29560 } 29561 } else if (gtlt === '<=') { 29562 // <=0.7.x is actually <0.8.0, since any 0.7.x should 29563 // pass. Similarly, <=7.x is actually <8.0.0, etc. 29564 gtlt = '<' 29565 if (xm) { 29566 M = +M + 1 29567 } else { 29568 m = +m + 1 29569 } 29570 } 29571 29572 if (gtlt === '<') { 29573 pr = '-0' 29574 } 29575 29576 ret = `${gtlt + M}.${m}.${p}${pr}` 29577 } else if (xm) { 29578 ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` 29579 } else if (xp) { 29580 ret = `>=${M}.${m}.0${pr 29581 } <${M}.${+m + 1}.0-0` 29582 } 29583 29584 debug('xRange return', ret) 29585 29586 return ret 29587 }) 29588 } 29589 29590 // Because * is AND-ed with everything else in the comparator, 29591 // and '' means "any version", just remove the *s entirely. 29592 const replaceStars = (comp, options) => { 29593 debug('replaceStars', comp, options) 29594 // Looseness is ignored here. star is always as loose as it gets! 29595 return comp 29596 .trim() 29597 .replace(re[t.STAR], '') 29598 } 29599 29600 const replaceGTE0 = (comp, options) => { 29601 debug('replaceGTE0', comp, options) 29602 return comp 29603 .trim() 29604 .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') 29605 } 29606 29607 // This function is passed to string.replace(re[t.HYPHENRANGE]) 29608 // M, m, patch, prerelease, build 29609 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 29610 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do 29611 // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 29612 const hyphenReplace = incPr => ($0, 29613 from, fM, fm, fp, fpr, fb, 29614 to, tM, tm, tp, tpr, tb) => { 29615 if (isX(fM)) { 29616 from = '' 29617 } else if (isX(fm)) { 29618 from = `>=${fM}.0.0${incPr ? '-0' : ''}` 29619 } else if (isX(fp)) { 29620 from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` 29621 } else if (fpr) { 29622 from = `>=${from}` 29623 } else { 29624 from = `>=${from}${incPr ? '-0' : ''}` 29625 } 29626 29627 if (isX(tM)) { 29628 to = '' 29629 } else if (isX(tm)) { 29630 to = `<${+tM + 1}.0.0-0` 29631 } else if (isX(tp)) { 29632 to = `<${tM}.${+tm + 1}.0-0` 29633 } else if (tpr) { 29634 to = `<=${tM}.${tm}.${tp}-${tpr}` 29635 } else if (incPr) { 29636 to = `<${tM}.${tm}.${+tp + 1}-0` 29637 } else { 29638 to = `<=${to}` 29639 } 29640 29641 return `${from} ${to}`.trim() 29642 } 29643 29644 const testSet = (set, version, options) => { 29645 for (let i = 0; i < set.length; i++) { 29646 if (!set[i].test(version)) { 29647 return false 29648 } 29649 } 29650 29651 if (version.prerelease.length && !options.includePrerelease) { 29652 // Find the set of versions that are allowed to have prereleases 29653 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 29654 // That should allow `1.2.3-pr.2` to pass. 29655 // However, `1.2.4-alpha.notready` should NOT be allowed, 29656 // even though it's within the range set by the comparators. 29657 for (let i = 0; i < set.length; i++) { 29658 debug(set[i].semver) 29659 if (set[i].semver === Comparator.ANY) { 29660 continue 29661 } 29662 29663 if (set[i].semver.prerelease.length > 0) { 29664 const allowed = set[i].semver 29665 if (allowed.major === version.major && 29666 allowed.minor === version.minor && 29667 allowed.patch === version.patch) { 29668 return true 29669 } 29670 } 29671 } 29672 29673 // Version has a -pre, but it's not one of the ones we like. 29674 return false 29675 } 29676 29677 return true 29678 } 29679 29680 29681 /***/ }), 29682 29683 /***/ 8088: 29684 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 29685 29686 const debug = __nccwpck_require__(427) 29687 const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(2293) 29688 const { safeRe: re, t } = __nccwpck_require__(2566) 29689 29690 const parseOptions = __nccwpck_require__(785) 29691 const { compareIdentifiers } = __nccwpck_require__(2463) 29692 class SemVer { 29693 constructor (version, options) { 29694 options = parseOptions(options) 29695 29696 if (version instanceof SemVer) { 29697 if (version.loose === !!options.loose && 29698 version.includePrerelease === !!options.includePrerelease) { 29699 return version 29700 } else { 29701 version = version.version 29702 } 29703 } else if (typeof version !== 'string') { 29704 throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) 29705 } 29706 29707 if (version.length > MAX_LENGTH) { 29708 throw new TypeError( 29709 `version is longer than ${MAX_LENGTH} characters` 29710 ) 29711 } 29712 29713 debug('SemVer', version, options) 29714 this.options = options 29715 this.loose = !!options.loose 29716 // this isn't actually relevant for versions, but keep it so that we 29717 // don't run into trouble passing this.options around. 29718 this.includePrerelease = !!options.includePrerelease 29719 29720 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) 29721 29722 if (!m) { 29723 throw new TypeError(`Invalid Version: ${version}`) 29724 } 29725 29726 this.raw = version 29727 29728 // these are actually numbers 29729 this.major = +m[1] 29730 this.minor = +m[2] 29731 this.patch = +m[3] 29732 29733 if (this.major > MAX_SAFE_INTEGER || this.major < 0) { 29734 throw new TypeError('Invalid major version') 29735 } 29736 29737 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { 29738 throw new TypeError('Invalid minor version') 29739 } 29740 29741 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { 29742 throw new TypeError('Invalid patch version') 29743 } 29744 29745 // numberify any prerelease numeric ids 29746 if (!m[4]) { 29747 this.prerelease = [] 29748 } else { 29749 this.prerelease = m[4].split('.').map((id) => { 29750 if (/^[0-9]+$/.test(id)) { 29751 const num = +id 29752 if (num >= 0 && num < MAX_SAFE_INTEGER) { 29753 return num 29754 } 29755 } 29756 return id 29757 }) 29758 } 29759 29760 this.build = m[5] ? m[5].split('.') : [] 29761 this.format() 29762 } 29763 29764 format () { 29765 this.version = `${this.major}.${this.minor}.${this.patch}` 29766 if (this.prerelease.length) { 29767 this.version += `-${this.prerelease.join('.')}` 29768 } 29769 return this.version 29770 } 29771 29772 toString () { 29773 return this.version 29774 } 29775 29776 compare (other) { 29777 debug('SemVer.compare', this.version, this.options, other) 29778 if (!(other instanceof SemVer)) { 29779 if (typeof other === 'string' && other === this.version) { 29780 return 0 29781 } 29782 other = new SemVer(other, this.options) 29783 } 29784 29785 if (other.version === this.version) { 29786 return 0 29787 } 29788 29789 return this.compareMain(other) || this.comparePre(other) 29790 } 29791 29792 compareMain (other) { 29793 if (!(other instanceof SemVer)) { 29794 other = new SemVer(other, this.options) 29795 } 29796 29797 return ( 29798 compareIdentifiers(this.major, other.major) || 29799 compareIdentifiers(this.minor, other.minor) || 29800 compareIdentifiers(this.patch, other.patch) 29801 ) 29802 } 29803 29804 comparePre (other) { 29805 if (!(other instanceof SemVer)) { 29806 other = new SemVer(other, this.options) 29807 } 29808 29809 // NOT having a prerelease is > having one 29810 if (this.prerelease.length && !other.prerelease.length) { 29811 return -1 29812 } else if (!this.prerelease.length && other.prerelease.length) { 29813 return 1 29814 } else if (!this.prerelease.length && !other.prerelease.length) { 29815 return 0 29816 } 29817 29818 let i = 0 29819 do { 29820 const a = this.prerelease[i] 29821 const b = other.prerelease[i] 29822 debug('prerelease compare', i, a, b) 29823 if (a === undefined && b === undefined) { 29824 return 0 29825 } else if (b === undefined) { 29826 return 1 29827 } else if (a === undefined) { 29828 return -1 29829 } else if (a === b) { 29830 continue 29831 } else { 29832 return compareIdentifiers(a, b) 29833 } 29834 } while (++i) 29835 } 29836 29837 compareBuild (other) { 29838 if (!(other instanceof SemVer)) { 29839 other = new SemVer(other, this.options) 29840 } 29841 29842 let i = 0 29843 do { 29844 const a = this.build[i] 29845 const b = other.build[i] 29846 debug('prerelease compare', i, a, b) 29847 if (a === undefined && b === undefined) { 29848 return 0 29849 } else if (b === undefined) { 29850 return 1 29851 } else if (a === undefined) { 29852 return -1 29853 } else if (a === b) { 29854 continue 29855 } else { 29856 return compareIdentifiers(a, b) 29857 } 29858 } while (++i) 29859 } 29860 29861 // preminor will bump the version up to the next minor release, and immediately 29862 // down to pre-release. premajor and prepatch work the same way. 29863 inc (release, identifier, identifierBase) { 29864 switch (release) { 29865 case 'premajor': 29866 this.prerelease.length = 0 29867 this.patch = 0 29868 this.minor = 0 29869 this.major++ 29870 this.inc('pre', identifier, identifierBase) 29871 break 29872 case 'preminor': 29873 this.prerelease.length = 0 29874 this.patch = 0 29875 this.minor++ 29876 this.inc('pre', identifier, identifierBase) 29877 break 29878 case 'prepatch': 29879 // If this is already a prerelease, it will bump to the next version 29880 // drop any prereleases that might already exist, since they are not 29881 // relevant at this point. 29882 this.prerelease.length = 0 29883 this.inc('patch', identifier, identifierBase) 29884 this.inc('pre', identifier, identifierBase) 29885 break 29886 // If the input is a non-prerelease version, this acts the same as 29887 // prepatch. 29888 case 'prerelease': 29889 if (this.prerelease.length === 0) { 29890 this.inc('patch', identifier, identifierBase) 29891 } 29892 this.inc('pre', identifier, identifierBase) 29893 break 29894 29895 case 'major': 29896 // If this is a pre-major version, bump up to the same major version. 29897 // Otherwise increment major. 29898 // 1.0.0-5 bumps to 1.0.0 29899 // 1.1.0 bumps to 2.0.0 29900 if ( 29901 this.minor !== 0 || 29902 this.patch !== 0 || 29903 this.prerelease.length === 0 29904 ) { 29905 this.major++ 29906 } 29907 this.minor = 0 29908 this.patch = 0 29909 this.prerelease = [] 29910 break 29911 case 'minor': 29912 // If this is a pre-minor version, bump up to the same minor version. 29913 // Otherwise increment minor. 29914 // 1.2.0-5 bumps to 1.2.0 29915 // 1.2.1 bumps to 1.3.0 29916 if (this.patch !== 0 || this.prerelease.length === 0) { 29917 this.minor++ 29918 } 29919 this.patch = 0 29920 this.prerelease = [] 29921 break 29922 case 'patch': 29923 // If this is not a pre-release version, it will increment the patch. 29924 // If it is a pre-release it will bump up to the same patch version. 29925 // 1.2.0-5 patches to 1.2.0 29926 // 1.2.0 patches to 1.2.1 29927 if (this.prerelease.length === 0) { 29928 this.patch++ 29929 } 29930 this.prerelease = [] 29931 break 29932 // This probably shouldn't be used publicly. 29933 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. 29934 case 'pre': { 29935 const base = Number(identifierBase) ? 1 : 0 29936 29937 if (!identifier && identifierBase === false) { 29938 throw new Error('invalid increment argument: identifier is empty') 29939 } 29940 29941 if (this.prerelease.length === 0) { 29942 this.prerelease = [base] 29943 } else { 29944 let i = this.prerelease.length 29945 while (--i >= 0) { 29946 if (typeof this.prerelease[i] === 'number') { 29947 this.prerelease[i]++ 29948 i = -2 29949 } 29950 } 29951 if (i === -1) { 29952 // didn't increment anything 29953 if (identifier === this.prerelease.join('.') && identifierBase === false) { 29954 throw new Error('invalid increment argument: identifier already exists') 29955 } 29956 this.prerelease.push(base) 29957 } 29958 } 29959 if (identifier) { 29960 // 1.2.0-beta.1 bumps to 1.2.0-beta.2, 29961 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 29962 let prerelease = [identifier, base] 29963 if (identifierBase === false) { 29964 prerelease = [identifier] 29965 } 29966 if (compareIdentifiers(this.prerelease[0], identifier) === 0) { 29967 if (isNaN(this.prerelease[1])) { 29968 this.prerelease = prerelease 29969 } 29970 } else { 29971 this.prerelease = prerelease 29972 } 29973 } 29974 break 29975 } 29976 default: 29977 throw new Error(`invalid increment argument: ${release}`) 29978 } 29979 this.raw = this.format() 29980 if (this.build.length) { 29981 this.raw += `+${this.build.join('.')}` 29982 } 29983 return this 29984 } 29985 } 29986 29987 module.exports = SemVer 29988 29989 29990 /***/ }), 29991 29992 /***/ 8848: 29993 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 29994 29995 const parse = __nccwpck_require__(5925) 29996 const clean = (version, options) => { 29997 const s = parse(version.trim().replace(/^[=v]+/, ''), options) 29998 return s ? s.version : null 29999 } 30000 module.exports = clean 30001 30002 30003 /***/ }), 30004 30005 /***/ 5098: 30006 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30007 30008 const eq = __nccwpck_require__(1898) 30009 const neq = __nccwpck_require__(6017) 30010 const gt = __nccwpck_require__(4123) 30011 const gte = __nccwpck_require__(5522) 30012 const lt = __nccwpck_require__(194) 30013 const lte = __nccwpck_require__(7520) 30014 30015 const cmp = (a, op, b, loose) => { 30016 switch (op) { 30017 case '===': 30018 if (typeof a === 'object') { 30019 a = a.version 30020 } 30021 if (typeof b === 'object') { 30022 b = b.version 30023 } 30024 return a === b 30025 30026 case '!==': 30027 if (typeof a === 'object') { 30028 a = a.version 30029 } 30030 if (typeof b === 'object') { 30031 b = b.version 30032 } 30033 return a !== b 30034 30035 case '': 30036 case '=': 30037 case '==': 30038 return eq(a, b, loose) 30039 30040 case '!=': 30041 return neq(a, b, loose) 30042 30043 case '>': 30044 return gt(a, b, loose) 30045 30046 case '>=': 30047 return gte(a, b, loose) 30048 30049 case '<': 30050 return lt(a, b, loose) 30051 30052 case '<=': 30053 return lte(a, b, loose) 30054 30055 default: 30056 throw new TypeError(`Invalid operator: ${op}`) 30057 } 30058 } 30059 module.exports = cmp 30060 30061 30062 /***/ }), 30063 30064 /***/ 3466: 30065 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30066 30067 const SemVer = __nccwpck_require__(8088) 30068 const parse = __nccwpck_require__(5925) 30069 const { safeRe: re, t } = __nccwpck_require__(2566) 30070 30071 const coerce = (version, options) => { 30072 if (version instanceof SemVer) { 30073 return version 30074 } 30075 30076 if (typeof version === 'number') { 30077 version = String(version) 30078 } 30079 30080 if (typeof version !== 'string') { 30081 return null 30082 } 30083 30084 options = options || {} 30085 30086 let match = null 30087 if (!options.rtl) { 30088 match = version.match(re[t.COERCE]) 30089 } else { 30090 // Find the right-most coercible string that does not share 30091 // a terminus with a more left-ward coercible string. 30092 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' 30093 // 30094 // Walk through the string checking with a /g regexp 30095 // Manually set the index so as to pick up overlapping matches. 30096 // Stop when we get a match that ends at the string end, since no 30097 // coercible string can be more right-ward without the same terminus. 30098 let next 30099 while ((next = re[t.COERCERTL].exec(version)) && 30100 (!match || match.index + match[0].length !== version.length) 30101 ) { 30102 if (!match || 30103 next.index + next[0].length !== match.index + match[0].length) { 30104 match = next 30105 } 30106 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length 30107 } 30108 // leave it in a clean state 30109 re[t.COERCERTL].lastIndex = -1 30110 } 30111 30112 if (match === null) { 30113 return null 30114 } 30115 30116 return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) 30117 } 30118 module.exports = coerce 30119 30120 30121 /***/ }), 30122 30123 /***/ 2156: 30124 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30125 30126 const SemVer = __nccwpck_require__(8088) 30127 const compareBuild = (a, b, loose) => { 30128 const versionA = new SemVer(a, loose) 30129 const versionB = new SemVer(b, loose) 30130 return versionA.compare(versionB) || versionA.compareBuild(versionB) 30131 } 30132 module.exports = compareBuild 30133 30134 30135 /***/ }), 30136 30137 /***/ 2804: 30138 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30139 30140 const compare = __nccwpck_require__(4309) 30141 const compareLoose = (a, b) => compare(a, b, true) 30142 module.exports = compareLoose 30143 30144 30145 /***/ }), 30146 30147 /***/ 4309: 30148 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30149 30150 const SemVer = __nccwpck_require__(8088) 30151 const compare = (a, b, loose) => 30152 new SemVer(a, loose).compare(new SemVer(b, loose)) 30153 30154 module.exports = compare 30155 30156 30157 /***/ }), 30158 30159 /***/ 4297: 30160 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30161 30162 const parse = __nccwpck_require__(5925) 30163 30164 const diff = (version1, version2) => { 30165 const v1 = parse(version1, null, true) 30166 const v2 = parse(version2, null, true) 30167 const comparison = v1.compare(v2) 30168 30169 if (comparison === 0) { 30170 return null 30171 } 30172 30173 const v1Higher = comparison > 0 30174 const highVersion = v1Higher ? v1 : v2 30175 const lowVersion = v1Higher ? v2 : v1 30176 const highHasPre = !!highVersion.prerelease.length 30177 const lowHasPre = !!lowVersion.prerelease.length 30178 30179 if (lowHasPre && !highHasPre) { 30180 // Going from prerelease -> no prerelease requires some special casing 30181 30182 // If the low version has only a major, then it will always be a major 30183 // Some examples: 30184 // 1.0.0-1 -> 1.0.0 30185 // 1.0.0-1 -> 1.1.1 30186 // 1.0.0-1 -> 2.0.0 30187 if (!lowVersion.patch && !lowVersion.minor) { 30188 return 'major' 30189 } 30190 30191 // Otherwise it can be determined by checking the high version 30192 30193 if (highVersion.patch) { 30194 // anything higher than a patch bump would result in the wrong version 30195 return 'patch' 30196 } 30197 30198 if (highVersion.minor) { 30199 // anything higher than a minor bump would result in the wrong version 30200 return 'minor' 30201 } 30202 30203 // bumping major/minor/patch all have same result 30204 return 'major' 30205 } 30206 30207 // add the `pre` prefix if we are going to a prerelease version 30208 const prefix = highHasPre ? 'pre' : '' 30209 30210 if (v1.major !== v2.major) { 30211 return prefix + 'major' 30212 } 30213 30214 if (v1.minor !== v2.minor) { 30215 return prefix + 'minor' 30216 } 30217 30218 if (v1.patch !== v2.patch) { 30219 return prefix + 'patch' 30220 } 30221 30222 // high and low are preleases 30223 return 'prerelease' 30224 } 30225 30226 module.exports = diff 30227 30228 30229 /***/ }), 30230 30231 /***/ 1898: 30232 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30233 30234 const compare = __nccwpck_require__(4309) 30235 const eq = (a, b, loose) => compare(a, b, loose) === 0 30236 module.exports = eq 30237 30238 30239 /***/ }), 30240 30241 /***/ 4123: 30242 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30243 30244 const compare = __nccwpck_require__(4309) 30245 const gt = (a, b, loose) => compare(a, b, loose) > 0 30246 module.exports = gt 30247 30248 30249 /***/ }), 30250 30251 /***/ 5522: 30252 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30253 30254 const compare = __nccwpck_require__(4309) 30255 const gte = (a, b, loose) => compare(a, b, loose) >= 0 30256 module.exports = gte 30257 30258 30259 /***/ }), 30260 30261 /***/ 900: 30262 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30263 30264 const SemVer = __nccwpck_require__(8088) 30265 30266 const inc = (version, release, options, identifier, identifierBase) => { 30267 if (typeof (options) === 'string') { 30268 identifierBase = identifier 30269 identifier = options 30270 options = undefined 30271 } 30272 30273 try { 30274 return new SemVer( 30275 version instanceof SemVer ? version.version : version, 30276 options 30277 ).inc(release, identifier, identifierBase).version 30278 } catch (er) { 30279 return null 30280 } 30281 } 30282 module.exports = inc 30283 30284 30285 /***/ }), 30286 30287 /***/ 194: 30288 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30289 30290 const compare = __nccwpck_require__(4309) 30291 const lt = (a, b, loose) => compare(a, b, loose) < 0 30292 module.exports = lt 30293 30294 30295 /***/ }), 30296 30297 /***/ 7520: 30298 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30299 30300 const compare = __nccwpck_require__(4309) 30301 const lte = (a, b, loose) => compare(a, b, loose) <= 0 30302 module.exports = lte 30303 30304 30305 /***/ }), 30306 30307 /***/ 6688: 30308 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30309 30310 const SemVer = __nccwpck_require__(8088) 30311 const major = (a, loose) => new SemVer(a, loose).major 30312 module.exports = major 30313 30314 30315 /***/ }), 30316 30317 /***/ 8447: 30318 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30319 30320 const SemVer = __nccwpck_require__(8088) 30321 const minor = (a, loose) => new SemVer(a, loose).minor 30322 module.exports = minor 30323 30324 30325 /***/ }), 30326 30327 /***/ 6017: 30328 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30329 30330 const compare = __nccwpck_require__(4309) 30331 const neq = (a, b, loose) => compare(a, b, loose) !== 0 30332 module.exports = neq 30333 30334 30335 /***/ }), 30336 30337 /***/ 5925: 30338 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30339 30340 const SemVer = __nccwpck_require__(8088) 30341 const parse = (version, options, throwErrors = false) => { 30342 if (version instanceof SemVer) { 30343 return version 30344 } 30345 try { 30346 return new SemVer(version, options) 30347 } catch (er) { 30348 if (!throwErrors) { 30349 return null 30350 } 30351 throw er 30352 } 30353 } 30354 30355 module.exports = parse 30356 30357 30358 /***/ }), 30359 30360 /***/ 2866: 30361 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30362 30363 const SemVer = __nccwpck_require__(8088) 30364 const patch = (a, loose) => new SemVer(a, loose).patch 30365 module.exports = patch 30366 30367 30368 /***/ }), 30369 30370 /***/ 4016: 30371 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30372 30373 const parse = __nccwpck_require__(5925) 30374 const prerelease = (version, options) => { 30375 const parsed = parse(version, options) 30376 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null 30377 } 30378 module.exports = prerelease 30379 30380 30381 /***/ }), 30382 30383 /***/ 6417: 30384 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30385 30386 const compare = __nccwpck_require__(4309) 30387 const rcompare = (a, b, loose) => compare(b, a, loose) 30388 module.exports = rcompare 30389 30390 30391 /***/ }), 30392 30393 /***/ 8701: 30394 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30395 30396 const compareBuild = __nccwpck_require__(2156) 30397 const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) 30398 module.exports = rsort 30399 30400 30401 /***/ }), 30402 30403 /***/ 6055: 30404 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30405 30406 const Range = __nccwpck_require__(9828) 30407 const satisfies = (version, range, options) => { 30408 try { 30409 range = new Range(range, options) 30410 } catch (er) { 30411 return false 30412 } 30413 return range.test(version) 30414 } 30415 module.exports = satisfies 30416 30417 30418 /***/ }), 30419 30420 /***/ 1426: 30421 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30422 30423 const compareBuild = __nccwpck_require__(2156) 30424 const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) 30425 module.exports = sort 30426 30427 30428 /***/ }), 30429 30430 /***/ 9601: 30431 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30432 30433 const parse = __nccwpck_require__(5925) 30434 const valid = (version, options) => { 30435 const v = parse(version, options) 30436 return v ? v.version : null 30437 } 30438 module.exports = valid 30439 30440 30441 /***/ }), 30442 30443 /***/ 1383: 30444 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30445 30446 // just pre-load all the stuff that index.js lazily exports 30447 const internalRe = __nccwpck_require__(2566) 30448 const constants = __nccwpck_require__(2293) 30449 const SemVer = __nccwpck_require__(8088) 30450 const identifiers = __nccwpck_require__(2463) 30451 const parse = __nccwpck_require__(5925) 30452 const valid = __nccwpck_require__(9601) 30453 const clean = __nccwpck_require__(8848) 30454 const inc = __nccwpck_require__(900) 30455 const diff = __nccwpck_require__(4297) 30456 const major = __nccwpck_require__(6688) 30457 const minor = __nccwpck_require__(8447) 30458 const patch = __nccwpck_require__(2866) 30459 const prerelease = __nccwpck_require__(4016) 30460 const compare = __nccwpck_require__(4309) 30461 const rcompare = __nccwpck_require__(6417) 30462 const compareLoose = __nccwpck_require__(2804) 30463 const compareBuild = __nccwpck_require__(2156) 30464 const sort = __nccwpck_require__(1426) 30465 const rsort = __nccwpck_require__(8701) 30466 const gt = __nccwpck_require__(4123) 30467 const lt = __nccwpck_require__(194) 30468 const eq = __nccwpck_require__(1898) 30469 const neq = __nccwpck_require__(6017) 30470 const gte = __nccwpck_require__(5522) 30471 const lte = __nccwpck_require__(7520) 30472 const cmp = __nccwpck_require__(5098) 30473 const coerce = __nccwpck_require__(3466) 30474 const Comparator = __nccwpck_require__(1532) 30475 const Range = __nccwpck_require__(9828) 30476 const satisfies = __nccwpck_require__(6055) 30477 const toComparators = __nccwpck_require__(2706) 30478 const maxSatisfying = __nccwpck_require__(579) 30479 const minSatisfying = __nccwpck_require__(832) 30480 const minVersion = __nccwpck_require__(4179) 30481 const validRange = __nccwpck_require__(2098) 30482 const outside = __nccwpck_require__(420) 30483 const gtr = __nccwpck_require__(9380) 30484 const ltr = __nccwpck_require__(3323) 30485 const intersects = __nccwpck_require__(7008) 30486 const simplifyRange = __nccwpck_require__(6561) 30487 const subset = __nccwpck_require__(7863) 30488 module.exports = { 30489 parse, 30490 valid, 30491 clean, 30492 inc, 30493 diff, 30494 major, 30495 minor, 30496 patch, 30497 prerelease, 30498 compare, 30499 rcompare, 30500 compareLoose, 30501 compareBuild, 30502 sort, 30503 rsort, 30504 gt, 30505 lt, 30506 eq, 30507 neq, 30508 gte, 30509 lte, 30510 cmp, 30511 coerce, 30512 Comparator, 30513 Range, 30514 satisfies, 30515 toComparators, 30516 maxSatisfying, 30517 minSatisfying, 30518 minVersion, 30519 validRange, 30520 outside, 30521 gtr, 30522 ltr, 30523 intersects, 30524 simplifyRange, 30525 subset, 30526 SemVer, 30527 re: internalRe.re, 30528 src: internalRe.src, 30529 tokens: internalRe.t, 30530 SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, 30531 RELEASE_TYPES: constants.RELEASE_TYPES, 30532 compareIdentifiers: identifiers.compareIdentifiers, 30533 rcompareIdentifiers: identifiers.rcompareIdentifiers, 30534 } 30535 30536 30537 /***/ }), 30538 30539 /***/ 2293: 30540 /***/ ((module) => { 30541 30542 // Note: this is the semver.org version of the spec that it implements 30543 // Not necessarily the package version of this code. 30544 const SEMVER_SPEC_VERSION = '2.0.0' 30545 30546 const MAX_LENGTH = 256 30547 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 30548 /* istanbul ignore next */ 9007199254740991 30549 30550 // Max safe segment length for coercion. 30551 const MAX_SAFE_COMPONENT_LENGTH = 16 30552 30553 // Max safe length for a build identifier. The max length minus 6 characters for 30554 // the shortest version with a build 0.0.0+BUILD. 30555 const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 30556 30557 const RELEASE_TYPES = [ 30558 'major', 30559 'premajor', 30560 'minor', 30561 'preminor', 30562 'patch', 30563 'prepatch', 30564 'prerelease', 30565 ] 30566 30567 module.exports = { 30568 MAX_LENGTH, 30569 MAX_SAFE_COMPONENT_LENGTH, 30570 MAX_SAFE_BUILD_LENGTH, 30571 MAX_SAFE_INTEGER, 30572 RELEASE_TYPES, 30573 SEMVER_SPEC_VERSION, 30574 FLAG_INCLUDE_PRERELEASE: 0b001, 30575 FLAG_LOOSE: 0b010, 30576 } 30577 30578 30579 /***/ }), 30580 30581 /***/ 427: 30582 /***/ ((module) => { 30583 30584 const debug = ( 30585 typeof process === 'object' && 30586 process.env && 30587 process.env.NODE_DEBUG && 30588 /\bsemver\b/i.test(process.env.NODE_DEBUG) 30589 ) ? (...args) => console.error('SEMVER', ...args) 30590 : () => {} 30591 30592 module.exports = debug 30593 30594 30595 /***/ }), 30596 30597 /***/ 2463: 30598 /***/ ((module) => { 30599 30600 const numeric = /^[0-9]+$/ 30601 const compareIdentifiers = (a, b) => { 30602 const anum = numeric.test(a) 30603 const bnum = numeric.test(b) 30604 30605 if (anum && bnum) { 30606 a = +a 30607 b = +b 30608 } 30609 30610 return a === b ? 0 30611 : (anum && !bnum) ? -1 30612 : (bnum && !anum) ? 1 30613 : a < b ? -1 30614 : 1 30615 } 30616 30617 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) 30618 30619 module.exports = { 30620 compareIdentifiers, 30621 rcompareIdentifiers, 30622 } 30623 30624 30625 /***/ }), 30626 30627 /***/ 785: 30628 /***/ ((module) => { 30629 30630 // parse out just the options we care about 30631 const looseOption = Object.freeze({ loose: true }) 30632 const emptyOpts = Object.freeze({ }) 30633 const parseOptions = options => { 30634 if (!options) { 30635 return emptyOpts 30636 } 30637 30638 if (typeof options !== 'object') { 30639 return looseOption 30640 } 30641 30642 return options 30643 } 30644 module.exports = parseOptions 30645 30646 30647 /***/ }), 30648 30649 /***/ 2566: 30650 /***/ ((module, exports, __nccwpck_require__) => { 30651 30652 const { 30653 MAX_SAFE_COMPONENT_LENGTH, 30654 MAX_SAFE_BUILD_LENGTH, 30655 MAX_LENGTH, 30656 } = __nccwpck_require__(2293) 30657 const debug = __nccwpck_require__(427) 30658 exports = module.exports = {} 30659 30660 // The actual regexps go on exports.re 30661 const re = exports.re = [] 30662 const safeRe = exports.safeRe = [] 30663 const src = exports.src = [] 30664 const t = exports.t = {} 30665 let R = 0 30666 30667 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' 30668 30669 // Replace some greedy regex tokens to prevent regex dos issues. These regex are 30670 // used internally via the safeRe object since all inputs in this library get 30671 // normalized first to trim and collapse all extra whitespace. The original 30672 // regexes are exported for userland consumption and lower level usage. A 30673 // future breaking change could export the safer regex only with a note that 30674 // all input should have extra whitespace removed. 30675 const safeRegexReplacements = [ 30676 ['\\s', 1], 30677 ['\\d', MAX_LENGTH], 30678 [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], 30679 ] 30680 30681 const makeSafeRegex = (value) => { 30682 for (const [token, max] of safeRegexReplacements) { 30683 value = value 30684 .split(`${token}*`).join(`${token}{0,${max}}`) 30685 .split(`${token}+`).join(`${token}{1,${max}}`) 30686 } 30687 return value 30688 } 30689 30690 const createToken = (name, value, isGlobal) => { 30691 const safe = makeSafeRegex(value) 30692 const index = R++ 30693 debug(name, index, value) 30694 t[name] = index 30695 src[index] = value 30696 re[index] = new RegExp(value, isGlobal ? 'g' : undefined) 30697 safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) 30698 } 30699 30700 // The following Regular Expressions can be used for tokenizing, 30701 // validating, and parsing SemVer version strings. 30702 30703 // ## Numeric Identifier 30704 // A single `0`, or a non-zero digit followed by zero or more digits. 30705 30706 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') 30707 createToken('NUMERICIDENTIFIERLOOSE', '\\d+') 30708 30709 // ## Non-numeric Identifier 30710 // Zero or more digits, followed by a letter or hyphen, and then zero or 30711 // more letters, digits, or hyphens. 30712 30713 createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) 30714 30715 // ## Main Version 30716 // Three dot-separated numeric identifiers. 30717 30718 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + 30719 `(${src[t.NUMERICIDENTIFIER]})\\.` + 30720 `(${src[t.NUMERICIDENTIFIER]})`) 30721 30722 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + 30723 `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + 30724 `(${src[t.NUMERICIDENTIFIERLOOSE]})`) 30725 30726 // ## Pre-release Version Identifier 30727 // A numeric identifier, or a non-numeric identifier. 30728 30729 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] 30730 }|${src[t.NONNUMERICIDENTIFIER]})`) 30731 30732 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] 30733 }|${src[t.NONNUMERICIDENTIFIER]})`) 30734 30735 // ## Pre-release Version 30736 // Hyphen, followed by one or more dot-separated pre-release version 30737 // identifiers. 30738 30739 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] 30740 }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) 30741 30742 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] 30743 }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) 30744 30745 // ## Build Metadata Identifier 30746 // Any combination of digits, letters, or hyphens. 30747 30748 createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) 30749 30750 // ## Build Metadata 30751 // Plus sign, followed by one or more period-separated build metadata 30752 // identifiers. 30753 30754 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] 30755 }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) 30756 30757 // ## Full Version String 30758 // A main version, followed optionally by a pre-release version and 30759 // build metadata. 30760 30761 // Note that the only major, minor, patch, and pre-release sections of 30762 // the version string are capturing groups. The build metadata is not a 30763 // capturing group, because it should not ever be used in version 30764 // comparison. 30765 30766 createToken('FULLPLAIN', `v?${src[t.MAINVERSION] 30767 }${src[t.PRERELEASE]}?${ 30768 src[t.BUILD]}?`) 30769 30770 createToken('FULL', `^${src[t.FULLPLAIN]}$`) 30771 30772 // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. 30773 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty 30774 // common in the npm registry. 30775 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] 30776 }${src[t.PRERELEASELOOSE]}?${ 30777 src[t.BUILD]}?`) 30778 30779 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) 30780 30781 createToken('GTLT', '((?:<|>)?=?)') 30782 30783 // Something like "2.*" or "1.2.x". 30784 // Note that "x.x" is a valid xRange identifer, meaning "any version" 30785 // Only the first item is strictly required. 30786 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) 30787 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) 30788 30789 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + 30790 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + 30791 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + 30792 `(?:${src[t.PRERELEASE]})?${ 30793 src[t.BUILD]}?` + 30794 `)?)?`) 30795 30796 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + 30797 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + 30798 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + 30799 `(?:${src[t.PRERELEASELOOSE]})?${ 30800 src[t.BUILD]}?` + 30801 `)?)?`) 30802 30803 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) 30804 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) 30805 30806 // Coercion. 30807 // Extract anything that could conceivably be a part of a valid semver 30808 createToken('COERCE', `${'(^|[^\\d])' + 30809 '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + 30810 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + 30811 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + 30812 `(?:$|[^\\d])`) 30813 createToken('COERCERTL', src[t.COERCE], true) 30814 30815 // Tilde ranges. 30816 // Meaning is "reasonably at or greater than" 30817 createToken('LONETILDE', '(?:~>?)') 30818 30819 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) 30820 exports.tildeTrimReplace = '$1~' 30821 30822 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) 30823 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) 30824 30825 // Caret ranges. 30826 // Meaning is "at least and backwards compatible with" 30827 createToken('LONECARET', '(?:\\^)') 30828 30829 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) 30830 exports.caretTrimReplace = '$1^' 30831 30832 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) 30833 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) 30834 30835 // A simple gt/lt/eq thing, or just "" to indicate "any version" 30836 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) 30837 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) 30838 30839 // An expression to strip any whitespace between the gtlt and the thing 30840 // it modifies, so that `> 1.2.3` ==> `>1.2.3` 30841 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] 30842 }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) 30843 exports.comparatorTrimReplace = '$1$2$3' 30844 30845 // Something like `1.2.3 - 1.2.4` 30846 // Note that these all use the loose form, because they'll be 30847 // checked against either the strict or loose comparator form 30848 // later. 30849 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + 30850 `\\s+-\\s+` + 30851 `(${src[t.XRANGEPLAIN]})` + 30852 `\\s*$`) 30853 30854 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + 30855 `\\s+-\\s+` + 30856 `(${src[t.XRANGEPLAINLOOSE]})` + 30857 `\\s*$`) 30858 30859 // Star ranges basically just allow anything at all. 30860 createToken('STAR', '(<|>)?=?\\s*\\*') 30861 // >=0.0.0 is like a star 30862 createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') 30863 createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') 30864 30865 30866 /***/ }), 30867 30868 /***/ 9380: 30869 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30870 30871 // Determine if version is greater than all the versions possible in the range. 30872 const outside = __nccwpck_require__(420) 30873 const gtr = (version, range, options) => outside(version, range, '>', options) 30874 module.exports = gtr 30875 30876 30877 /***/ }), 30878 30879 /***/ 7008: 30880 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30881 30882 const Range = __nccwpck_require__(9828) 30883 const intersects = (r1, r2, options) => { 30884 r1 = new Range(r1, options) 30885 r2 = new Range(r2, options) 30886 return r1.intersects(r2, options) 30887 } 30888 module.exports = intersects 30889 30890 30891 /***/ }), 30892 30893 /***/ 3323: 30894 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30895 30896 const outside = __nccwpck_require__(420) 30897 // Determine if version is less than all the versions possible in the range 30898 const ltr = (version, range, options) => outside(version, range, '<', options) 30899 module.exports = ltr 30900 30901 30902 /***/ }), 30903 30904 /***/ 579: 30905 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30906 30907 const SemVer = __nccwpck_require__(8088) 30908 const Range = __nccwpck_require__(9828) 30909 30910 const maxSatisfying = (versions, range, options) => { 30911 let max = null 30912 let maxSV = null 30913 let rangeObj = null 30914 try { 30915 rangeObj = new Range(range, options) 30916 } catch (er) { 30917 return null 30918 } 30919 versions.forEach((v) => { 30920 if (rangeObj.test(v)) { 30921 // satisfies(v, range, options) 30922 if (!max || maxSV.compare(v) === -1) { 30923 // compare(max, v, true) 30924 max = v 30925 maxSV = new SemVer(max, options) 30926 } 30927 } 30928 }) 30929 return max 30930 } 30931 module.exports = maxSatisfying 30932 30933 30934 /***/ }), 30935 30936 /***/ 832: 30937 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30938 30939 const SemVer = __nccwpck_require__(8088) 30940 const Range = __nccwpck_require__(9828) 30941 const minSatisfying = (versions, range, options) => { 30942 let min = null 30943 let minSV = null 30944 let rangeObj = null 30945 try { 30946 rangeObj = new Range(range, options) 30947 } catch (er) { 30948 return null 30949 } 30950 versions.forEach((v) => { 30951 if (rangeObj.test(v)) { 30952 // satisfies(v, range, options) 30953 if (!min || minSV.compare(v) === 1) { 30954 // compare(min, v, true) 30955 min = v 30956 minSV = new SemVer(min, options) 30957 } 30958 } 30959 }) 30960 return min 30961 } 30962 module.exports = minSatisfying 30963 30964 30965 /***/ }), 30966 30967 /***/ 4179: 30968 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 30969 30970 const SemVer = __nccwpck_require__(8088) 30971 const Range = __nccwpck_require__(9828) 30972 const gt = __nccwpck_require__(4123) 30973 30974 const minVersion = (range, loose) => { 30975 range = new Range(range, loose) 30976 30977 let minver = new SemVer('0.0.0') 30978 if (range.test(minver)) { 30979 return minver 30980 } 30981 30982 minver = new SemVer('0.0.0-0') 30983 if (range.test(minver)) { 30984 return minver 30985 } 30986 30987 minver = null 30988 for (let i = 0; i < range.set.length; ++i) { 30989 const comparators = range.set[i] 30990 30991 let setMin = null 30992 comparators.forEach((comparator) => { 30993 // Clone to avoid manipulating the comparator's semver object. 30994 const compver = new SemVer(comparator.semver.version) 30995 switch (comparator.operator) { 30996 case '>': 30997 if (compver.prerelease.length === 0) { 30998 compver.patch++ 30999 } else { 31000 compver.prerelease.push(0) 31001 } 31002 compver.raw = compver.format() 31003 /* fallthrough */ 31004 case '': 31005 case '>=': 31006 if (!setMin || gt(compver, setMin)) { 31007 setMin = compver 31008 } 31009 break 31010 case '<': 31011 case '<=': 31012 /* Ignore maximum versions */ 31013 break 31014 /* istanbul ignore next */ 31015 default: 31016 throw new Error(`Unexpected operation: ${comparator.operator}`) 31017 } 31018 }) 31019 if (setMin && (!minver || gt(minver, setMin))) { 31020 minver = setMin 31021 } 31022 } 31023 31024 if (minver && range.test(minver)) { 31025 return minver 31026 } 31027 31028 return null 31029 } 31030 module.exports = minVersion 31031 31032 31033 /***/ }), 31034 31035 /***/ 420: 31036 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 31037 31038 const SemVer = __nccwpck_require__(8088) 31039 const Comparator = __nccwpck_require__(1532) 31040 const { ANY } = Comparator 31041 const Range = __nccwpck_require__(9828) 31042 const satisfies = __nccwpck_require__(6055) 31043 const gt = __nccwpck_require__(4123) 31044 const lt = __nccwpck_require__(194) 31045 const lte = __nccwpck_require__(7520) 31046 const gte = __nccwpck_require__(5522) 31047 31048 const outside = (version, range, hilo, options) => { 31049 version = new SemVer(version, options) 31050 range = new Range(range, options) 31051 31052 let gtfn, ltefn, ltfn, comp, ecomp 31053 switch (hilo) { 31054 case '>': 31055 gtfn = gt 31056 ltefn = lte 31057 ltfn = lt 31058 comp = '>' 31059 ecomp = '>=' 31060 break 31061 case '<': 31062 gtfn = lt 31063 ltefn = gte 31064 ltfn = gt 31065 comp = '<' 31066 ecomp = '<=' 31067 break 31068 default: 31069 throw new TypeError('Must provide a hilo val of "<" or ">"') 31070 } 31071 31072 // If it satisfies the range it is not outside 31073 if (satisfies(version, range, options)) { 31074 return false 31075 } 31076 31077 // From now on, variable terms are as if we're in "gtr" mode. 31078 // but note that everything is flipped for the "ltr" function. 31079 31080 for (let i = 0; i < range.set.length; ++i) { 31081 const comparators = range.set[i] 31082 31083 let high = null 31084 let low = null 31085 31086 comparators.forEach((comparator) => { 31087 if (comparator.semver === ANY) { 31088 comparator = new Comparator('>=0.0.0') 31089 } 31090 high = high || comparator 31091 low = low || comparator 31092 if (gtfn(comparator.semver, high.semver, options)) { 31093 high = comparator 31094 } else if (ltfn(comparator.semver, low.semver, options)) { 31095 low = comparator 31096 } 31097 }) 31098 31099 // If the edge version comparator has a operator then our version 31100 // isn't outside it 31101 if (high.operator === comp || high.operator === ecomp) { 31102 return false 31103 } 31104 31105 // If the lowest version comparator has an operator and our version 31106 // is less than it then it isn't higher than the range 31107 if ((!low.operator || low.operator === comp) && 31108 ltefn(version, low.semver)) { 31109 return false 31110 } else if (low.operator === ecomp && ltfn(version, low.semver)) { 31111 return false 31112 } 31113 } 31114 return true 31115 } 31116 31117 module.exports = outside 31118 31119 31120 /***/ }), 31121 31122 /***/ 6561: 31123 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 31124 31125 // given a set of versions and a range, create a "simplified" range 31126 // that includes the same versions that the original range does 31127 // If the original range is shorter than the simplified one, return that. 31128 const satisfies = __nccwpck_require__(6055) 31129 const compare = __nccwpck_require__(4309) 31130 module.exports = (versions, range, options) => { 31131 const set = [] 31132 let first = null 31133 let prev = null 31134 const v = versions.sort((a, b) => compare(a, b, options)) 31135 for (const version of v) { 31136 const included = satisfies(version, range, options) 31137 if (included) { 31138 prev = version 31139 if (!first) { 31140 first = version 31141 } 31142 } else { 31143 if (prev) { 31144 set.push([first, prev]) 31145 } 31146 prev = null 31147 first = null 31148 } 31149 } 31150 if (first) { 31151 set.push([first, null]) 31152 } 31153 31154 const ranges = [] 31155 for (const [min, max] of set) { 31156 if (min === max) { 31157 ranges.push(min) 31158 } else if (!max && min === v[0]) { 31159 ranges.push('*') 31160 } else if (!max) { 31161 ranges.push(`>=${min}`) 31162 } else if (min === v[0]) { 31163 ranges.push(`<=${max}`) 31164 } else { 31165 ranges.push(`${min} - ${max}`) 31166 } 31167 } 31168 const simplified = ranges.join(' || ') 31169 const original = typeof range.raw === 'string' ? range.raw : String(range) 31170 return simplified.length < original.length ? simplified : range 31171 } 31172 31173 31174 /***/ }), 31175 31176 /***/ 7863: 31177 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 31178 31179 const Range = __nccwpck_require__(9828) 31180 const Comparator = __nccwpck_require__(1532) 31181 const { ANY } = Comparator 31182 const satisfies = __nccwpck_require__(6055) 31183 const compare = __nccwpck_require__(4309) 31184 31185 // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: 31186 // - Every simple range `r1, r2, ...` is a null set, OR 31187 // - Every simple range `r1, r2, ...` which is not a null set is a subset of 31188 // some `R1, R2, ...` 31189 // 31190 // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: 31191 // - If c is only the ANY comparator 31192 // - If C is only the ANY comparator, return true 31193 // - Else if in prerelease mode, return false 31194 // - else replace c with `[>=0.0.0]` 31195 // - If C is only the ANY comparator 31196 // - if in prerelease mode, return true 31197 // - else replace C with `[>=0.0.0]` 31198 // - Let EQ be the set of = comparators in c 31199 // - If EQ is more than one, return true (null set) 31200 // - Let GT be the highest > or >= comparator in c 31201 // - Let LT be the lowest < or <= comparator in c 31202 // - If GT and LT, and GT.semver > LT.semver, return true (null set) 31203 // - If any C is a = range, and GT or LT are set, return false 31204 // - If EQ 31205 // - If GT, and EQ does not satisfy GT, return true (null set) 31206 // - If LT, and EQ does not satisfy LT, return true (null set) 31207 // - If EQ satisfies every C, return true 31208 // - Else return false 31209 // - If GT 31210 // - If GT.semver is lower than any > or >= comp in C, return false 31211 // - If GT is >=, and GT.semver does not satisfy every C, return false 31212 // - If GT.semver has a prerelease, and not in prerelease mode 31213 // - If no C has a prerelease and the GT.semver tuple, return false 31214 // - If LT 31215 // - If LT.semver is greater than any < or <= comp in C, return false 31216 // - If LT is <=, and LT.semver does not satisfy every C, return false 31217 // - If GT.semver has a prerelease, and not in prerelease mode 31218 // - If no C has a prerelease and the LT.semver tuple, return false 31219 // - Else return true 31220 31221 const subset = (sub, dom, options = {}) => { 31222 if (sub === dom) { 31223 return true 31224 } 31225 31226 sub = new Range(sub, options) 31227 dom = new Range(dom, options) 31228 let sawNonNull = false 31229 31230 OUTER: for (const simpleSub of sub.set) { 31231 for (const simpleDom of dom.set) { 31232 const isSub = simpleSubset(simpleSub, simpleDom, options) 31233 sawNonNull = sawNonNull || isSub !== null 31234 if (isSub) { 31235 continue OUTER 31236 } 31237 } 31238 // the null set is a subset of everything, but null simple ranges in 31239 // a complex range should be ignored. so if we saw a non-null range, 31240 // then we know this isn't a subset, but if EVERY simple range was null, 31241 // then it is a subset. 31242 if (sawNonNull) { 31243 return false 31244 } 31245 } 31246 return true 31247 } 31248 31249 const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] 31250 const minimumVersion = [new Comparator('>=0.0.0')] 31251 31252 const simpleSubset = (sub, dom, options) => { 31253 if (sub === dom) { 31254 return true 31255 } 31256 31257 if (sub.length === 1 && sub[0].semver === ANY) { 31258 if (dom.length === 1 && dom[0].semver === ANY) { 31259 return true 31260 } else if (options.includePrerelease) { 31261 sub = minimumVersionWithPreRelease 31262 } else { 31263 sub = minimumVersion 31264 } 31265 } 31266 31267 if (dom.length === 1 && dom[0].semver === ANY) { 31268 if (options.includePrerelease) { 31269 return true 31270 } else { 31271 dom = minimumVersion 31272 } 31273 } 31274 31275 const eqSet = new Set() 31276 let gt, lt 31277 for (const c of sub) { 31278 if (c.operator === '>' || c.operator === '>=') { 31279 gt = higherGT(gt, c, options) 31280 } else if (c.operator === '<' || c.operator === '<=') { 31281 lt = lowerLT(lt, c, options) 31282 } else { 31283 eqSet.add(c.semver) 31284 } 31285 } 31286 31287 if (eqSet.size > 1) { 31288 return null 31289 } 31290 31291 let gtltComp 31292 if (gt && lt) { 31293 gtltComp = compare(gt.semver, lt.semver, options) 31294 if (gtltComp > 0) { 31295 return null 31296 } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { 31297 return null 31298 } 31299 } 31300 31301 // will iterate one or zero times 31302 for (const eq of eqSet) { 31303 if (gt && !satisfies(eq, String(gt), options)) { 31304 return null 31305 } 31306 31307 if (lt && !satisfies(eq, String(lt), options)) { 31308 return null 31309 } 31310 31311 for (const c of dom) { 31312 if (!satisfies(eq, String(c), options)) { 31313 return false 31314 } 31315 } 31316 31317 return true 31318 } 31319 31320 let higher, lower 31321 let hasDomLT, hasDomGT 31322 // if the subset has a prerelease, we need a comparator in the superset 31323 // with the same tuple and a prerelease, or it's not a subset 31324 let needDomLTPre = lt && 31325 !options.includePrerelease && 31326 lt.semver.prerelease.length ? lt.semver : false 31327 let needDomGTPre = gt && 31328 !options.includePrerelease && 31329 gt.semver.prerelease.length ? gt.semver : false 31330 // exception: <1.2.3-0 is the same as <1.2.3 31331 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && 31332 lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { 31333 needDomLTPre = false 31334 } 31335 31336 for (const c of dom) { 31337 hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' 31338 hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' 31339 if (gt) { 31340 if (needDomGTPre) { 31341 if (c.semver.prerelease && c.semver.prerelease.length && 31342 c.semver.major === needDomGTPre.major && 31343 c.semver.minor === needDomGTPre.minor && 31344 c.semver.patch === needDomGTPre.patch) { 31345 needDomGTPre = false 31346 } 31347 } 31348 if (c.operator === '>' || c.operator === '>=') { 31349 higher = higherGT(gt, c, options) 31350 if (higher === c && higher !== gt) { 31351 return false 31352 } 31353 } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { 31354 return false 31355 } 31356 } 31357 if (lt) { 31358 if (needDomLTPre) { 31359 if (c.semver.prerelease && c.semver.prerelease.length && 31360 c.semver.major === needDomLTPre.major && 31361 c.semver.minor === needDomLTPre.minor && 31362 c.semver.patch === needDomLTPre.patch) { 31363 needDomLTPre = false 31364 } 31365 } 31366 if (c.operator === '<' || c.operator === '<=') { 31367 lower = lowerLT(lt, c, options) 31368 if (lower === c && lower !== lt) { 31369 return false 31370 } 31371 } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { 31372 return false 31373 } 31374 } 31375 if (!c.operator && (lt || gt) && gtltComp !== 0) { 31376 return false 31377 } 31378 } 31379 31380 // if there was a < or >, and nothing in the dom, then must be false 31381 // UNLESS it was limited by another range in the other direction. 31382 // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 31383 if (gt && hasDomLT && !lt && gtltComp !== 0) { 31384 return false 31385 } 31386 31387 if (lt && hasDomGT && !gt && gtltComp !== 0) { 31388 return false 31389 } 31390 31391 // we needed a prerelease range in a specific tuple, but didn't get one 31392 // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, 31393 // because it includes prereleases in the 1.2.3 tuple 31394 if (needDomGTPre || needDomLTPre) { 31395 return false 31396 } 31397 31398 return true 31399 } 31400 31401 // >=1.2.3 is lower than >1.2.3 31402 const higherGT = (a, b, options) => { 31403 if (!a) { 31404 return b 31405 } 31406 const comp = compare(a.semver, b.semver, options) 31407 return comp > 0 ? a 31408 : comp < 0 ? b 31409 : b.operator === '>' && a.operator === '>=' ? b 31410 : a 31411 } 31412 31413 // <=1.2.3 is higher than <1.2.3 31414 const lowerLT = (a, b, options) => { 31415 if (!a) { 31416 return b 31417 } 31418 const comp = compare(a.semver, b.semver, options) 31419 return comp < 0 ? a 31420 : comp > 0 ? b 31421 : b.operator === '<' && a.operator === '<=' ? b 31422 : a 31423 } 31424 31425 module.exports = subset 31426 31427 31428 /***/ }), 31429 31430 /***/ 2706: 31431 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 31432 31433 const Range = __nccwpck_require__(9828) 31434 31435 // Mostly just for testing and legacy API reasons 31436 const toComparators = (range, options) => 31437 new Range(range, options).set 31438 .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) 31439 31440 module.exports = toComparators 31441 31442 31443 /***/ }), 31444 31445 /***/ 2098: 31446 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 31447 31448 const Range = __nccwpck_require__(9828) 31449 const validRange = (range, options) => { 31450 try { 31451 // Return '*' instead of '' so that truthiness works. 31452 // This will throw if it's invalid anyway 31453 return new Range(range, options).range || '*' 31454 } catch (er) { 31455 return null 31456 } 31457 } 31458 module.exports = validRange 31459 31460 31461 /***/ }), 31462 31463 /***/ 3430: 31464 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 31465 31466 "use strict"; 31467 31468 Object.defineProperty(exports, "__esModule", ({ value: true })); 31469 exports.createVerificationPolicy = exports.createKeyFinder = exports.createBundleBuilder = exports.DEFAULT_TIMEOUT = exports.DEFAULT_RETRY = void 0; 31470 /* 31471 Copyright 2023 The Sigstore Authors. 31472 31473 Licensed under the Apache License, Version 2.0 (the "License"); 31474 you may not use this file except in compliance with the License. 31475 You may obtain a copy of the License at 31476 31477 http://www.apache.org/licenses/LICENSE-2.0 31478 31479 Unless required by applicable law or agreed to in writing, software 31480 distributed under the License is distributed on an "AS IS" BASIS, 31481 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31482 See the License for the specific language governing permissions and 31483 limitations under the License. 31484 */ 31485 const core_1 = __nccwpck_require__(3352); 31486 const sign_1 = __nccwpck_require__(2071); 31487 const verify_1 = __nccwpck_require__(666); 31488 exports.DEFAULT_RETRY = { retries: 2 }; 31489 exports.DEFAULT_TIMEOUT = 5000; 31490 function createBundleBuilder(bundleType, options) { 31491 const bundlerOptions = { 31492 signer: initSigner(options), 31493 witnesses: initWitnesses(options), 31494 }; 31495 switch (bundleType) { 31496 case 'messageSignature': 31497 return new sign_1.MessageSignatureBundleBuilder(bundlerOptions); 31498 case 'dsseEnvelope': 31499 return new sign_1.DSSEBundleBuilder(bundlerOptions); 31500 } 31501 } 31502 exports.createBundleBuilder = createBundleBuilder; 31503 // Translates the public KeySelector type into the KeyFinderFunc type needed by 31504 // the verifier. 31505 function createKeyFinder(keySelector) { 31506 return (hint) => { 31507 const key = keySelector(hint); 31508 if (!key) { 31509 throw new verify_1.VerificationError({ 31510 code: 'PUBLIC_KEY_ERROR', 31511 message: `key not found: ${hint}`, 31512 }); 31513 } 31514 return { 31515 publicKey: core_1.crypto.createPublicKey(key), 31516 validFor: () => true, 31517 }; 31518 }; 31519 } 31520 exports.createKeyFinder = createKeyFinder; 31521 function createVerificationPolicy(options) { 31522 const policy = {}; 31523 const san = options.certificateIdentityEmail || options.certificateIdentityURI; 31524 if (san) { 31525 policy.subjectAlternativeName = san; 31526 } 31527 if (options.certificateIssuer) { 31528 policy.extensions = { issuer: options.certificateIssuer }; 31529 } 31530 return policy; 31531 } 31532 exports.createVerificationPolicy = createVerificationPolicy; 31533 // Instantiate the FulcioSigner based on the supplied options. 31534 function initSigner(options) { 31535 return new sign_1.FulcioSigner({ 31536 fulcioBaseURL: options.fulcioURL, 31537 identityProvider: options.identityProvider || initIdentityProvider(options), 31538 retry: options.retry ?? exports.DEFAULT_RETRY, 31539 timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, 31540 }); 31541 } 31542 // Instantiate an identity provider based on the supplied options. If an 31543 // explicit identity token is provided, use that. Otherwise, use the CI 31544 // context provider. 31545 function initIdentityProvider(options) { 31546 const token = options.identityToken; 31547 if (token) { 31548 /* istanbul ignore next */ 31549 return { getToken: () => Promise.resolve(token) }; 31550 } 31551 else { 31552 return new sign_1.CIContextProvider('sigstore'); 31553 } 31554 } 31555 // Instantiate a collection of witnesses based on the supplied options. 31556 function initWitnesses(options) { 31557 const witnesses = []; 31558 if (isRekorEnabled(options)) { 31559 witnesses.push(new sign_1.RekorWitness({ 31560 rekorBaseURL: options.rekorURL, 31561 fetchOnConflict: false, 31562 retry: options.retry ?? exports.DEFAULT_RETRY, 31563 timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, 31564 })); 31565 } 31566 if (isTSAEnabled(options)) { 31567 witnesses.push(new sign_1.TSAWitness({ 31568 tsaBaseURL: options.tsaServerURL, 31569 retry: options.retry ?? exports.DEFAULT_RETRY, 31570 timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, 31571 })); 31572 } 31573 return witnesses; 31574 } 31575 // Type assertion to ensure that Rekor is enabled 31576 function isRekorEnabled(options) { 31577 return options.tlogUpload !== false; 31578 } 31579 // Type assertion to ensure that TSA is enabled 31580 function isTSAEnabled(options) { 31581 return options.tsaServerURL !== undefined; 31582 } 31583 31584 31585 /***/ }), 31586 31587 /***/ 9149: 31588 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 31589 31590 "use strict"; 31591 31592 Object.defineProperty(exports, "__esModule", ({ value: true })); 31593 exports.verify = exports.sign = exports.createVerifier = exports.attest = exports.VerificationError = exports.PolicyError = exports.TUFError = exports.InternalError = exports.DEFAULT_REKOR_URL = exports.DEFAULT_FULCIO_URL = exports.ValidationError = void 0; 31594 /* 31595 Copyright 2022 The Sigstore Authors. 31596 31597 Licensed under the Apache License, Version 2.0 (the "License"); 31598 you may not use this file except in compliance with the License. 31599 You may obtain a copy of the License at 31600 31601 http://www.apache.org/licenses/LICENSE-2.0 31602 31603 Unless required by applicable law or agreed to in writing, software 31604 distributed under the License is distributed on an "AS IS" BASIS, 31605 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31606 See the License for the specific language governing permissions and 31607 limitations under the License. 31608 */ 31609 var bundle_1 = __nccwpck_require__(9715); 31610 Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return bundle_1.ValidationError; } })); 31611 var sign_1 = __nccwpck_require__(2071); 31612 Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return sign_1.DEFAULT_FULCIO_URL; } })); 31613 Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return sign_1.DEFAULT_REKOR_URL; } })); 31614 Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return sign_1.InternalError; } })); 31615 var tuf_1 = __nccwpck_require__(8567); 31616 Object.defineProperty(exports, "TUFError", ({ enumerable: true, get: function () { return tuf_1.TUFError; } })); 31617 var verify_1 = __nccwpck_require__(666); 31618 Object.defineProperty(exports, "PolicyError", ({ enumerable: true, get: function () { return verify_1.PolicyError; } })); 31619 Object.defineProperty(exports, "VerificationError", ({ enumerable: true, get: function () { return verify_1.VerificationError; } })); 31620 var sigstore_1 = __nccwpck_require__(1111); 31621 Object.defineProperty(exports, "attest", ({ enumerable: true, get: function () { return sigstore_1.attest; } })); 31622 Object.defineProperty(exports, "createVerifier", ({ enumerable: true, get: function () { return sigstore_1.createVerifier; } })); 31623 Object.defineProperty(exports, "sign", ({ enumerable: true, get: function () { return sigstore_1.sign; } })); 31624 Object.defineProperty(exports, "verify", ({ enumerable: true, get: function () { return sigstore_1.verify; } })); 31625 31626 31627 /***/ }), 31628 31629 /***/ 1111: 31630 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 31631 31632 "use strict"; 31633 31634 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 31635 if (k2 === undefined) k2 = k; 31636 var desc = Object.getOwnPropertyDescriptor(m, k); 31637 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 31638 desc = { enumerable: true, get: function() { return m[k]; } }; 31639 } 31640 Object.defineProperty(o, k2, desc); 31641 }) : (function(o, m, k, k2) { 31642 if (k2 === undefined) k2 = k; 31643 o[k2] = m[k]; 31644 })); 31645 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 31646 Object.defineProperty(o, "default", { enumerable: true, value: v }); 31647 }) : function(o, v) { 31648 o["default"] = v; 31649 }); 31650 var __importStar = (this && this.__importStar) || function (mod) { 31651 if (mod && mod.__esModule) return mod; 31652 var result = {}; 31653 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 31654 __setModuleDefault(result, mod); 31655 return result; 31656 }; 31657 Object.defineProperty(exports, "__esModule", ({ value: true })); 31658 exports.createVerifier = exports.verify = exports.attest = exports.sign = void 0; 31659 /* 31660 Copyright 2023 The Sigstore Authors. 31661 31662 Licensed under the Apache License, Version 2.0 (the "License"); 31663 you may not use this file except in compliance with the License. 31664 You may obtain a copy of the License at 31665 31666 http://www.apache.org/licenses/LICENSE-2.0 31667 31668 Unless required by applicable law or agreed to in writing, software 31669 distributed under the License is distributed on an "AS IS" BASIS, 31670 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31671 See the License for the specific language governing permissions and 31672 limitations under the License. 31673 */ 31674 const bundle_1 = __nccwpck_require__(9715); 31675 const tuf = __importStar(__nccwpck_require__(8567)); 31676 const verify_1 = __nccwpck_require__(666); 31677 const config = __importStar(__nccwpck_require__(3430)); 31678 async function sign(payload, 31679 /* istanbul ignore next */ 31680 options = {}) { 31681 const bundler = config.createBundleBuilder('messageSignature', options); 31682 const bundle = await bundler.create({ data: payload }); 31683 return (0, bundle_1.bundleToJSON)(bundle); 31684 } 31685 exports.sign = sign; 31686 async function attest(payload, payloadType, 31687 /* istanbul ignore next */ 31688 options = {}) { 31689 const bundler = config.createBundleBuilder('dsseEnvelope', options); 31690 const bundle = await bundler.create({ data: payload, type: payloadType }); 31691 return (0, bundle_1.bundleToJSON)(bundle); 31692 } 31693 exports.attest = attest; 31694 async function verify(bundle, dataOrOptions, options) { 31695 let data; 31696 if (Buffer.isBuffer(dataOrOptions)) { 31697 data = dataOrOptions; 31698 } 31699 else { 31700 options = dataOrOptions; 31701 } 31702 return createVerifier(options).then((verifier) => verifier.verify(bundle, data)); 31703 } 31704 exports.verify = verify; 31705 async function createVerifier( 31706 /* istanbul ignore next */ 31707 options = {}) { 31708 const trustedRoot = await tuf.getTrustedRoot({ 31709 mirrorURL: options.tufMirrorURL, 31710 rootPath: options.tufRootPath, 31711 cachePath: options.tufCachePath, 31712 forceCache: options.tufForceCache, 31713 retry: options.retry ?? config.DEFAULT_RETRY, 31714 timeout: options.timeout ?? config.DEFAULT_TIMEOUT, 31715 }); 31716 const keyFinder = options.keySelector 31717 ? config.createKeyFinder(options.keySelector) 31718 : undefined; 31719 const trustMaterial = (0, verify_1.toTrustMaterial)(trustedRoot, keyFinder); 31720 const verifierOptions = { 31721 ctlogThreshold: options.ctLogThreshold, 31722 tlogThreshold: options.tlogThreshold, 31723 }; 31724 const verifier = new verify_1.Verifier(trustMaterial, verifierOptions); 31725 const policy = config.createVerificationPolicy(options); 31726 return { 31727 verify: (bundle, payload) => { 31728 const deserializedBundle = (0, bundle_1.bundleFromJSON)(bundle); 31729 const signedEntity = (0, verify_1.toSignedEntity)(deserializedBundle, payload); 31730 verifier.verify(signedEntity, policy); 31731 return; 31732 }, 31733 }; 31734 } 31735 exports.createVerifier = createVerifier; 31736 31737 31738 /***/ }), 31739 31740 /***/ 1062: 31741 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 31742 31743 "use strict"; 31744 31745 Object.defineProperty(exports, "__esModule", ({ value: true })); 31746 const utils_1 = __nccwpck_require__(8132); 31747 // The default Buffer size if one is not provided. 31748 const DEFAULT_SMARTBUFFER_SIZE = 4096; 31749 // The default string encoding to use for reading/writing strings. 31750 const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; 31751 class SmartBuffer { 31752 /** 31753 * Creates a new SmartBuffer instance. 31754 * 31755 * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. 31756 */ 31757 constructor(options) { 31758 this.length = 0; 31759 this._encoding = DEFAULT_SMARTBUFFER_ENCODING; 31760 this._writeOffset = 0; 31761 this._readOffset = 0; 31762 if (SmartBuffer.isSmartBufferOptions(options)) { 31763 // Checks for encoding 31764 if (options.encoding) { 31765 utils_1.checkEncoding(options.encoding); 31766 this._encoding = options.encoding; 31767 } 31768 // Checks for initial size length 31769 if (options.size) { 31770 if (utils_1.isFiniteInteger(options.size) && options.size > 0) { 31771 this._buff = Buffer.allocUnsafe(options.size); 31772 } 31773 else { 31774 throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); 31775 } 31776 // Check for initial Buffer 31777 } 31778 else if (options.buff) { 31779 if (Buffer.isBuffer(options.buff)) { 31780 this._buff = options.buff; 31781 this.length = options.buff.length; 31782 } 31783 else { 31784 throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); 31785 } 31786 } 31787 else { 31788 this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); 31789 } 31790 } 31791 else { 31792 // If something was passed but it's not a SmartBufferOptions object 31793 if (typeof options !== 'undefined') { 31794 throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); 31795 } 31796 // Otherwise default to sane options 31797 this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); 31798 } 31799 } 31800 /** 31801 * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. 31802 * 31803 * @param size { Number } The size of the internal Buffer. 31804 * @param encoding { String } The BufferEncoding to use for strings. 31805 * 31806 * @return { SmartBuffer } 31807 */ 31808 static fromSize(size, encoding) { 31809 return new this({ 31810 size: size, 31811 encoding: encoding 31812 }); 31813 } 31814 /** 31815 * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. 31816 * 31817 * @param buffer { Buffer } The Buffer to use as the internal Buffer value. 31818 * @param encoding { String } The BufferEncoding to use for strings. 31819 * 31820 * @return { SmartBuffer } 31821 */ 31822 static fromBuffer(buff, encoding) { 31823 return new this({ 31824 buff: buff, 31825 encoding: encoding 31826 }); 31827 } 31828 /** 31829 * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. 31830 * 31831 * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. 31832 */ 31833 static fromOptions(options) { 31834 return new this(options); 31835 } 31836 /** 31837 * Type checking function that determines if an object is a SmartBufferOptions object. 31838 */ 31839 static isSmartBufferOptions(options) { 31840 const castOptions = options; 31841 return (castOptions && 31842 (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); 31843 } 31844 // Signed integers 31845 /** 31846 * Reads an Int8 value from the current read position or an optionally provided offset. 31847 * 31848 * @param offset { Number } The offset to read data from (optional) 31849 * @return { Number } 31850 */ 31851 readInt8(offset) { 31852 return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); 31853 } 31854 /** 31855 * Reads an Int16BE value from the current read position or an optionally provided offset. 31856 * 31857 * @param offset { Number } The offset to read data from (optional) 31858 * @return { Number } 31859 */ 31860 readInt16BE(offset) { 31861 return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); 31862 } 31863 /** 31864 * Reads an Int16LE value from the current read position or an optionally provided offset. 31865 * 31866 * @param offset { Number } The offset to read data from (optional) 31867 * @return { Number } 31868 */ 31869 readInt16LE(offset) { 31870 return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); 31871 } 31872 /** 31873 * Reads an Int32BE value from the current read position or an optionally provided offset. 31874 * 31875 * @param offset { Number } The offset to read data from (optional) 31876 * @return { Number } 31877 */ 31878 readInt32BE(offset) { 31879 return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); 31880 } 31881 /** 31882 * Reads an Int32LE value from the current read position or an optionally provided offset. 31883 * 31884 * @param offset { Number } The offset to read data from (optional) 31885 * @return { Number } 31886 */ 31887 readInt32LE(offset) { 31888 return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); 31889 } 31890 /** 31891 * Reads a BigInt64BE value from the current read position or an optionally provided offset. 31892 * 31893 * @param offset { Number } The offset to read data from (optional) 31894 * @return { BigInt } 31895 */ 31896 readBigInt64BE(offset) { 31897 utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); 31898 return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); 31899 } 31900 /** 31901 * Reads a BigInt64LE value from the current read position or an optionally provided offset. 31902 * 31903 * @param offset { Number } The offset to read data from (optional) 31904 * @return { BigInt } 31905 */ 31906 readBigInt64LE(offset) { 31907 utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); 31908 return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); 31909 } 31910 /** 31911 * Writes an Int8 value to the current write position (or at optional offset). 31912 * 31913 * @param value { Number } The value to write. 31914 * @param offset { Number } The offset to write the value at. 31915 * 31916 * @return this 31917 */ 31918 writeInt8(value, offset) { 31919 this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); 31920 return this; 31921 } 31922 /** 31923 * Inserts an Int8 value at the given offset value. 31924 * 31925 * @param value { Number } The value to insert. 31926 * @param offset { Number } The offset to insert the value at. 31927 * 31928 * @return this 31929 */ 31930 insertInt8(value, offset) { 31931 return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); 31932 } 31933 /** 31934 * Writes an Int16BE value to the current write position (or at optional offset). 31935 * 31936 * @param value { Number } The value to write. 31937 * @param offset { Number } The offset to write the value at. 31938 * 31939 * @return this 31940 */ 31941 writeInt16BE(value, offset) { 31942 return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); 31943 } 31944 /** 31945 * Inserts an Int16BE value at the given offset value. 31946 * 31947 * @param value { Number } The value to insert. 31948 * @param offset { Number } The offset to insert the value at. 31949 * 31950 * @return this 31951 */ 31952 insertInt16BE(value, offset) { 31953 return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); 31954 } 31955 /** 31956 * Writes an Int16LE value to the current write position (or at optional offset). 31957 * 31958 * @param value { Number } The value to write. 31959 * @param offset { Number } The offset to write the value at. 31960 * 31961 * @return this 31962 */ 31963 writeInt16LE(value, offset) { 31964 return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); 31965 } 31966 /** 31967 * Inserts an Int16LE value at the given offset value. 31968 * 31969 * @param value { Number } The value to insert. 31970 * @param offset { Number } The offset to insert the value at. 31971 * 31972 * @return this 31973 */ 31974 insertInt16LE(value, offset) { 31975 return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); 31976 } 31977 /** 31978 * Writes an Int32BE value to the current write position (or at optional offset). 31979 * 31980 * @param value { Number } The value to write. 31981 * @param offset { Number } The offset to write the value at. 31982 * 31983 * @return this 31984 */ 31985 writeInt32BE(value, offset) { 31986 return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); 31987 } 31988 /** 31989 * Inserts an Int32BE value at the given offset value. 31990 * 31991 * @param value { Number } The value to insert. 31992 * @param offset { Number } The offset to insert the value at. 31993 * 31994 * @return this 31995 */ 31996 insertInt32BE(value, offset) { 31997 return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); 31998 } 31999 /** 32000 * Writes an Int32LE value to the current write position (or at optional offset). 32001 * 32002 * @param value { Number } The value to write. 32003 * @param offset { Number } The offset to write the value at. 32004 * 32005 * @return this 32006 */ 32007 writeInt32LE(value, offset) { 32008 return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); 32009 } 32010 /** 32011 * Inserts an Int32LE value at the given offset value. 32012 * 32013 * @param value { Number } The value to insert. 32014 * @param offset { Number } The offset to insert the value at. 32015 * 32016 * @return this 32017 */ 32018 insertInt32LE(value, offset) { 32019 return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); 32020 } 32021 /** 32022 * Writes a BigInt64BE value to the current write position (or at optional offset). 32023 * 32024 * @param value { BigInt } The value to write. 32025 * @param offset { Number } The offset to write the value at. 32026 * 32027 * @return this 32028 */ 32029 writeBigInt64BE(value, offset) { 32030 utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); 32031 return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); 32032 } 32033 /** 32034 * Inserts a BigInt64BE value at the given offset value. 32035 * 32036 * @param value { BigInt } The value to insert. 32037 * @param offset { Number } The offset to insert the value at. 32038 * 32039 * @return this 32040 */ 32041 insertBigInt64BE(value, offset) { 32042 utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); 32043 return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); 32044 } 32045 /** 32046 * Writes a BigInt64LE value to the current write position (or at optional offset). 32047 * 32048 * @param value { BigInt } The value to write. 32049 * @param offset { Number } The offset to write the value at. 32050 * 32051 * @return this 32052 */ 32053 writeBigInt64LE(value, offset) { 32054 utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); 32055 return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); 32056 } 32057 /** 32058 * Inserts a Int64LE value at the given offset value. 32059 * 32060 * @param value { BigInt } The value to insert. 32061 * @param offset { Number } The offset to insert the value at. 32062 * 32063 * @return this 32064 */ 32065 insertBigInt64LE(value, offset) { 32066 utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); 32067 return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); 32068 } 32069 // Unsigned Integers 32070 /** 32071 * Reads an UInt8 value from the current read position or an optionally provided offset. 32072 * 32073 * @param offset { Number } The offset to read data from (optional) 32074 * @return { Number } 32075 */ 32076 readUInt8(offset) { 32077 return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); 32078 } 32079 /** 32080 * Reads an UInt16BE value from the current read position or an optionally provided offset. 32081 * 32082 * @param offset { Number } The offset to read data from (optional) 32083 * @return { Number } 32084 */ 32085 readUInt16BE(offset) { 32086 return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); 32087 } 32088 /** 32089 * Reads an UInt16LE value from the current read position or an optionally provided offset. 32090 * 32091 * @param offset { Number } The offset to read data from (optional) 32092 * @return { Number } 32093 */ 32094 readUInt16LE(offset) { 32095 return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); 32096 } 32097 /** 32098 * Reads an UInt32BE value from the current read position or an optionally provided offset. 32099 * 32100 * @param offset { Number } The offset to read data from (optional) 32101 * @return { Number } 32102 */ 32103 readUInt32BE(offset) { 32104 return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); 32105 } 32106 /** 32107 * Reads an UInt32LE value from the current read position or an optionally provided offset. 32108 * 32109 * @param offset { Number } The offset to read data from (optional) 32110 * @return { Number } 32111 */ 32112 readUInt32LE(offset) { 32113 return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); 32114 } 32115 /** 32116 * Reads a BigUInt64BE value from the current read position or an optionally provided offset. 32117 * 32118 * @param offset { Number } The offset to read data from (optional) 32119 * @return { BigInt } 32120 */ 32121 readBigUInt64BE(offset) { 32122 utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); 32123 return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); 32124 } 32125 /** 32126 * Reads a BigUInt64LE value from the current read position or an optionally provided offset. 32127 * 32128 * @param offset { Number } The offset to read data from (optional) 32129 * @return { BigInt } 32130 */ 32131 readBigUInt64LE(offset) { 32132 utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); 32133 return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); 32134 } 32135 /** 32136 * Writes an UInt8 value to the current write position (or at optional offset). 32137 * 32138 * @param value { Number } The value to write. 32139 * @param offset { Number } The offset to write the value at. 32140 * 32141 * @return this 32142 */ 32143 writeUInt8(value, offset) { 32144 return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); 32145 } 32146 /** 32147 * Inserts an UInt8 value at the given offset value. 32148 * 32149 * @param value { Number } The value to insert. 32150 * @param offset { Number } The offset to insert the value at. 32151 * 32152 * @return this 32153 */ 32154 insertUInt8(value, offset) { 32155 return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); 32156 } 32157 /** 32158 * Writes an UInt16BE value to the current write position (or at optional offset). 32159 * 32160 * @param value { Number } The value to write. 32161 * @param offset { Number } The offset to write the value at. 32162 * 32163 * @return this 32164 */ 32165 writeUInt16BE(value, offset) { 32166 return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); 32167 } 32168 /** 32169 * Inserts an UInt16BE value at the given offset value. 32170 * 32171 * @param value { Number } The value to insert. 32172 * @param offset { Number } The offset to insert the value at. 32173 * 32174 * @return this 32175 */ 32176 insertUInt16BE(value, offset) { 32177 return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); 32178 } 32179 /** 32180 * Writes an UInt16LE value to the current write position (or at optional offset). 32181 * 32182 * @param value { Number } The value to write. 32183 * @param offset { Number } The offset to write the value at. 32184 * 32185 * @return this 32186 */ 32187 writeUInt16LE(value, offset) { 32188 return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); 32189 } 32190 /** 32191 * Inserts an UInt16LE value at the given offset value. 32192 * 32193 * @param value { Number } The value to insert. 32194 * @param offset { Number } The offset to insert the value at. 32195 * 32196 * @return this 32197 */ 32198 insertUInt16LE(value, offset) { 32199 return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); 32200 } 32201 /** 32202 * Writes an UInt32BE value to the current write position (or at optional offset). 32203 * 32204 * @param value { Number } The value to write. 32205 * @param offset { Number } The offset to write the value at. 32206 * 32207 * @return this 32208 */ 32209 writeUInt32BE(value, offset) { 32210 return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); 32211 } 32212 /** 32213 * Inserts an UInt32BE value at the given offset value. 32214 * 32215 * @param value { Number } The value to insert. 32216 * @param offset { Number } The offset to insert the value at. 32217 * 32218 * @return this 32219 */ 32220 insertUInt32BE(value, offset) { 32221 return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); 32222 } 32223 /** 32224 * Writes an UInt32LE value to the current write position (or at optional offset). 32225 * 32226 * @param value { Number } The value to write. 32227 * @param offset { Number } The offset to write the value at. 32228 * 32229 * @return this 32230 */ 32231 writeUInt32LE(value, offset) { 32232 return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); 32233 } 32234 /** 32235 * Inserts an UInt32LE value at the given offset value. 32236 * 32237 * @param value { Number } The value to insert. 32238 * @param offset { Number } The offset to insert the value at. 32239 * 32240 * @return this 32241 */ 32242 insertUInt32LE(value, offset) { 32243 return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); 32244 } 32245 /** 32246 * Writes a BigUInt64BE value to the current write position (or at optional offset). 32247 * 32248 * @param value { Number } The value to write. 32249 * @param offset { Number } The offset to write the value at. 32250 * 32251 * @return this 32252 */ 32253 writeBigUInt64BE(value, offset) { 32254 utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); 32255 return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); 32256 } 32257 /** 32258 * Inserts a BigUInt64BE value at the given offset value. 32259 * 32260 * @param value { Number } The value to insert. 32261 * @param offset { Number } The offset to insert the value at. 32262 * 32263 * @return this 32264 */ 32265 insertBigUInt64BE(value, offset) { 32266 utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); 32267 return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); 32268 } 32269 /** 32270 * Writes a BigUInt64LE value to the current write position (or at optional offset). 32271 * 32272 * @param value { Number } The value to write. 32273 * @param offset { Number } The offset to write the value at. 32274 * 32275 * @return this 32276 */ 32277 writeBigUInt64LE(value, offset) { 32278 utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); 32279 return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); 32280 } 32281 /** 32282 * Inserts a BigUInt64LE value at the given offset value. 32283 * 32284 * @param value { Number } The value to insert. 32285 * @param offset { Number } The offset to insert the value at. 32286 * 32287 * @return this 32288 */ 32289 insertBigUInt64LE(value, offset) { 32290 utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); 32291 return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); 32292 } 32293 // Floating Point 32294 /** 32295 * Reads an FloatBE value from the current read position or an optionally provided offset. 32296 * 32297 * @param offset { Number } The offset to read data from (optional) 32298 * @return { Number } 32299 */ 32300 readFloatBE(offset) { 32301 return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); 32302 } 32303 /** 32304 * Reads an FloatLE value from the current read position or an optionally provided offset. 32305 * 32306 * @param offset { Number } The offset to read data from (optional) 32307 * @return { Number } 32308 */ 32309 readFloatLE(offset) { 32310 return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); 32311 } 32312 /** 32313 * Writes a FloatBE value to the current write position (or at optional offset). 32314 * 32315 * @param value { Number } The value to write. 32316 * @param offset { Number } The offset to write the value at. 32317 * 32318 * @return this 32319 */ 32320 writeFloatBE(value, offset) { 32321 return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); 32322 } 32323 /** 32324 * Inserts a FloatBE value at the given offset value. 32325 * 32326 * @param value { Number } The value to insert. 32327 * @param offset { Number } The offset to insert the value at. 32328 * 32329 * @return this 32330 */ 32331 insertFloatBE(value, offset) { 32332 return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); 32333 } 32334 /** 32335 * Writes a FloatLE value to the current write position (or at optional offset). 32336 * 32337 * @param value { Number } The value to write. 32338 * @param offset { Number } The offset to write the value at. 32339 * 32340 * @return this 32341 */ 32342 writeFloatLE(value, offset) { 32343 return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); 32344 } 32345 /** 32346 * Inserts a FloatLE value at the given offset value. 32347 * 32348 * @param value { Number } The value to insert. 32349 * @param offset { Number } The offset to insert the value at. 32350 * 32351 * @return this 32352 */ 32353 insertFloatLE(value, offset) { 32354 return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); 32355 } 32356 // Double Floating Point 32357 /** 32358 * Reads an DoublEBE value from the current read position or an optionally provided offset. 32359 * 32360 * @param offset { Number } The offset to read data from (optional) 32361 * @return { Number } 32362 */ 32363 readDoubleBE(offset) { 32364 return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); 32365 } 32366 /** 32367 * Reads an DoubleLE value from the current read position or an optionally provided offset. 32368 * 32369 * @param offset { Number } The offset to read data from (optional) 32370 * @return { Number } 32371 */ 32372 readDoubleLE(offset) { 32373 return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); 32374 } 32375 /** 32376 * Writes a DoubleBE value to the current write position (or at optional offset). 32377 * 32378 * @param value { Number } The value to write. 32379 * @param offset { Number } The offset to write the value at. 32380 * 32381 * @return this 32382 */ 32383 writeDoubleBE(value, offset) { 32384 return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); 32385 } 32386 /** 32387 * Inserts a DoubleBE value at the given offset value. 32388 * 32389 * @param value { Number } The value to insert. 32390 * @param offset { Number } The offset to insert the value at. 32391 * 32392 * @return this 32393 */ 32394 insertDoubleBE(value, offset) { 32395 return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); 32396 } 32397 /** 32398 * Writes a DoubleLE value to the current write position (or at optional offset). 32399 * 32400 * @param value { Number } The value to write. 32401 * @param offset { Number } The offset to write the value at. 32402 * 32403 * @return this 32404 */ 32405 writeDoubleLE(value, offset) { 32406 return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); 32407 } 32408 /** 32409 * Inserts a DoubleLE value at the given offset value. 32410 * 32411 * @param value { Number } The value to insert. 32412 * @param offset { Number } The offset to insert the value at. 32413 * 32414 * @return this 32415 */ 32416 insertDoubleLE(value, offset) { 32417 return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); 32418 } 32419 // Strings 32420 /** 32421 * Reads a String from the current read position. 32422 * 32423 * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for 32424 * the string (Defaults to instance level encoding). 32425 * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). 32426 * 32427 * @return { String } 32428 */ 32429 readString(arg1, encoding) { 32430 let lengthVal; 32431 // Length provided 32432 if (typeof arg1 === 'number') { 32433 utils_1.checkLengthValue(arg1); 32434 lengthVal = Math.min(arg1, this.length - this._readOffset); 32435 } 32436 else { 32437 encoding = arg1; 32438 lengthVal = this.length - this._readOffset; 32439 } 32440 // Check encoding 32441 if (typeof encoding !== 'undefined') { 32442 utils_1.checkEncoding(encoding); 32443 } 32444 const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); 32445 this._readOffset += lengthVal; 32446 return value; 32447 } 32448 /** 32449 * Inserts a String 32450 * 32451 * @param value { String } The String value to insert. 32452 * @param offset { Number } The offset to insert the string at. 32453 * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). 32454 * 32455 * @return this 32456 */ 32457 insertString(value, offset, encoding) { 32458 utils_1.checkOffsetValue(offset); 32459 return this._handleString(value, true, offset, encoding); 32460 } 32461 /** 32462 * Writes a String 32463 * 32464 * @param value { String } The String value to write. 32465 * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. 32466 * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). 32467 * 32468 * @return this 32469 */ 32470 writeString(value, arg2, encoding) { 32471 return this._handleString(value, false, arg2, encoding); 32472 } 32473 /** 32474 * Reads a null-terminated String from the current read position. 32475 * 32476 * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). 32477 * 32478 * @return { String } 32479 */ 32480 readStringNT(encoding) { 32481 if (typeof encoding !== 'undefined') { 32482 utils_1.checkEncoding(encoding); 32483 } 32484 // Set null character position to the end SmartBuffer instance. 32485 let nullPos = this.length; 32486 // Find next null character (if one is not found, default from above is used) 32487 for (let i = this._readOffset; i < this.length; i++) { 32488 if (this._buff[i] === 0x00) { 32489 nullPos = i; 32490 break; 32491 } 32492 } 32493 // Read string value 32494 const value = this._buff.slice(this._readOffset, nullPos); 32495 // Increment internal Buffer read offset 32496 this._readOffset = nullPos + 1; 32497 return value.toString(encoding || this._encoding); 32498 } 32499 /** 32500 * Inserts a null-terminated String. 32501 * 32502 * @param value { String } The String value to write. 32503 * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. 32504 * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). 32505 * 32506 * @return this 32507 */ 32508 insertStringNT(value, offset, encoding) { 32509 utils_1.checkOffsetValue(offset); 32510 // Write Values 32511 this.insertString(value, offset, encoding); 32512 this.insertUInt8(0x00, offset + value.length); 32513 return this; 32514 } 32515 /** 32516 * Writes a null-terminated String. 32517 * 32518 * @param value { String } The String value to write. 32519 * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. 32520 * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). 32521 * 32522 * @return this 32523 */ 32524 writeStringNT(value, arg2, encoding) { 32525 // Write Values 32526 this.writeString(value, arg2, encoding); 32527 this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset); 32528 return this; 32529 } 32530 // Buffers 32531 /** 32532 * Reads a Buffer from the internal read position. 32533 * 32534 * @param length { Number } The length of data to read as a Buffer. 32535 * 32536 * @return { Buffer } 32537 */ 32538 readBuffer(length) { 32539 if (typeof length !== 'undefined') { 32540 utils_1.checkLengthValue(length); 32541 } 32542 const lengthVal = typeof length === 'number' ? length : this.length; 32543 const endPoint = Math.min(this.length, this._readOffset + lengthVal); 32544 // Read buffer value 32545 const value = this._buff.slice(this._readOffset, endPoint); 32546 // Increment internal Buffer read offset 32547 this._readOffset = endPoint; 32548 return value; 32549 } 32550 /** 32551 * Writes a Buffer to the current write position. 32552 * 32553 * @param value { Buffer } The Buffer to write. 32554 * @param offset { Number } The offset to write the Buffer to. 32555 * 32556 * @return this 32557 */ 32558 insertBuffer(value, offset) { 32559 utils_1.checkOffsetValue(offset); 32560 return this._handleBuffer(value, true, offset); 32561 } 32562 /** 32563 * Writes a Buffer to the current write position. 32564 * 32565 * @param value { Buffer } The Buffer to write. 32566 * @param offset { Number } The offset to write the Buffer to. 32567 * 32568 * @return this 32569 */ 32570 writeBuffer(value, offset) { 32571 return this._handleBuffer(value, false, offset); 32572 } 32573 /** 32574 * Reads a null-terminated Buffer from the current read poisiton. 32575 * 32576 * @return { Buffer } 32577 */ 32578 readBufferNT() { 32579 // Set null character position to the end SmartBuffer instance. 32580 let nullPos = this.length; 32581 // Find next null character (if one is not found, default from above is used) 32582 for (let i = this._readOffset; i < this.length; i++) { 32583 if (this._buff[i] === 0x00) { 32584 nullPos = i; 32585 break; 32586 } 32587 } 32588 // Read value 32589 const value = this._buff.slice(this._readOffset, nullPos); 32590 // Increment internal Buffer read offset 32591 this._readOffset = nullPos + 1; 32592 return value; 32593 } 32594 /** 32595 * Inserts a null-terminated Buffer. 32596 * 32597 * @param value { Buffer } The Buffer to write. 32598 * @param offset { Number } The offset to write the Buffer to. 32599 * 32600 * @return this 32601 */ 32602 insertBufferNT(value, offset) { 32603 utils_1.checkOffsetValue(offset); 32604 // Write Values 32605 this.insertBuffer(value, offset); 32606 this.insertUInt8(0x00, offset + value.length); 32607 return this; 32608 } 32609 /** 32610 * Writes a null-terminated Buffer. 32611 * 32612 * @param value { Buffer } The Buffer to write. 32613 * @param offset { Number } The offset to write the Buffer to. 32614 * 32615 * @return this 32616 */ 32617 writeBufferNT(value, offset) { 32618 // Checks for valid numberic value; 32619 if (typeof offset !== 'undefined') { 32620 utils_1.checkOffsetValue(offset); 32621 } 32622 // Write Values 32623 this.writeBuffer(value, offset); 32624 this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset); 32625 return this; 32626 } 32627 /** 32628 * Clears the SmartBuffer instance to its original empty state. 32629 */ 32630 clear() { 32631 this._writeOffset = 0; 32632 this._readOffset = 0; 32633 this.length = 0; 32634 return this; 32635 } 32636 /** 32637 * Gets the remaining data left to be read from the SmartBuffer instance. 32638 * 32639 * @return { Number } 32640 */ 32641 remaining() { 32642 return this.length - this._readOffset; 32643 } 32644 /** 32645 * Gets the current read offset value of the SmartBuffer instance. 32646 * 32647 * @return { Number } 32648 */ 32649 get readOffset() { 32650 return this._readOffset; 32651 } 32652 /** 32653 * Sets the read offset value of the SmartBuffer instance. 32654 * 32655 * @param offset { Number } - The offset value to set. 32656 */ 32657 set readOffset(offset) { 32658 utils_1.checkOffsetValue(offset); 32659 // Check for bounds. 32660 utils_1.checkTargetOffset(offset, this); 32661 this._readOffset = offset; 32662 } 32663 /** 32664 * Gets the current write offset value of the SmartBuffer instance. 32665 * 32666 * @return { Number } 32667 */ 32668 get writeOffset() { 32669 return this._writeOffset; 32670 } 32671 /** 32672 * Sets the write offset value of the SmartBuffer instance. 32673 * 32674 * @param offset { Number } - The offset value to set. 32675 */ 32676 set writeOffset(offset) { 32677 utils_1.checkOffsetValue(offset); 32678 // Check for bounds. 32679 utils_1.checkTargetOffset(offset, this); 32680 this._writeOffset = offset; 32681 } 32682 /** 32683 * Gets the currently set string encoding of the SmartBuffer instance. 32684 * 32685 * @return { BufferEncoding } The string Buffer encoding currently set. 32686 */ 32687 get encoding() { 32688 return this._encoding; 32689 } 32690 /** 32691 * Sets the string encoding of the SmartBuffer instance. 32692 * 32693 * @param encoding { BufferEncoding } The string Buffer encoding to set. 32694 */ 32695 set encoding(encoding) { 32696 utils_1.checkEncoding(encoding); 32697 this._encoding = encoding; 32698 } 32699 /** 32700 * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) 32701 * 32702 * @return { Buffer } The Buffer value. 32703 */ 32704 get internalBuffer() { 32705 return this._buff; 32706 } 32707 /** 32708 * Gets the value of the internal managed Buffer (Includes managed data only) 32709 * 32710 * @param { Buffer } 32711 */ 32712 toBuffer() { 32713 return this._buff.slice(0, this.length); 32714 } 32715 /** 32716 * Gets the String value of the internal managed Buffer 32717 * 32718 * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). 32719 */ 32720 toString(encoding) { 32721 const encodingVal = typeof encoding === 'string' ? encoding : this._encoding; 32722 // Check for invalid encoding. 32723 utils_1.checkEncoding(encodingVal); 32724 return this._buff.toString(encodingVal, 0, this.length); 32725 } 32726 /** 32727 * Destroys the SmartBuffer instance. 32728 */ 32729 destroy() { 32730 this.clear(); 32731 return this; 32732 } 32733 /** 32734 * Handles inserting and writing strings. 32735 * 32736 * @param value { String } The String value to insert. 32737 * @param isInsert { Boolean } True if inserting a string, false if writing. 32738 * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. 32739 * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). 32740 */ 32741 _handleString(value, isInsert, arg3, encoding) { 32742 let offsetVal = this._writeOffset; 32743 let encodingVal = this._encoding; 32744 // Check for offset 32745 if (typeof arg3 === 'number') { 32746 offsetVal = arg3; 32747 // Check for encoding 32748 } 32749 else if (typeof arg3 === 'string') { 32750 utils_1.checkEncoding(arg3); 32751 encodingVal = arg3; 32752 } 32753 // Check for encoding (third param) 32754 if (typeof encoding === 'string') { 32755 utils_1.checkEncoding(encoding); 32756 encodingVal = encoding; 32757 } 32758 // Calculate bytelength of string. 32759 const byteLength = Buffer.byteLength(value, encodingVal); 32760 // Ensure there is enough internal Buffer capacity. 32761 if (isInsert) { 32762 this.ensureInsertable(byteLength, offsetVal); 32763 } 32764 else { 32765 this._ensureWriteable(byteLength, offsetVal); 32766 } 32767 // Write value 32768 this._buff.write(value, offsetVal, byteLength, encodingVal); 32769 // Increment internal Buffer write offset; 32770 if (isInsert) { 32771 this._writeOffset += byteLength; 32772 } 32773 else { 32774 // If an offset was given, check to see if we wrote beyond the current writeOffset. 32775 if (typeof arg3 === 'number') { 32776 this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); 32777 } 32778 else { 32779 // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. 32780 this._writeOffset += byteLength; 32781 } 32782 } 32783 return this; 32784 } 32785 /** 32786 * Handles writing or insert of a Buffer. 32787 * 32788 * @param value { Buffer } The Buffer to write. 32789 * @param offset { Number } The offset to write the Buffer to. 32790 */ 32791 _handleBuffer(value, isInsert, offset) { 32792 const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; 32793 // Ensure there is enough internal Buffer capacity. 32794 if (isInsert) { 32795 this.ensureInsertable(value.length, offsetVal); 32796 } 32797 else { 32798 this._ensureWriteable(value.length, offsetVal); 32799 } 32800 // Write buffer value 32801 value.copy(this._buff, offsetVal); 32802 // Increment internal Buffer write offset; 32803 if (isInsert) { 32804 this._writeOffset += value.length; 32805 } 32806 else { 32807 // If an offset was given, check to see if we wrote beyond the current writeOffset. 32808 if (typeof offset === 'number') { 32809 this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); 32810 } 32811 else { 32812 // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. 32813 this._writeOffset += value.length; 32814 } 32815 } 32816 return this; 32817 } 32818 /** 32819 * Ensures that the internal Buffer is large enough to read data. 32820 * 32821 * @param length { Number } The length of the data that needs to be read. 32822 * @param offset { Number } The offset of the data that needs to be read. 32823 */ 32824 ensureReadable(length, offset) { 32825 // Offset value defaults to managed read offset. 32826 let offsetVal = this._readOffset; 32827 // If an offset was provided, use it. 32828 if (typeof offset !== 'undefined') { 32829 // Checks for valid numberic value; 32830 utils_1.checkOffsetValue(offset); 32831 // Overide with custom offset. 32832 offsetVal = offset; 32833 } 32834 // Checks if offset is below zero, or the offset+length offset is beyond the total length of the managed data. 32835 if (offsetVal < 0 || offsetVal + length > this.length) { 32836 throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); 32837 } 32838 } 32839 /** 32840 * Ensures that the internal Buffer is large enough to insert data. 32841 * 32842 * @param dataLength { Number } The length of the data that needs to be written. 32843 * @param offset { Number } The offset of the data to be written. 32844 */ 32845 ensureInsertable(dataLength, offset) { 32846 // Checks for valid numberic value; 32847 utils_1.checkOffsetValue(offset); 32848 // Ensure there is enough internal Buffer capacity. 32849 this._ensureCapacity(this.length + dataLength); 32850 // If an offset was provided and its not the very end of the buffer, copy data into appropriate location in regards to the offset. 32851 if (offset < this.length) { 32852 this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); 32853 } 32854 // Adjust tracked smart buffer length 32855 if (offset + dataLength > this.length) { 32856 this.length = offset + dataLength; 32857 } 32858 else { 32859 this.length += dataLength; 32860 } 32861 } 32862 /** 32863 * Ensures that the internal Buffer is large enough to write data. 32864 * 32865 * @param dataLength { Number } The length of the data that needs to be written. 32866 * @param offset { Number } The offset of the data to be written (defaults to writeOffset). 32867 */ 32868 _ensureWriteable(dataLength, offset) { 32869 const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; 32870 // Ensure enough capacity to write data. 32871 this._ensureCapacity(offsetVal + dataLength); 32872 // Adjust SmartBuffer length (if offset + length is larger than managed length, adjust length) 32873 if (offsetVal + dataLength > this.length) { 32874 this.length = offsetVal + dataLength; 32875 } 32876 } 32877 /** 32878 * Ensures that the internal Buffer is large enough to write at least the given amount of data. 32879 * 32880 * @param minLength { Number } The minimum length of the data needs to be written. 32881 */ 32882 _ensureCapacity(minLength) { 32883 const oldLength = this._buff.length; 32884 if (minLength > oldLength) { 32885 let data = this._buff; 32886 let newLength = (oldLength * 3) / 2 + 1; 32887 if (newLength < minLength) { 32888 newLength = minLength; 32889 } 32890 this._buff = Buffer.allocUnsafe(newLength); 32891 data.copy(this._buff, 0, 0, oldLength); 32892 } 32893 } 32894 /** 32895 * Reads a numeric number value using the provided function. 32896 * 32897 * @typeparam T { number | bigint } The type of the value to be read 32898 * 32899 * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. 32900 * @param byteSize { Number } The number of bytes read. 32901 * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. 32902 * 32903 * @returns { T } the number value 32904 */ 32905 _readNumberValue(func, byteSize, offset) { 32906 this.ensureReadable(byteSize, offset); 32907 // Call Buffer.readXXXX(); 32908 const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset); 32909 // Adjust internal read offset if an optional read offset was not provided. 32910 if (typeof offset === 'undefined') { 32911 this._readOffset += byteSize; 32912 } 32913 return value; 32914 } 32915 /** 32916 * Inserts a numeric number value based on the given offset and value. 32917 * 32918 * @typeparam T { number | bigint } The type of the value to be written 32919 * 32920 * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. 32921 * @param byteSize { Number } The number of bytes written. 32922 * @param value { T } The number value to write. 32923 * @param offset { Number } the offset to write the number at (REQUIRED). 32924 * 32925 * @returns SmartBuffer this buffer 32926 */ 32927 _insertNumberValue(func, byteSize, value, offset) { 32928 // Check for invalid offset values. 32929 utils_1.checkOffsetValue(offset); 32930 // Ensure there is enough internal Buffer capacity. (raw offset is passed) 32931 this.ensureInsertable(byteSize, offset); 32932 // Call buffer.writeXXXX(); 32933 func.call(this._buff, value, offset); 32934 // Adjusts internally managed write offset. 32935 this._writeOffset += byteSize; 32936 return this; 32937 } 32938 /** 32939 * Writes a numeric number value based on the given offset and value. 32940 * 32941 * @typeparam T { number | bigint } The type of the value to be written 32942 * 32943 * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. 32944 * @param byteSize { Number } The number of bytes written. 32945 * @param value { T } The number value to write. 32946 * @param offset { Number } the offset to write the number at (REQUIRED). 32947 * 32948 * @returns SmartBuffer this buffer 32949 */ 32950 _writeNumberValue(func, byteSize, value, offset) { 32951 // If an offset was provided, validate it. 32952 if (typeof offset === 'number') { 32953 // Check if we're writing beyond the bounds of the managed data. 32954 if (offset < 0) { 32955 throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); 32956 } 32957 utils_1.checkOffsetValue(offset); 32958 } 32959 // Default to writeOffset if no offset value was given. 32960 const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; 32961 // Ensure there is enough internal Buffer capacity. (raw offset is passed) 32962 this._ensureWriteable(byteSize, offsetVal); 32963 func.call(this._buff, value, offsetVal); 32964 // If an offset was given, check to see if we wrote beyond the current writeOffset. 32965 if (typeof offset === 'number') { 32966 this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); 32967 } 32968 else { 32969 // If no numeric offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. 32970 this._writeOffset += byteSize; 32971 } 32972 return this; 32973 } 32974 } 32975 exports.SmartBuffer = SmartBuffer; 32976 //# sourceMappingURL=smartbuffer.js.map 32977 32978 /***/ }), 32979 32980 /***/ 8132: 32981 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 32982 32983 "use strict"; 32984 32985 Object.defineProperty(exports, "__esModule", ({ value: true })); 32986 const buffer_1 = __nccwpck_require__(4300); 32987 /** 32988 * Error strings 32989 */ 32990 const ERRORS = { 32991 INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.', 32992 INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.', 32993 INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.', 32994 INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.', 32995 INVALID_OFFSET: 'An invalid offset value was provided.', 32996 INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.', 32997 INVALID_LENGTH: 'An invalid length value was provided.', 32998 INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.', 32999 INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.', 33000 INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.', 33001 INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.', 33002 INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.' 33003 }; 33004 exports.ERRORS = ERRORS; 33005 /** 33006 * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) 33007 * 33008 * @param { String } encoding The encoding string to check. 33009 */ 33010 function checkEncoding(encoding) { 33011 if (!buffer_1.Buffer.isEncoding(encoding)) { 33012 throw new Error(ERRORS.INVALID_ENCODING); 33013 } 33014 } 33015 exports.checkEncoding = checkEncoding; 33016 /** 33017 * Checks if a given number is a finite integer. (Throws an exception if check fails) 33018 * 33019 * @param { Number } value The number value to check. 33020 */ 33021 function isFiniteInteger(value) { 33022 return typeof value === 'number' && isFinite(value) && isInteger(value); 33023 } 33024 exports.isFiniteInteger = isFiniteInteger; 33025 /** 33026 * Checks if an offset/length value is valid. (Throws an exception if check fails) 33027 * 33028 * @param value The value to check. 33029 * @param offset True if checking an offset, false if checking a length. 33030 */ 33031 function checkOffsetOrLengthValue(value, offset) { 33032 if (typeof value === 'number') { 33033 // Check for non finite/non integers 33034 if (!isFiniteInteger(value) || value < 0) { 33035 throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); 33036 } 33037 } 33038 else { 33039 throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); 33040 } 33041 } 33042 /** 33043 * Checks if a length value is valid. (Throws an exception if check fails) 33044 * 33045 * @param { Number } length The value to check. 33046 */ 33047 function checkLengthValue(length) { 33048 checkOffsetOrLengthValue(length, false); 33049 } 33050 exports.checkLengthValue = checkLengthValue; 33051 /** 33052 * Checks if a offset value is valid. (Throws an exception if check fails) 33053 * 33054 * @param { Number } offset The value to check. 33055 */ 33056 function checkOffsetValue(offset) { 33057 checkOffsetOrLengthValue(offset, true); 33058 } 33059 exports.checkOffsetValue = checkOffsetValue; 33060 /** 33061 * Checks if a target offset value is out of bounds. (Throws an exception if check fails) 33062 * 33063 * @param { Number } offset The offset value to check. 33064 * @param { SmartBuffer } buff The SmartBuffer instance to check against. 33065 */ 33066 function checkTargetOffset(offset, buff) { 33067 if (offset < 0 || offset > buff.length) { 33068 throw new Error(ERRORS.INVALID_TARGET_OFFSET); 33069 } 33070 } 33071 exports.checkTargetOffset = checkTargetOffset; 33072 /** 33073 * Determines whether a given number is a integer. 33074 * @param value The number to check. 33075 */ 33076 function isInteger(value) { 33077 return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; 33078 } 33079 /** 33080 * Throws if Node.js version is too low to support bigint 33081 */ 33082 function bigIntAndBufferInt64Check(bufferMethod) { 33083 if (typeof BigInt === 'undefined') { 33084 throw new Error('Platform does not support JS BigInt type.'); 33085 } 33086 if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') { 33087 throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); 33088 } 33089 } 33090 exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; 33091 //# sourceMappingURL=utils.js.map 33092 33093 /***/ }), 33094 33095 /***/ 5038: 33096 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 33097 33098 "use strict"; 33099 33100 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 33101 if (k2 === undefined) k2 = k; 33102 var desc = Object.getOwnPropertyDescriptor(m, k); 33103 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 33104 desc = { enumerable: true, get: function() { return m[k]; } }; 33105 } 33106 Object.defineProperty(o, k2, desc); 33107 }) : (function(o, m, k, k2) { 33108 if (k2 === undefined) k2 = k; 33109 o[k2] = m[k]; 33110 })); 33111 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 33112 Object.defineProperty(o, "default", { enumerable: true, value: v }); 33113 }) : function(o, v) { 33114 o["default"] = v; 33115 }); 33116 var __importStar = (this && this.__importStar) || function (mod) { 33117 if (mod && mod.__esModule) return mod; 33118 var result = {}; 33119 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 33120 __setModuleDefault(result, mod); 33121 return result; 33122 }; 33123 var __importDefault = (this && this.__importDefault) || function (mod) { 33124 return (mod && mod.__esModule) ? mod : { "default": mod }; 33125 }; 33126 Object.defineProperty(exports, "__esModule", ({ value: true })); 33127 exports.SocksProxyAgent = void 0; 33128 const socks_1 = __nccwpck_require__(4754); 33129 const agent_base_1 = __nccwpck_require__(694); 33130 const debug_1 = __importDefault(__nccwpck_require__(8237)); 33131 const dns = __importStar(__nccwpck_require__(9523)); 33132 const net = __importStar(__nccwpck_require__(1808)); 33133 const tls = __importStar(__nccwpck_require__(4404)); 33134 const url_1 = __nccwpck_require__(7310); 33135 const debug = (0, debug_1.default)('socks-proxy-agent'); 33136 function parseSocksURL(url) { 33137 let lookup = false; 33138 let type = 5; 33139 const host = url.hostname; 33140 // From RFC 1928, Section 3: https://tools.ietf.org/html/rfc1928#section-3 33141 // "The SOCKS service is conventionally located on TCP port 1080" 33142 const port = parseInt(url.port, 10) || 1080; 33143 // figure out if we want socks v4 or v5, based on the "protocol" used. 33144 // Defaults to 5. 33145 switch (url.protocol.replace(':', '')) { 33146 case 'socks4': 33147 lookup = true; 33148 type = 4; 33149 break; 33150 // pass through 33151 case 'socks4a': 33152 type = 4; 33153 break; 33154 case 'socks5': 33155 lookup = true; 33156 type = 5; 33157 break; 33158 // pass through 33159 case 'socks': // no version specified, default to 5h 33160 type = 5; 33161 break; 33162 case 'socks5h': 33163 type = 5; 33164 break; 33165 default: 33166 throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`); 33167 } 33168 const proxy = { 33169 host, 33170 port, 33171 type, 33172 }; 33173 if (url.username) { 33174 Object.defineProperty(proxy, 'userId', { 33175 value: decodeURIComponent(url.username), 33176 enumerable: false, 33177 }); 33178 } 33179 if (url.password != null) { 33180 Object.defineProperty(proxy, 'password', { 33181 value: decodeURIComponent(url.password), 33182 enumerable: false, 33183 }); 33184 } 33185 return { lookup, proxy }; 33186 } 33187 class SocksProxyAgent extends agent_base_1.Agent { 33188 constructor(uri, opts) { 33189 super(opts); 33190 const url = typeof uri === 'string' ? new url_1.URL(uri) : uri; 33191 const { proxy, lookup } = parseSocksURL(url); 33192 this.shouldLookup = lookup; 33193 this.proxy = proxy; 33194 this.timeout = opts?.timeout ?? null; 33195 } 33196 /** 33197 * Initiates a SOCKS connection to the specified SOCKS proxy server, 33198 * which in turn connects to the specified remote host and port. 33199 */ 33200 async connect(req, opts) { 33201 const { shouldLookup, proxy, timeout } = this; 33202 if (!opts.host) { 33203 throw new Error('No `host` defined!'); 33204 } 33205 let { host } = opts; 33206 const { port, lookup: lookupFn = dns.lookup } = opts; 33207 if (shouldLookup) { 33208 // Client-side DNS resolution for "4" and "5" socks proxy versions. 33209 host = await new Promise((resolve, reject) => { 33210 // Use the request's custom lookup, if one was configured: 33211 lookupFn(host, {}, (err, res) => { 33212 if (err) { 33213 reject(err); 33214 } 33215 else { 33216 resolve(res); 33217 } 33218 }); 33219 }); 33220 } 33221 const socksOpts = { 33222 proxy, 33223 destination: { 33224 host, 33225 port: typeof port === 'number' ? port : parseInt(port, 10), 33226 }, 33227 command: 'connect', 33228 timeout: timeout ?? undefined, 33229 }; 33230 const cleanup = (tlsSocket) => { 33231 req.destroy(); 33232 socket.destroy(); 33233 if (tlsSocket) 33234 tlsSocket.destroy(); 33235 }; 33236 debug('Creating socks proxy connection: %o', socksOpts); 33237 const { socket } = await socks_1.SocksClient.createConnection(socksOpts); 33238 debug('Successfully created socks proxy connection'); 33239 if (timeout !== null) { 33240 socket.setTimeout(timeout); 33241 socket.on('timeout', () => cleanup()); 33242 } 33243 if (opts.secureEndpoint) { 33244 // The proxy is connecting to a TLS server, so upgrade 33245 // this socket connection to a TLS connection. 33246 debug('Upgrading socket connection to TLS'); 33247 const servername = opts.servername || opts.host; 33248 const tlsSocket = tls.connect({ 33249 ...omit(opts, 'host', 'path', 'port'), 33250 socket, 33251 servername: net.isIP(servername) ? undefined : servername, 33252 }); 33253 tlsSocket.once('error', (error) => { 33254 debug('Socket TLS error', error.message); 33255 cleanup(tlsSocket); 33256 }); 33257 return tlsSocket; 33258 } 33259 return socket; 33260 } 33261 } 33262 SocksProxyAgent.protocols = [ 33263 'socks', 33264 'socks4', 33265 'socks4a', 33266 'socks5', 33267 'socks5h', 33268 ]; 33269 exports.SocksProxyAgent = SocksProxyAgent; 33270 function omit(obj, ...keys) { 33271 const ret = {}; 33272 let key; 33273 for (key in obj) { 33274 if (!keys.includes(key)) { 33275 ret[key] = obj[key]; 33276 } 33277 } 33278 return ret; 33279 } 33280 //# sourceMappingURL=index.js.map 33281 33282 /***/ }), 33283 33284 /***/ 6127: 33285 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 33286 33287 "use strict"; 33288 33289 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 33290 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 33291 return new (P || (P = Promise))(function (resolve, reject) { 33292 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 33293 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 33294 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 33295 step((generator = generator.apply(thisArg, _arguments || [])).next()); 33296 }); 33297 }; 33298 Object.defineProperty(exports, "__esModule", ({ value: true })); 33299 exports.SocksClientError = exports.SocksClient = void 0; 33300 const events_1 = __nccwpck_require__(2361); 33301 const net = __nccwpck_require__(1808); 33302 const smart_buffer_1 = __nccwpck_require__(1062); 33303 const constants_1 = __nccwpck_require__(9647); 33304 const helpers_1 = __nccwpck_require__(4324); 33305 const receivebuffer_1 = __nccwpck_require__(9740); 33306 const util_1 = __nccwpck_require__(5523); 33307 Object.defineProperty(exports, "SocksClientError", ({ enumerable: true, get: function () { return util_1.SocksClientError; } })); 33308 const ip_address_1 = __nccwpck_require__(8953); 33309 class SocksClient extends events_1.EventEmitter { 33310 constructor(options) { 33311 super(); 33312 this.options = Object.assign({}, options); 33313 // Validate SocksClientOptions 33314 (0, helpers_1.validateSocksClientOptions)(options); 33315 // Default state 33316 this.setState(constants_1.SocksClientState.Created); 33317 } 33318 /** 33319 * Creates a new SOCKS connection. 33320 * 33321 * Note: Supports callbacks and promises. Only supports the connect command. 33322 * @param options { SocksClientOptions } Options. 33323 * @param callback { Function } An optional callback function. 33324 * @returns { Promise } 33325 */ 33326 static createConnection(options, callback) { 33327 return new Promise((resolve, reject) => { 33328 // Validate SocksClientOptions 33329 try { 33330 (0, helpers_1.validateSocksClientOptions)(options, ['connect']); 33331 } 33332 catch (err) { 33333 if (typeof callback === 'function') { 33334 callback(err); 33335 // eslint-disable-next-line @typescript-eslint/no-explicit-any 33336 return resolve(err); // Resolves pending promise (prevents memory leaks). 33337 } 33338 else { 33339 return reject(err); 33340 } 33341 } 33342 const client = new SocksClient(options); 33343 client.connect(options.existing_socket); 33344 client.once('established', (info) => { 33345 client.removeAllListeners(); 33346 if (typeof callback === 'function') { 33347 callback(null, info); 33348 resolve(info); // Resolves pending promise (prevents memory leaks). 33349 } 33350 else { 33351 resolve(info); 33352 } 33353 }); 33354 // Error occurred, failed to establish connection. 33355 client.once('error', (err) => { 33356 client.removeAllListeners(); 33357 if (typeof callback === 'function') { 33358 callback(err); 33359 // eslint-disable-next-line @typescript-eslint/no-explicit-any 33360 resolve(err); // Resolves pending promise (prevents memory leaks). 33361 } 33362 else { 33363 reject(err); 33364 } 33365 }); 33366 }); 33367 } 33368 /** 33369 * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. 33370 * 33371 * Note: Supports callbacks and promises. Only supports the connect method. 33372 * Note: Implemented via createConnection() factory function. 33373 * @param options { SocksClientChainOptions } Options 33374 * @param callback { Function } An optional callback function. 33375 * @returns { Promise } 33376 */ 33377 static createConnectionChain(options, callback) { 33378 // eslint-disable-next-line no-async-promise-executor 33379 return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { 33380 // Validate SocksClientChainOptions 33381 try { 33382 (0, helpers_1.validateSocksClientChainOptions)(options); 33383 } 33384 catch (err) { 33385 if (typeof callback === 'function') { 33386 callback(err); 33387 // eslint-disable-next-line @typescript-eslint/no-explicit-any 33388 return resolve(err); // Resolves pending promise (prevents memory leaks). 33389 } 33390 else { 33391 return reject(err); 33392 } 33393 } 33394 // Shuffle proxies 33395 if (options.randomizeChain) { 33396 (0, util_1.shuffleArray)(options.proxies); 33397 } 33398 try { 33399 let sock; 33400 for (let i = 0; i < options.proxies.length; i++) { 33401 const nextProxy = options.proxies[i]; 33402 // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy. 33403 const nextDestination = i === options.proxies.length - 1 33404 ? options.destination 33405 : { 33406 host: options.proxies[i + 1].host || 33407 options.proxies[i + 1].ipaddress, 33408 port: options.proxies[i + 1].port, 33409 }; 33410 // Creates the next connection in the chain. 33411 const result = yield SocksClient.createConnection({ 33412 command: 'connect', 33413 proxy: nextProxy, 33414 destination: nextDestination, 33415 existing_socket: sock, 33416 }); 33417 // If sock is undefined, assign it here. 33418 sock = sock || result.socket; 33419 } 33420 if (typeof callback === 'function') { 33421 callback(null, { socket: sock }); 33422 resolve({ socket: sock }); // Resolves pending promise (prevents memory leaks). 33423 } 33424 else { 33425 resolve({ socket: sock }); 33426 } 33427 } 33428 catch (err) { 33429 if (typeof callback === 'function') { 33430 callback(err); 33431 // eslint-disable-next-line @typescript-eslint/no-explicit-any 33432 resolve(err); // Resolves pending promise (prevents memory leaks). 33433 } 33434 else { 33435 reject(err); 33436 } 33437 } 33438 })); 33439 } 33440 /** 33441 * Creates a SOCKS UDP Frame. 33442 * @param options 33443 */ 33444 static createUDPFrame(options) { 33445 const buff = new smart_buffer_1.SmartBuffer(); 33446 buff.writeUInt16BE(0); 33447 buff.writeUInt8(options.frameNumber || 0); 33448 // IPv4/IPv6/Hostname 33449 if (net.isIPv4(options.remoteHost.host)) { 33450 buff.writeUInt8(constants_1.Socks5HostType.IPv4); 33451 buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host)); 33452 } 33453 else if (net.isIPv6(options.remoteHost.host)) { 33454 buff.writeUInt8(constants_1.Socks5HostType.IPv6); 33455 buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host)); 33456 } 33457 else { 33458 buff.writeUInt8(constants_1.Socks5HostType.Hostname); 33459 buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); 33460 buff.writeString(options.remoteHost.host); 33461 } 33462 // Port 33463 buff.writeUInt16BE(options.remoteHost.port); 33464 // Data 33465 buff.writeBuffer(options.data); 33466 return buff.toBuffer(); 33467 } 33468 /** 33469 * Parses a SOCKS UDP frame. 33470 * @param data 33471 */ 33472 static parseUDPFrame(data) { 33473 const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); 33474 buff.readOffset = 2; 33475 const frameNumber = buff.readUInt8(); 33476 const hostType = buff.readUInt8(); 33477 let remoteHost; 33478 if (hostType === constants_1.Socks5HostType.IPv4) { 33479 remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()); 33480 } 33481 else if (hostType === constants_1.Socks5HostType.IPv6) { 33482 remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(); 33483 } 33484 else { 33485 remoteHost = buff.readString(buff.readUInt8()); 33486 } 33487 const remotePort = buff.readUInt16BE(); 33488 return { 33489 frameNumber, 33490 remoteHost: { 33491 host: remoteHost, 33492 port: remotePort, 33493 }, 33494 data: buff.readBuffer(), 33495 }; 33496 } 33497 /** 33498 * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. 33499 */ 33500 setState(newState) { 33501 if (this.state !== constants_1.SocksClientState.Error) { 33502 this.state = newState; 33503 } 33504 } 33505 /** 33506 * Starts the connection establishment to the proxy and destination. 33507 * @param existingSocket Connected socket to use instead of creating a new one (internal use). 33508 */ 33509 connect(existingSocket) { 33510 this.onDataReceived = (data) => this.onDataReceivedHandler(data); 33511 this.onClose = () => this.onCloseHandler(); 33512 this.onError = (err) => this.onErrorHandler(err); 33513 this.onConnect = () => this.onConnectHandler(); 33514 // Start timeout timer (defaults to 30 seconds) 33515 const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT); 33516 // check whether unref is available as it differs from browser to NodeJS (#33) 33517 if (timer.unref && typeof timer.unref === 'function') { 33518 timer.unref(); 33519 } 33520 // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket. 33521 if (existingSocket) { 33522 this.socket = existingSocket; 33523 } 33524 else { 33525 this.socket = new net.Socket(); 33526 } 33527 // Attach Socket error handlers. 33528 this.socket.once('close', this.onClose); 33529 this.socket.once('error', this.onError); 33530 this.socket.once('connect', this.onConnect); 33531 this.socket.on('data', this.onDataReceived); 33532 this.setState(constants_1.SocksClientState.Connecting); 33533 this.receiveBuffer = new receivebuffer_1.ReceiveBuffer(); 33534 if (existingSocket) { 33535 this.socket.emit('connect'); 33536 } 33537 else { 33538 this.socket.connect(this.getSocketOptions()); 33539 if (this.options.set_tcp_nodelay !== undefined && 33540 this.options.set_tcp_nodelay !== null) { 33541 this.socket.setNoDelay(!!this.options.set_tcp_nodelay); 33542 } 33543 } 33544 // Listen for established event so we can re-emit any excess data received during handshakes. 33545 this.prependOnceListener('established', (info) => { 33546 setImmediate(() => { 33547 if (this.receiveBuffer.length > 0) { 33548 const excessData = this.receiveBuffer.get(this.receiveBuffer.length); 33549 info.socket.emit('data', excessData); 33550 } 33551 info.socket.resume(); 33552 }); 33553 }); 33554 } 33555 // Socket options (defaults host/port to options.proxy.host/options.proxy.port) 33556 getSocketOptions() { 33557 return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port }); 33558 } 33559 /** 33560 * Handles internal Socks timeout callback. 33561 * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. 33562 */ 33563 onEstablishedTimeout() { 33564 if (this.state !== constants_1.SocksClientState.Established && 33565 this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { 33566 this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); 33567 } 33568 } 33569 /** 33570 * Handles Socket connect event. 33571 */ 33572 onConnectHandler() { 33573 this.setState(constants_1.SocksClientState.Connected); 33574 // Send initial handshake. 33575 if (this.options.proxy.type === 4) { 33576 this.sendSocks4InitialHandshake(); 33577 } 33578 else { 33579 this.sendSocks5InitialHandshake(); 33580 } 33581 this.setState(constants_1.SocksClientState.SentInitialHandshake); 33582 } 33583 /** 33584 * Handles Socket data event. 33585 * @param data 33586 */ 33587 onDataReceivedHandler(data) { 33588 /* 33589 All received data is appended to a ReceiveBuffer. 33590 This makes sure that all the data we need is received before we attempt to process it. 33591 */ 33592 this.receiveBuffer.append(data); 33593 // Process data that we have. 33594 this.processData(); 33595 } 33596 /** 33597 * Handles processing of the data we have received. 33598 */ 33599 processData() { 33600 // If we have enough data to process the next step in the SOCKS handshake, proceed. 33601 while (this.state !== constants_1.SocksClientState.Established && 33602 this.state !== constants_1.SocksClientState.Error && 33603 this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) { 33604 // Sent initial handshake, waiting for response. 33605 if (this.state === constants_1.SocksClientState.SentInitialHandshake) { 33606 if (this.options.proxy.type === 4) { 33607 // Socks v4 only has one handshake response. 33608 this.handleSocks4FinalHandshakeResponse(); 33609 } 33610 else { 33611 // Socks v5 has two handshakes, handle initial one here. 33612 this.handleInitialSocks5HandshakeResponse(); 33613 } 33614 // Sent auth request for Socks v5, waiting for response. 33615 } 33616 else if (this.state === constants_1.SocksClientState.SentAuthentication) { 33617 this.handleInitialSocks5AuthenticationHandshakeResponse(); 33618 // Sent final Socks v5 handshake, waiting for final response. 33619 } 33620 else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { 33621 this.handleSocks5FinalHandshakeResponse(); 33622 // Socks BIND established. Waiting for remote connection via proxy. 33623 } 33624 else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { 33625 if (this.options.proxy.type === 4) { 33626 this.handleSocks4IncomingConnectionResponse(); 33627 } 33628 else { 33629 this.handleSocks5IncomingConnectionResponse(); 33630 } 33631 } 33632 else { 33633 this.closeSocket(constants_1.ERRORS.InternalError); 33634 break; 33635 } 33636 } 33637 } 33638 /** 33639 * Handles Socket close event. 33640 * @param had_error 33641 */ 33642 onCloseHandler() { 33643 this.closeSocket(constants_1.ERRORS.SocketClosed); 33644 } 33645 /** 33646 * Handles Socket error event. 33647 * @param err 33648 */ 33649 onErrorHandler(err) { 33650 this.closeSocket(err.message); 33651 } 33652 /** 33653 * Removes internal event listeners on the underlying Socket. 33654 */ 33655 removeInternalSocketHandlers() { 33656 // Pauses data flow of the socket (this is internally resumed after 'established' is emitted) 33657 this.socket.pause(); 33658 this.socket.removeListener('data', this.onDataReceived); 33659 this.socket.removeListener('close', this.onClose); 33660 this.socket.removeListener('error', this.onError); 33661 this.socket.removeListener('connect', this.onConnect); 33662 } 33663 /** 33664 * Closes and destroys the underlying Socket. Emits an error event. 33665 * @param err { String } An error string to include in error event. 33666 */ 33667 closeSocket(err) { 33668 // Make sure only one 'error' event is fired for the lifetime of this SocksClient instance. 33669 if (this.state !== constants_1.SocksClientState.Error) { 33670 // Set internal state to Error. 33671 this.setState(constants_1.SocksClientState.Error); 33672 // Destroy Socket 33673 this.socket.destroy(); 33674 // Remove internal listeners 33675 this.removeInternalSocketHandlers(); 33676 // Fire 'error' event. 33677 this.emit('error', new util_1.SocksClientError(err, this.options)); 33678 } 33679 } 33680 /** 33681 * Sends initial Socks v4 handshake request. 33682 */ 33683 sendSocks4InitialHandshake() { 33684 const userId = this.options.proxy.userId || ''; 33685 const buff = new smart_buffer_1.SmartBuffer(); 33686 buff.writeUInt8(0x04); 33687 buff.writeUInt8(constants_1.SocksCommand[this.options.command]); 33688 buff.writeUInt16BE(this.options.destination.port); 33689 // Socks 4 (IPv4) 33690 if (net.isIPv4(this.options.destination.host)) { 33691 buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); 33692 buff.writeStringNT(userId); 33693 // Socks 4a (hostname) 33694 } 33695 else { 33696 buff.writeUInt8(0x00); 33697 buff.writeUInt8(0x00); 33698 buff.writeUInt8(0x00); 33699 buff.writeUInt8(0x01); 33700 buff.writeStringNT(userId); 33701 buff.writeStringNT(this.options.destination.host); 33702 } 33703 this.nextRequiredPacketBufferSize = 33704 constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; 33705 this.socket.write(buff.toBuffer()); 33706 } 33707 /** 33708 * Handles Socks v4 handshake response. 33709 * @param data 33710 */ 33711 handleSocks4FinalHandshakeResponse() { 33712 const data = this.receiveBuffer.get(8); 33713 if (data[1] !== constants_1.Socks4Response.Granted) { 33714 this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`); 33715 } 33716 else { 33717 // Bind response 33718 if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { 33719 const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); 33720 buff.readOffset = 2; 33721 const remoteHost = { 33722 port: buff.readUInt16BE(), 33723 host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), 33724 }; 33725 // If host is 0.0.0.0, set to proxy host. 33726 if (remoteHost.host === '0.0.0.0') { 33727 remoteHost.host = this.options.proxy.ipaddress; 33728 } 33729 this.setState(constants_1.SocksClientState.BoundWaitingForConnection); 33730 this.emit('bound', { remoteHost, socket: this.socket }); 33731 // Connect response 33732 } 33733 else { 33734 this.setState(constants_1.SocksClientState.Established); 33735 this.removeInternalSocketHandlers(); 33736 this.emit('established', { socket: this.socket }); 33737 } 33738 } 33739 } 33740 /** 33741 * Handles Socks v4 incoming connection request (BIND) 33742 * @param data 33743 */ 33744 handleSocks4IncomingConnectionResponse() { 33745 const data = this.receiveBuffer.get(8); 33746 if (data[1] !== constants_1.Socks4Response.Granted) { 33747 this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`); 33748 } 33749 else { 33750 const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); 33751 buff.readOffset = 2; 33752 const remoteHost = { 33753 port: buff.readUInt16BE(), 33754 host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), 33755 }; 33756 this.setState(constants_1.SocksClientState.Established); 33757 this.removeInternalSocketHandlers(); 33758 this.emit('established', { remoteHost, socket: this.socket }); 33759 } 33760 } 33761 /** 33762 * Sends initial Socks v5 handshake request. 33763 */ 33764 sendSocks5InitialHandshake() { 33765 const buff = new smart_buffer_1.SmartBuffer(); 33766 // By default we always support no auth. 33767 const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth]; 33768 // We should only tell the proxy we support user/pass auth if auth info is actually provided. 33769 // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority. 33770 if (this.options.proxy.userId || this.options.proxy.password) { 33771 supportedAuthMethods.push(constants_1.Socks5Auth.UserPass); 33772 } 33773 // Custom auth method? 33774 if (this.options.proxy.custom_auth_method !== undefined) { 33775 supportedAuthMethods.push(this.options.proxy.custom_auth_method); 33776 } 33777 // Build handshake packet 33778 buff.writeUInt8(0x05); 33779 buff.writeUInt8(supportedAuthMethods.length); 33780 for (const authMethod of supportedAuthMethods) { 33781 buff.writeUInt8(authMethod); 33782 } 33783 this.nextRequiredPacketBufferSize = 33784 constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse; 33785 this.socket.write(buff.toBuffer()); 33786 this.setState(constants_1.SocksClientState.SentInitialHandshake); 33787 } 33788 /** 33789 * Handles initial Socks v5 handshake response. 33790 * @param data 33791 */ 33792 handleInitialSocks5HandshakeResponse() { 33793 const data = this.receiveBuffer.get(2); 33794 if (data[0] !== 0x05) { 33795 this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion); 33796 } 33797 else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) { 33798 this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType); 33799 } 33800 else { 33801 // If selected Socks v5 auth method is no auth, send final handshake request. 33802 if (data[1] === constants_1.Socks5Auth.NoAuth) { 33803 this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth; 33804 this.sendSocks5CommandRequest(); 33805 // If selected Socks v5 auth method is user/password, send auth handshake. 33806 } 33807 else if (data[1] === constants_1.Socks5Auth.UserPass) { 33808 this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass; 33809 this.sendSocks5UserPassAuthentication(); 33810 // If selected Socks v5 auth method is the custom_auth_method, send custom handshake. 33811 } 33812 else if (data[1] === this.options.proxy.custom_auth_method) { 33813 this.socks5ChosenAuthType = this.options.proxy.custom_auth_method; 33814 this.sendSocks5CustomAuthentication(); 33815 } 33816 else { 33817 this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType); 33818 } 33819 } 33820 } 33821 /** 33822 * Sends Socks v5 user & password auth handshake. 33823 * 33824 * Note: No auth and user/pass are currently supported. 33825 */ 33826 sendSocks5UserPassAuthentication() { 33827 const userId = this.options.proxy.userId || ''; 33828 const password = this.options.proxy.password || ''; 33829 const buff = new smart_buffer_1.SmartBuffer(); 33830 buff.writeUInt8(0x01); 33831 buff.writeUInt8(Buffer.byteLength(userId)); 33832 buff.writeString(userId); 33833 buff.writeUInt8(Buffer.byteLength(password)); 33834 buff.writeString(password); 33835 this.nextRequiredPacketBufferSize = 33836 constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; 33837 this.socket.write(buff.toBuffer()); 33838 this.setState(constants_1.SocksClientState.SentAuthentication); 33839 } 33840 sendSocks5CustomAuthentication() { 33841 return __awaiter(this, void 0, void 0, function* () { 33842 this.nextRequiredPacketBufferSize = 33843 this.options.proxy.custom_auth_response_size; 33844 this.socket.write(yield this.options.proxy.custom_auth_request_handler()); 33845 this.setState(constants_1.SocksClientState.SentAuthentication); 33846 }); 33847 } 33848 handleSocks5CustomAuthHandshakeResponse(data) { 33849 return __awaiter(this, void 0, void 0, function* () { 33850 return yield this.options.proxy.custom_auth_response_handler(data); 33851 }); 33852 } 33853 handleSocks5AuthenticationNoAuthHandshakeResponse(data) { 33854 return __awaiter(this, void 0, void 0, function* () { 33855 return data[1] === 0x00; 33856 }); 33857 } 33858 handleSocks5AuthenticationUserPassHandshakeResponse(data) { 33859 return __awaiter(this, void 0, void 0, function* () { 33860 return data[1] === 0x00; 33861 }); 33862 } 33863 /** 33864 * Handles Socks v5 auth handshake response. 33865 * @param data 33866 */ 33867 handleInitialSocks5AuthenticationHandshakeResponse() { 33868 return __awaiter(this, void 0, void 0, function* () { 33869 this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse); 33870 let authResult = false; 33871 if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) { 33872 authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)); 33873 } 33874 else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) { 33875 authResult = 33876 yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)); 33877 } 33878 else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) { 33879 authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size)); 33880 } 33881 if (!authResult) { 33882 this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); 33883 } 33884 else { 33885 this.sendSocks5CommandRequest(); 33886 } 33887 }); 33888 } 33889 /** 33890 * Sends Socks v5 final handshake request. 33891 */ 33892 sendSocks5CommandRequest() { 33893 const buff = new smart_buffer_1.SmartBuffer(); 33894 buff.writeUInt8(0x05); 33895 buff.writeUInt8(constants_1.SocksCommand[this.options.command]); 33896 buff.writeUInt8(0x00); 33897 // ipv4, ipv6, domain? 33898 if (net.isIPv4(this.options.destination.host)) { 33899 buff.writeUInt8(constants_1.Socks5HostType.IPv4); 33900 buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); 33901 } 33902 else if (net.isIPv6(this.options.destination.host)) { 33903 buff.writeUInt8(constants_1.Socks5HostType.IPv6); 33904 buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); 33905 } 33906 else { 33907 buff.writeUInt8(constants_1.Socks5HostType.Hostname); 33908 buff.writeUInt8(this.options.destination.host.length); 33909 buff.writeString(this.options.destination.host); 33910 } 33911 buff.writeUInt16BE(this.options.destination.port); 33912 this.nextRequiredPacketBufferSize = 33913 constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; 33914 this.socket.write(buff.toBuffer()); 33915 this.setState(constants_1.SocksClientState.SentFinalHandshake); 33916 } 33917 /** 33918 * Handles Socks v5 final handshake response. 33919 * @param data 33920 */ 33921 handleSocks5FinalHandshakeResponse() { 33922 // Peek at available data (we need at least 5 bytes to get the hostname length) 33923 const header = this.receiveBuffer.peek(5); 33924 if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { 33925 this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); 33926 } 33927 else { 33928 // Read address type 33929 const addressType = header[3]; 33930 let remoteHost; 33931 let buff; 33932 // IPv4 33933 if (addressType === constants_1.Socks5HostType.IPv4) { 33934 // Check if data is available. 33935 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; 33936 if (this.receiveBuffer.length < dataNeeded) { 33937 this.nextRequiredPacketBufferSize = dataNeeded; 33938 return; 33939 } 33940 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); 33941 remoteHost = { 33942 host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), 33943 port: buff.readUInt16BE(), 33944 }; 33945 // If given host is 0.0.0.0, assume remote proxy ip instead. 33946 if (remoteHost.host === '0.0.0.0') { 33947 remoteHost.host = this.options.proxy.ipaddress; 33948 } 33949 // Hostname 33950 } 33951 else if (addressType === constants_1.Socks5HostType.Hostname) { 33952 const hostLength = header[4]; 33953 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port 33954 // Check if data is available. 33955 if (this.receiveBuffer.length < dataNeeded) { 33956 this.nextRequiredPacketBufferSize = dataNeeded; 33957 return; 33958 } 33959 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); 33960 remoteHost = { 33961 host: buff.readString(hostLength), 33962 port: buff.readUInt16BE(), 33963 }; 33964 // IPv6 33965 } 33966 else if (addressType === constants_1.Socks5HostType.IPv6) { 33967 // Check if data is available. 33968 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; 33969 if (this.receiveBuffer.length < dataNeeded) { 33970 this.nextRequiredPacketBufferSize = dataNeeded; 33971 return; 33972 } 33973 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); 33974 remoteHost = { 33975 host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), 33976 port: buff.readUInt16BE(), 33977 }; 33978 } 33979 // We have everything we need 33980 this.setState(constants_1.SocksClientState.ReceivedFinalResponse); 33981 // If using CONNECT, the client is now in the established state. 33982 if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) { 33983 this.setState(constants_1.SocksClientState.Established); 33984 this.removeInternalSocketHandlers(); 33985 this.emit('established', { remoteHost, socket: this.socket }); 33986 } 33987 else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { 33988 /* If using BIND, the Socks client is now in BoundWaitingForConnection state. 33989 This means that the remote proxy server is waiting for a remote connection to the bound port. */ 33990 this.setState(constants_1.SocksClientState.BoundWaitingForConnection); 33991 this.nextRequiredPacketBufferSize = 33992 constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; 33993 this.emit('bound', { remoteHost, socket: this.socket }); 33994 /* 33995 If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the 33996 given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work. 33997 */ 33998 } 33999 else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) { 34000 this.setState(constants_1.SocksClientState.Established); 34001 this.removeInternalSocketHandlers(); 34002 this.emit('established', { 34003 remoteHost, 34004 socket: this.socket, 34005 }); 34006 } 34007 } 34008 } 34009 /** 34010 * Handles Socks v5 incoming connection request (BIND). 34011 */ 34012 handleSocks5IncomingConnectionResponse() { 34013 // Peek at available data (we need at least 5 bytes to get the hostname length) 34014 const header = this.receiveBuffer.peek(5); 34015 if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { 34016 this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); 34017 } 34018 else { 34019 // Read address type 34020 const addressType = header[3]; 34021 let remoteHost; 34022 let buff; 34023 // IPv4 34024 if (addressType === constants_1.Socks5HostType.IPv4) { 34025 // Check if data is available. 34026 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; 34027 if (this.receiveBuffer.length < dataNeeded) { 34028 this.nextRequiredPacketBufferSize = dataNeeded; 34029 return; 34030 } 34031 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); 34032 remoteHost = { 34033 host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), 34034 port: buff.readUInt16BE(), 34035 }; 34036 // If given host is 0.0.0.0, assume remote proxy ip instead. 34037 if (remoteHost.host === '0.0.0.0') { 34038 remoteHost.host = this.options.proxy.ipaddress; 34039 } 34040 // Hostname 34041 } 34042 else if (addressType === constants_1.Socks5HostType.Hostname) { 34043 const hostLength = header[4]; 34044 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port 34045 // Check if data is available. 34046 if (this.receiveBuffer.length < dataNeeded) { 34047 this.nextRequiredPacketBufferSize = dataNeeded; 34048 return; 34049 } 34050 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); 34051 remoteHost = { 34052 host: buff.readString(hostLength), 34053 port: buff.readUInt16BE(), 34054 }; 34055 // IPv6 34056 } 34057 else if (addressType === constants_1.Socks5HostType.IPv6) { 34058 // Check if data is available. 34059 const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; 34060 if (this.receiveBuffer.length < dataNeeded) { 34061 this.nextRequiredPacketBufferSize = dataNeeded; 34062 return; 34063 } 34064 buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); 34065 remoteHost = { 34066 host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), 34067 port: buff.readUInt16BE(), 34068 }; 34069 } 34070 this.setState(constants_1.SocksClientState.Established); 34071 this.removeInternalSocketHandlers(); 34072 this.emit('established', { remoteHost, socket: this.socket }); 34073 } 34074 } 34075 get socksClientOptions() { 34076 return Object.assign({}, this.options); 34077 } 34078 } 34079 exports.SocksClient = SocksClient; 34080 //# sourceMappingURL=socksclient.js.map 34081 34082 /***/ }), 34083 34084 /***/ 9647: 34085 /***/ ((__unused_webpack_module, exports) => { 34086 34087 "use strict"; 34088 34089 Object.defineProperty(exports, "__esModule", ({ value: true })); 34090 exports.SOCKS5_NO_ACCEPTABLE_AUTH = exports.SOCKS5_CUSTOM_AUTH_END = exports.SOCKS5_CUSTOM_AUTH_START = exports.SOCKS_INCOMING_PACKET_SIZES = exports.SocksClientState = exports.Socks5Response = exports.Socks5HostType = exports.Socks5Auth = exports.Socks4Response = exports.SocksCommand = exports.ERRORS = exports.DEFAULT_TIMEOUT = void 0; 34091 const DEFAULT_TIMEOUT = 30000; 34092 exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; 34093 // prettier-ignore 34094 const ERRORS = { 34095 InvalidSocksCommand: 'An invalid SOCKS command was provided. Valid options are connect, bind, and associate.', 34096 InvalidSocksCommandForOperation: 'An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.', 34097 InvalidSocksCommandChain: 'An invalid SOCKS command was provided. Chaining currently only supports the connect command.', 34098 InvalidSocksClientOptionsDestination: 'An invalid destination host was provided.', 34099 InvalidSocksClientOptionsExistingSocket: 'An invalid existing socket was provided. This should be an instance of stream.Duplex.', 34100 InvalidSocksClientOptionsProxy: 'Invalid SOCKS proxy details were provided.', 34101 InvalidSocksClientOptionsTimeout: 'An invalid timeout value was provided. Please enter a value above 0 (in ms).', 34102 InvalidSocksClientOptionsProxiesLength: 'At least two socks proxies must be provided for chaining.', 34103 InvalidSocksClientOptionsCustomAuthRange: 'Custom auth must be a value between 0x80 and 0xFE.', 34104 InvalidSocksClientOptionsCustomAuthOptions: 'When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.', 34105 NegotiationError: 'Negotiation error', 34106 SocketClosed: 'Socket closed', 34107 ProxyConnectionTimedOut: 'Proxy connection timed out', 34108 InternalError: 'SocksClient internal error (this should not happen)', 34109 InvalidSocks4HandshakeResponse: 'Received invalid Socks4 handshake response', 34110 Socks4ProxyRejectedConnection: 'Socks4 Proxy rejected connection', 34111 InvalidSocks4IncomingConnectionResponse: 'Socks4 invalid incoming connection response', 34112 Socks4ProxyRejectedIncomingBoundConnection: 'Socks4 Proxy rejected incoming bound connection', 34113 InvalidSocks5InitialHandshakeResponse: 'Received invalid Socks5 initial handshake response', 34114 InvalidSocks5IntiailHandshakeSocksVersion: 'Received invalid Socks5 initial handshake (invalid socks version)', 34115 InvalidSocks5InitialHandshakeNoAcceptedAuthType: 'Received invalid Socks5 initial handshake (no accepted authentication type)', 34116 InvalidSocks5InitialHandshakeUnknownAuthType: 'Received invalid Socks5 initial handshake (unknown authentication type)', 34117 Socks5AuthenticationFailed: 'Socks5 Authentication failed', 34118 InvalidSocks5FinalHandshake: 'Received invalid Socks5 final handshake response', 34119 InvalidSocks5FinalHandshakeRejected: 'Socks5 proxy rejected connection', 34120 InvalidSocks5IncomingConnectionResponse: 'Received invalid Socks5 incoming connection response', 34121 Socks5ProxyRejectedIncomingBoundConnection: 'Socks5 Proxy rejected incoming bound connection', 34122 }; 34123 exports.ERRORS = ERRORS; 34124 const SOCKS_INCOMING_PACKET_SIZES = { 34125 Socks5InitialHandshakeResponse: 2, 34126 Socks5UserPassAuthenticationResponse: 2, 34127 // Command response + incoming connection (bind) 34128 Socks5ResponseHeader: 5, // We need at least 5 to read the hostname length, then we wait for the address+port information. 34129 Socks5ResponseIPv4: 10, // 4 header + 4 ip + 2 port 34130 Socks5ResponseIPv6: 22, // 4 header + 16 ip + 2 port 34131 Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, // 4 header + 1 host length + host + 2 port 34132 // Command response + incoming connection (bind) 34133 Socks4Response: 8, // 2 header + 2 port + 4 ip 34134 }; 34135 exports.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES; 34136 var SocksCommand; 34137 (function (SocksCommand) { 34138 SocksCommand[SocksCommand["connect"] = 1] = "connect"; 34139 SocksCommand[SocksCommand["bind"] = 2] = "bind"; 34140 SocksCommand[SocksCommand["associate"] = 3] = "associate"; 34141 })(SocksCommand || (exports.SocksCommand = SocksCommand = {})); 34142 var Socks4Response; 34143 (function (Socks4Response) { 34144 Socks4Response[Socks4Response["Granted"] = 90] = "Granted"; 34145 Socks4Response[Socks4Response["Failed"] = 91] = "Failed"; 34146 Socks4Response[Socks4Response["Rejected"] = 92] = "Rejected"; 34147 Socks4Response[Socks4Response["RejectedIdent"] = 93] = "RejectedIdent"; 34148 })(Socks4Response || (exports.Socks4Response = Socks4Response = {})); 34149 var Socks5Auth; 34150 (function (Socks5Auth) { 34151 Socks5Auth[Socks5Auth["NoAuth"] = 0] = "NoAuth"; 34152 Socks5Auth[Socks5Auth["GSSApi"] = 1] = "GSSApi"; 34153 Socks5Auth[Socks5Auth["UserPass"] = 2] = "UserPass"; 34154 })(Socks5Auth || (exports.Socks5Auth = Socks5Auth = {})); 34155 const SOCKS5_CUSTOM_AUTH_START = 0x80; 34156 exports.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START; 34157 const SOCKS5_CUSTOM_AUTH_END = 0xfe; 34158 exports.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END; 34159 const SOCKS5_NO_ACCEPTABLE_AUTH = 0xff; 34160 exports.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH; 34161 var Socks5Response; 34162 (function (Socks5Response) { 34163 Socks5Response[Socks5Response["Granted"] = 0] = "Granted"; 34164 Socks5Response[Socks5Response["Failure"] = 1] = "Failure"; 34165 Socks5Response[Socks5Response["NotAllowed"] = 2] = "NotAllowed"; 34166 Socks5Response[Socks5Response["NetworkUnreachable"] = 3] = "NetworkUnreachable"; 34167 Socks5Response[Socks5Response["HostUnreachable"] = 4] = "HostUnreachable"; 34168 Socks5Response[Socks5Response["ConnectionRefused"] = 5] = "ConnectionRefused"; 34169 Socks5Response[Socks5Response["TTLExpired"] = 6] = "TTLExpired"; 34170 Socks5Response[Socks5Response["CommandNotSupported"] = 7] = "CommandNotSupported"; 34171 Socks5Response[Socks5Response["AddressNotSupported"] = 8] = "AddressNotSupported"; 34172 })(Socks5Response || (exports.Socks5Response = Socks5Response = {})); 34173 var Socks5HostType; 34174 (function (Socks5HostType) { 34175 Socks5HostType[Socks5HostType["IPv4"] = 1] = "IPv4"; 34176 Socks5HostType[Socks5HostType["Hostname"] = 3] = "Hostname"; 34177 Socks5HostType[Socks5HostType["IPv6"] = 4] = "IPv6"; 34178 })(Socks5HostType || (exports.Socks5HostType = Socks5HostType = {})); 34179 var SocksClientState; 34180 (function (SocksClientState) { 34181 SocksClientState[SocksClientState["Created"] = 0] = "Created"; 34182 SocksClientState[SocksClientState["Connecting"] = 1] = "Connecting"; 34183 SocksClientState[SocksClientState["Connected"] = 2] = "Connected"; 34184 SocksClientState[SocksClientState["SentInitialHandshake"] = 3] = "SentInitialHandshake"; 34185 SocksClientState[SocksClientState["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse"; 34186 SocksClientState[SocksClientState["SentAuthentication"] = 5] = "SentAuthentication"; 34187 SocksClientState[SocksClientState["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse"; 34188 SocksClientState[SocksClientState["SentFinalHandshake"] = 7] = "SentFinalHandshake"; 34189 SocksClientState[SocksClientState["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse"; 34190 SocksClientState[SocksClientState["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection"; 34191 SocksClientState[SocksClientState["Established"] = 10] = "Established"; 34192 SocksClientState[SocksClientState["Disconnected"] = 11] = "Disconnected"; 34193 SocksClientState[SocksClientState["Error"] = 99] = "Error"; 34194 })(SocksClientState || (exports.SocksClientState = SocksClientState = {})); 34195 //# sourceMappingURL=constants.js.map 34196 34197 /***/ }), 34198 34199 /***/ 4324: 34200 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 34201 34202 "use strict"; 34203 34204 Object.defineProperty(exports, "__esModule", ({ value: true })); 34205 exports.ipToBuffer = exports.int32ToIpv4 = exports.ipv4ToInt32 = exports.validateSocksClientChainOptions = exports.validateSocksClientOptions = void 0; 34206 const util_1 = __nccwpck_require__(5523); 34207 const constants_1 = __nccwpck_require__(9647); 34208 const stream = __nccwpck_require__(2781); 34209 const ip_address_1 = __nccwpck_require__(8953); 34210 const net = __nccwpck_require__(1808); 34211 /** 34212 * Validates the provided SocksClientOptions 34213 * @param options { SocksClientOptions } 34214 * @param acceptedCommands { string[] } A list of accepted SocksProxy commands. 34215 */ 34216 function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) { 34217 // Check SOCKs command option. 34218 if (!constants_1.SocksCommand[options.command]) { 34219 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options); 34220 } 34221 // Check SocksCommand for acceptable command. 34222 if (acceptedCommands.indexOf(options.command) === -1) { 34223 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options); 34224 } 34225 // Check destination 34226 if (!isValidSocksRemoteHost(options.destination)) { 34227 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); 34228 } 34229 // Check SOCKS proxy to use 34230 if (!isValidSocksProxy(options.proxy)) { 34231 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); 34232 } 34233 // Validate custom auth (if set) 34234 validateCustomProxyAuth(options.proxy, options); 34235 // Check timeout 34236 if (options.timeout && !isValidTimeoutValue(options.timeout)) { 34237 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); 34238 } 34239 // Check existing_socket (if provided) 34240 if (options.existing_socket && 34241 !(options.existing_socket instanceof stream.Duplex)) { 34242 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options); 34243 } 34244 } 34245 exports.validateSocksClientOptions = validateSocksClientOptions; 34246 /** 34247 * Validates the SocksClientChainOptions 34248 * @param options { SocksClientChainOptions } 34249 */ 34250 function validateSocksClientChainOptions(options) { 34251 // Only connect is supported when chaining. 34252 if (options.command !== 'connect') { 34253 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options); 34254 } 34255 // Check destination 34256 if (!isValidSocksRemoteHost(options.destination)) { 34257 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); 34258 } 34259 // Validate proxies (length) 34260 if (!(options.proxies && 34261 Array.isArray(options.proxies) && 34262 options.proxies.length >= 2)) { 34263 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); 34264 } 34265 // Validate proxies 34266 options.proxies.forEach((proxy) => { 34267 if (!isValidSocksProxy(proxy)) { 34268 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); 34269 } 34270 // Validate custom auth (if set) 34271 validateCustomProxyAuth(proxy, options); 34272 }); 34273 // Check timeout 34274 if (options.timeout && !isValidTimeoutValue(options.timeout)) { 34275 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); 34276 } 34277 } 34278 exports.validateSocksClientChainOptions = validateSocksClientChainOptions; 34279 function validateCustomProxyAuth(proxy, options) { 34280 if (proxy.custom_auth_method !== undefined) { 34281 // Invalid auth method range 34282 if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || 34283 proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) { 34284 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options); 34285 } 34286 // Missing custom_auth_request_handler 34287 if (proxy.custom_auth_request_handler === undefined || 34288 typeof proxy.custom_auth_request_handler !== 'function') { 34289 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); 34290 } 34291 // Missing custom_auth_response_size 34292 if (proxy.custom_auth_response_size === undefined) { 34293 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); 34294 } 34295 // Missing/invalid custom_auth_response_handler 34296 if (proxy.custom_auth_response_handler === undefined || 34297 typeof proxy.custom_auth_response_handler !== 'function') { 34298 throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); 34299 } 34300 } 34301 } 34302 /** 34303 * Validates a SocksRemoteHost 34304 * @param remoteHost { SocksRemoteHost } 34305 */ 34306 function isValidSocksRemoteHost(remoteHost) { 34307 return (remoteHost && 34308 typeof remoteHost.host === 'string' && 34309 typeof remoteHost.port === 'number' && 34310 remoteHost.port >= 0 && 34311 remoteHost.port <= 65535); 34312 } 34313 /** 34314 * Validates a SocksProxy 34315 * @param proxy { SocksProxy } 34316 */ 34317 function isValidSocksProxy(proxy) { 34318 return (proxy && 34319 (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') && 34320 typeof proxy.port === 'number' && 34321 proxy.port >= 0 && 34322 proxy.port <= 65535 && 34323 (proxy.type === 4 || proxy.type === 5)); 34324 } 34325 /** 34326 * Validates a timeout value. 34327 * @param value { Number } 34328 */ 34329 function isValidTimeoutValue(value) { 34330 return typeof value === 'number' && value > 0; 34331 } 34332 function ipv4ToInt32(ip) { 34333 const address = new ip_address_1.Address4(ip); 34334 // Convert the IPv4 address parts to an integer 34335 return address.toArray().reduce((acc, part) => (acc << 8) + part, 0); 34336 } 34337 exports.ipv4ToInt32 = ipv4ToInt32; 34338 function int32ToIpv4(int32) { 34339 // Extract each byte (octet) from the 32-bit integer 34340 const octet1 = (int32 >>> 24) & 0xff; 34341 const octet2 = (int32 >>> 16) & 0xff; 34342 const octet3 = (int32 >>> 8) & 0xff; 34343 const octet4 = int32 & 0xff; 34344 // Combine the octets into a string in IPv4 format 34345 return [octet1, octet2, octet3, octet4].join('.'); 34346 } 34347 exports.int32ToIpv4 = int32ToIpv4; 34348 function ipToBuffer(ip) { 34349 if (net.isIPv4(ip)) { 34350 // Handle IPv4 addresses 34351 const address = new ip_address_1.Address4(ip); 34352 return Buffer.from(address.toArray()); 34353 } 34354 else if (net.isIPv6(ip)) { 34355 // Handle IPv6 addresses 34356 const address = new ip_address_1.Address6(ip); 34357 return Buffer.from(address.toByteArray()); 34358 } 34359 else { 34360 throw new Error('Invalid IP address format'); 34361 } 34362 } 34363 exports.ipToBuffer = ipToBuffer; 34364 //# sourceMappingURL=helpers.js.map 34365 34366 /***/ }), 34367 34368 /***/ 9740: 34369 /***/ ((__unused_webpack_module, exports) => { 34370 34371 "use strict"; 34372 34373 Object.defineProperty(exports, "__esModule", ({ value: true })); 34374 exports.ReceiveBuffer = void 0; 34375 class ReceiveBuffer { 34376 constructor(size = 4096) { 34377 this.buffer = Buffer.allocUnsafe(size); 34378 this.offset = 0; 34379 this.originalSize = size; 34380 } 34381 get length() { 34382 return this.offset; 34383 } 34384 append(data) { 34385 if (!Buffer.isBuffer(data)) { 34386 throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.'); 34387 } 34388 if (this.offset + data.length >= this.buffer.length) { 34389 const tmp = this.buffer; 34390 this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length)); 34391 tmp.copy(this.buffer); 34392 } 34393 data.copy(this.buffer, this.offset); 34394 return (this.offset += data.length); 34395 } 34396 peek(length) { 34397 if (length > this.offset) { 34398 throw new Error('Attempted to read beyond the bounds of the managed internal data.'); 34399 } 34400 return this.buffer.slice(0, length); 34401 } 34402 get(length) { 34403 if (length > this.offset) { 34404 throw new Error('Attempted to read beyond the bounds of the managed internal data.'); 34405 } 34406 const value = Buffer.allocUnsafe(length); 34407 this.buffer.slice(0, length).copy(value); 34408 this.buffer.copyWithin(0, length, length + this.offset - length); 34409 this.offset -= length; 34410 return value; 34411 } 34412 } 34413 exports.ReceiveBuffer = ReceiveBuffer; 34414 //# sourceMappingURL=receivebuffer.js.map 34415 34416 /***/ }), 34417 34418 /***/ 5523: 34419 /***/ ((__unused_webpack_module, exports) => { 34420 34421 "use strict"; 34422 34423 Object.defineProperty(exports, "__esModule", ({ value: true })); 34424 exports.shuffleArray = exports.SocksClientError = void 0; 34425 /** 34426 * Error wrapper for SocksClient 34427 */ 34428 class SocksClientError extends Error { 34429 constructor(message, options) { 34430 super(message); 34431 this.options = options; 34432 } 34433 } 34434 exports.SocksClientError = SocksClientError; 34435 /** 34436 * Shuffles a given array. 34437 * @param array The array to shuffle. 34438 */ 34439 function shuffleArray(array) { 34440 for (let i = array.length - 1; i > 0; i--) { 34441 const j = Math.floor(Math.random() * (i + 1)); 34442 [array[i], array[j]] = [array[j], array[i]]; 34443 } 34444 } 34445 exports.shuffleArray = shuffleArray; 34446 //# sourceMappingURL=util.js.map 34447 34448 /***/ }), 34449 34450 /***/ 4754: 34451 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 34452 34453 "use strict"; 34454 34455 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 34456 if (k2 === undefined) k2 = k; 34457 var desc = Object.getOwnPropertyDescriptor(m, k); 34458 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 34459 desc = { enumerable: true, get: function() { return m[k]; } }; 34460 } 34461 Object.defineProperty(o, k2, desc); 34462 }) : (function(o, m, k, k2) { 34463 if (k2 === undefined) k2 = k; 34464 o[k2] = m[k]; 34465 })); 34466 var __exportStar = (this && this.__exportStar) || function(m, exports) { 34467 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); 34468 }; 34469 Object.defineProperty(exports, "__esModule", ({ value: true })); 34470 __exportStar(__nccwpck_require__(6127), exports); 34471 //# sourceMappingURL=index.js.map 34472 34473 /***/ }), 34474 34475 /***/ 3988: 34476 /***/ ((__unused_webpack_module, exports) => { 34477 34478 /* global window, exports, define */ 34479 34480 !function() { 34481 'use strict' 34482 34483 var re = { 34484 not_string: /[^s]/, 34485 not_bool: /[^t]/, 34486 not_type: /[^T]/, 34487 not_primitive: /[^v]/, 34488 number: /[diefg]/, 34489 numeric_arg: /[bcdiefguxX]/, 34490 json: /[j]/, 34491 not_json: /[^j]/, 34492 text: /^[^\x25]+/, 34493 modulo: /^\x25{2}/, 34494 placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, 34495 key: /^([a-z_][a-z_\d]*)/i, 34496 key_access: /^\.([a-z_][a-z_\d]*)/i, 34497 index_access: /^\[(\d+)\]/, 34498 sign: /^[+-]/ 34499 } 34500 34501 function sprintf(key) { 34502 // `arguments` is not an array, but should be fine for this call 34503 return sprintf_format(sprintf_parse(key), arguments) 34504 } 34505 34506 function vsprintf(fmt, argv) { 34507 return sprintf.apply(null, [fmt].concat(argv || [])) 34508 } 34509 34510 function sprintf_format(parse_tree, argv) { 34511 var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign 34512 for (i = 0; i < tree_length; i++) { 34513 if (typeof parse_tree[i] === 'string') { 34514 output += parse_tree[i] 34515 } 34516 else if (typeof parse_tree[i] === 'object') { 34517 ph = parse_tree[i] // convenience purposes only 34518 if (ph.keys) { // keyword argument 34519 arg = argv[cursor] 34520 for (k = 0; k < ph.keys.length; k++) { 34521 if (arg == undefined) { 34522 throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1])) 34523 } 34524 arg = arg[ph.keys[k]] 34525 } 34526 } 34527 else if (ph.param_no) { // positional argument (explicit) 34528 arg = argv[ph.param_no] 34529 } 34530 else { // positional argument (implicit) 34531 arg = argv[cursor++] 34532 } 34533 34534 if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) { 34535 arg = arg() 34536 } 34537 34538 if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) { 34539 throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) 34540 } 34541 34542 if (re.number.test(ph.type)) { 34543 is_positive = arg >= 0 34544 } 34545 34546 switch (ph.type) { 34547 case 'b': 34548 arg = parseInt(arg, 10).toString(2) 34549 break 34550 case 'c': 34551 arg = String.fromCharCode(parseInt(arg, 10)) 34552 break 34553 case 'd': 34554 case 'i': 34555 arg = parseInt(arg, 10) 34556 break 34557 case 'j': 34558 arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0) 34559 break 34560 case 'e': 34561 arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential() 34562 break 34563 case 'f': 34564 arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg) 34565 break 34566 case 'g': 34567 arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg) 34568 break 34569 case 'o': 34570 arg = (parseInt(arg, 10) >>> 0).toString(8) 34571 break 34572 case 's': 34573 arg = String(arg) 34574 arg = (ph.precision ? arg.substring(0, ph.precision) : arg) 34575 break 34576 case 't': 34577 arg = String(!!arg) 34578 arg = (ph.precision ? arg.substring(0, ph.precision) : arg) 34579 break 34580 case 'T': 34581 arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() 34582 arg = (ph.precision ? arg.substring(0, ph.precision) : arg) 34583 break 34584 case 'u': 34585 arg = parseInt(arg, 10) >>> 0 34586 break 34587 case 'v': 34588 arg = arg.valueOf() 34589 arg = (ph.precision ? arg.substring(0, ph.precision) : arg) 34590 break 34591 case 'x': 34592 arg = (parseInt(arg, 10) >>> 0).toString(16) 34593 break 34594 case 'X': 34595 arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() 34596 break 34597 } 34598 if (re.json.test(ph.type)) { 34599 output += arg 34600 } 34601 else { 34602 if (re.number.test(ph.type) && (!is_positive || ph.sign)) { 34603 sign = is_positive ? '+' : '-' 34604 arg = arg.toString().replace(re.sign, '') 34605 } 34606 else { 34607 sign = '' 34608 } 34609 pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ' 34610 pad_length = ph.width - (sign + arg).length 34611 pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' 34612 output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) 34613 } 34614 } 34615 } 34616 return output 34617 } 34618 34619 var sprintf_cache = Object.create(null) 34620 34621 function sprintf_parse(fmt) { 34622 if (sprintf_cache[fmt]) { 34623 return sprintf_cache[fmt] 34624 } 34625 34626 var _fmt = fmt, match, parse_tree = [], arg_names = 0 34627 while (_fmt) { 34628 if ((match = re.text.exec(_fmt)) !== null) { 34629 parse_tree.push(match[0]) 34630 } 34631 else if ((match = re.modulo.exec(_fmt)) !== null) { 34632 parse_tree.push('%') 34633 } 34634 else if ((match = re.placeholder.exec(_fmt)) !== null) { 34635 if (match[2]) { 34636 arg_names |= 1 34637 var field_list = [], replacement_field = match[2], field_match = [] 34638 if ((field_match = re.key.exec(replacement_field)) !== null) { 34639 field_list.push(field_match[1]) 34640 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { 34641 if ((field_match = re.key_access.exec(replacement_field)) !== null) { 34642 field_list.push(field_match[1]) 34643 } 34644 else if ((field_match = re.index_access.exec(replacement_field)) !== null) { 34645 field_list.push(field_match[1]) 34646 } 34647 else { 34648 throw new SyntaxError('[sprintf] failed to parse named argument key') 34649 } 34650 } 34651 } 34652 else { 34653 throw new SyntaxError('[sprintf] failed to parse named argument key') 34654 } 34655 match[2] = field_list 34656 } 34657 else { 34658 arg_names |= 2 34659 } 34660 if (arg_names === 3) { 34661 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') 34662 } 34663 34664 parse_tree.push( 34665 { 34666 placeholder: match[0], 34667 param_no: match[1], 34668 keys: match[2], 34669 sign: match[3], 34670 pad_char: match[4], 34671 align: match[5], 34672 width: match[6], 34673 precision: match[7], 34674 type: match[8] 34675 } 34676 ) 34677 } 34678 else { 34679 throw new SyntaxError('[sprintf] unexpected placeholder') 34680 } 34681 _fmt = _fmt.substring(match[0].length) 34682 } 34683 return sprintf_cache[fmt] = parse_tree 34684 } 34685 34686 /** 34687 * export to either browser or node.js 34688 */ 34689 /* eslint-disable quote-props */ 34690 if (true) { 34691 exports.sprintf = sprintf 34692 exports.vsprintf = vsprintf 34693 } 34694 if (typeof window !== 'undefined') { 34695 window['sprintf'] = sprintf 34696 window['vsprintf'] = vsprintf 34697 34698 if (typeof define === 'function' && define['amd']) { 34699 define(function() { 34700 return { 34701 'sprintf': sprintf, 34702 'vsprintf': vsprintf 34703 } 34704 }) 34705 } 34706 } 34707 /* eslint-enable quote-props */ 34708 }(); // eslint-disable-line 34709 34710 34711 /***/ }), 34712 34713 /***/ 4406: 34714 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 34715 34716 "use strict"; 34717 34718 34719 const crypto = __nccwpck_require__(6113) 34720 const { Minipass } = __nccwpck_require__(4968) 34721 34722 const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'] 34723 const DEFAULT_ALGORITHMS = ['sha512'] 34724 34725 // TODO: this should really be a hardcoded list of algorithms we support, 34726 // rather than [a-z0-9]. 34727 const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i 34728 const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/ 34729 const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/ 34730 const VCHAR_REGEX = /^[\x21-\x7E]+$/ 34731 34732 const getOptString = options => options?.length ? `?${options.join('?')}` : '' 34733 34734 class IntegrityStream extends Minipass { 34735 #emittedIntegrity 34736 #emittedSize 34737 #emittedVerified 34738 34739 constructor (opts) { 34740 super() 34741 this.size = 0 34742 this.opts = opts 34743 34744 // may be overridden later, but set now for class consistency 34745 this.#getOptions() 34746 34747 // options used for calculating stream. can't be changed. 34748 if (opts?.algorithms) { 34749 this.algorithms = [...opts.algorithms] 34750 } else { 34751 this.algorithms = [...DEFAULT_ALGORITHMS] 34752 } 34753 if (this.algorithm !== null && !this.algorithms.includes(this.algorithm)) { 34754 this.algorithms.push(this.algorithm) 34755 } 34756 34757 this.hashes = this.algorithms.map(crypto.createHash) 34758 } 34759 34760 #getOptions () { 34761 // For verification 34762 this.sri = this.opts?.integrity ? parse(this.opts?.integrity, this.opts) : null 34763 this.expectedSize = this.opts?.size 34764 34765 if (!this.sri) { 34766 this.algorithm = null 34767 } else if (this.sri.isHash) { 34768 this.goodSri = true 34769 this.algorithm = this.sri.algorithm 34770 } else { 34771 this.goodSri = !this.sri.isEmpty() 34772 this.algorithm = this.sri.pickAlgorithm(this.opts) 34773 } 34774 34775 this.digests = this.goodSri ? this.sri[this.algorithm] : null 34776 this.optString = getOptString(this.opts?.options) 34777 } 34778 34779 on (ev, handler) { 34780 if (ev === 'size' && this.#emittedSize) { 34781 return handler(this.#emittedSize) 34782 } 34783 34784 if (ev === 'integrity' && this.#emittedIntegrity) { 34785 return handler(this.#emittedIntegrity) 34786 } 34787 34788 if (ev === 'verified' && this.#emittedVerified) { 34789 return handler(this.#emittedVerified) 34790 } 34791 34792 return super.on(ev, handler) 34793 } 34794 34795 emit (ev, data) { 34796 if (ev === 'end') { 34797 this.#onEnd() 34798 } 34799 return super.emit(ev, data) 34800 } 34801 34802 write (data) { 34803 this.size += data.length 34804 this.hashes.forEach(h => h.update(data)) 34805 return super.write(data) 34806 } 34807 34808 #onEnd () { 34809 if (!this.goodSri) { 34810 this.#getOptions() 34811 } 34812 const newSri = parse(this.hashes.map((h, i) => { 34813 return `${this.algorithms[i]}-${h.digest('base64')}${this.optString}` 34814 }).join(' '), this.opts) 34815 // Integrity verification mode 34816 const match = this.goodSri && newSri.match(this.sri, this.opts) 34817 if (typeof this.expectedSize === 'number' && this.size !== this.expectedSize) { 34818 /* eslint-disable-next-line max-len */ 34819 const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.expectedSize}\n Found: ${this.size}`) 34820 err.code = 'EBADSIZE' 34821 err.found = this.size 34822 err.expected = this.expectedSize 34823 err.sri = this.sri 34824 this.emit('error', err) 34825 } else if (this.sri && !match) { 34826 /* eslint-disable-next-line max-len */ 34827 const err = new Error(`${this.sri} integrity checksum failed when using ${this.algorithm}: wanted ${this.digests} but got ${newSri}. (${this.size} bytes)`) 34828 err.code = 'EINTEGRITY' 34829 err.found = newSri 34830 err.expected = this.digests 34831 err.algorithm = this.algorithm 34832 err.sri = this.sri 34833 this.emit('error', err) 34834 } else { 34835 this.#emittedSize = this.size 34836 this.emit('size', this.size) 34837 this.#emittedIntegrity = newSri 34838 this.emit('integrity', newSri) 34839 if (match) { 34840 this.#emittedVerified = match 34841 this.emit('verified', match) 34842 } 34843 } 34844 } 34845 } 34846 34847 class Hash { 34848 get isHash () { 34849 return true 34850 } 34851 34852 constructor (hash, opts) { 34853 const strict = opts?.strict 34854 this.source = hash.trim() 34855 34856 // set default values so that we make V8 happy to 34857 // always see a familiar object template. 34858 this.digest = '' 34859 this.algorithm = '' 34860 this.options = [] 34861 34862 // 3.1. Integrity metadata (called "Hash" by ssri) 34863 // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description 34864 const match = this.source.match( 34865 strict 34866 ? STRICT_SRI_REGEX 34867 : SRI_REGEX 34868 ) 34869 if (!match) { 34870 return 34871 } 34872 if (strict && !SPEC_ALGORITHMS.includes(match[1])) { 34873 return 34874 } 34875 this.algorithm = match[1] 34876 this.digest = match[2] 34877 34878 const rawOpts = match[3] 34879 if (rawOpts) { 34880 this.options = rawOpts.slice(1).split('?') 34881 } 34882 } 34883 34884 hexDigest () { 34885 return this.digest && Buffer.from(this.digest, 'base64').toString('hex') 34886 } 34887 34888 toJSON () { 34889 return this.toString() 34890 } 34891 34892 match (integrity, opts) { 34893 const other = parse(integrity, opts) 34894 if (!other) { 34895 return false 34896 } 34897 if (other.isIntegrity) { 34898 const algo = other.pickAlgorithm(opts, [this.algorithm]) 34899 34900 if (!algo) { 34901 return false 34902 } 34903 34904 const foundHash = other[algo].find(hash => hash.digest === this.digest) 34905 34906 if (foundHash) { 34907 return foundHash 34908 } 34909 34910 return false 34911 } 34912 return other.digest === this.digest ? other : false 34913 } 34914 34915 toString (opts) { 34916 if (opts?.strict) { 34917 // Strict mode enforces the standard as close to the foot of the 34918 // letter as it can. 34919 if (!( 34920 // The spec has very restricted productions for algorithms. 34921 // https://www.w3.org/TR/CSP2/#source-list-syntax 34922 SPEC_ALGORITHMS.includes(this.algorithm) && 34923 // Usually, if someone insists on using a "different" base64, we 34924 // leave it as-is, since there's multiple standards, and the 34925 // specified is not a URL-safe variant. 34926 // https://www.w3.org/TR/CSP2/#base64_value 34927 this.digest.match(BASE64_REGEX) && 34928 // Option syntax is strictly visual chars. 34929 // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression 34930 // https://tools.ietf.org/html/rfc5234#appendix-B.1 34931 this.options.every(opt => opt.match(VCHAR_REGEX)) 34932 )) { 34933 return '' 34934 } 34935 } 34936 return `${this.algorithm}-${this.digest}${getOptString(this.options)}` 34937 } 34938 } 34939 34940 function integrityHashToString (toString, sep, opts, hashes) { 34941 const toStringIsNotEmpty = toString !== '' 34942 34943 let shouldAddFirstSep = false 34944 let complement = '' 34945 34946 const lastIndex = hashes.length - 1 34947 34948 for (let i = 0; i < lastIndex; i++) { 34949 const hashString = Hash.prototype.toString.call(hashes[i], opts) 34950 34951 if (hashString) { 34952 shouldAddFirstSep = true 34953 34954 complement += hashString 34955 complement += sep 34956 } 34957 } 34958 34959 const finalHashString = Hash.prototype.toString.call(hashes[lastIndex], opts) 34960 34961 if (finalHashString) { 34962 shouldAddFirstSep = true 34963 complement += finalHashString 34964 } 34965 34966 if (toStringIsNotEmpty && shouldAddFirstSep) { 34967 return toString + sep + complement 34968 } 34969 34970 return toString + complement 34971 } 34972 34973 class Integrity { 34974 get isIntegrity () { 34975 return true 34976 } 34977 34978 toJSON () { 34979 return this.toString() 34980 } 34981 34982 isEmpty () { 34983 return Object.keys(this).length === 0 34984 } 34985 34986 toString (opts) { 34987 let sep = opts?.sep || ' ' 34988 let toString = '' 34989 34990 if (opts?.strict) { 34991 // Entries must be separated by whitespace, according to spec. 34992 sep = sep.replace(/\S+/g, ' ') 34993 34994 for (const hash of SPEC_ALGORITHMS) { 34995 if (this[hash]) { 34996 toString = integrityHashToString(toString, sep, opts, this[hash]) 34997 } 34998 } 34999 } else { 35000 for (const hash of Object.keys(this)) { 35001 toString = integrityHashToString(toString, sep, opts, this[hash]) 35002 } 35003 } 35004 35005 return toString 35006 } 35007 35008 concat (integrity, opts) { 35009 const other = typeof integrity === 'string' 35010 ? integrity 35011 : stringify(integrity, opts) 35012 return parse(`${this.toString(opts)} ${other}`, opts) 35013 } 35014 35015 hexDigest () { 35016 return parse(this, { single: true }).hexDigest() 35017 } 35018 35019 // add additional hashes to an integrity value, but prevent 35020 // *changing* an existing integrity hash. 35021 merge (integrity, opts) { 35022 const other = parse(integrity, opts) 35023 for (const algo in other) { 35024 if (this[algo]) { 35025 if (!this[algo].find(hash => 35026 other[algo].find(otherhash => 35027 hash.digest === otherhash.digest))) { 35028 throw new Error('hashes do not match, cannot update integrity') 35029 } 35030 } else { 35031 this[algo] = other[algo] 35032 } 35033 } 35034 } 35035 35036 match (integrity, opts) { 35037 const other = parse(integrity, opts) 35038 if (!other) { 35039 return false 35040 } 35041 const algo = other.pickAlgorithm(opts, Object.keys(this)) 35042 return ( 35043 !!algo && 35044 this[algo] && 35045 other[algo] && 35046 this[algo].find(hash => 35047 other[algo].find(otherhash => 35048 hash.digest === otherhash.digest 35049 ) 35050 ) 35051 ) || false 35052 } 35053 35054 // Pick the highest priority algorithm present, optionally also limited to a 35055 // set of hashes found in another integrity. When limiting it may return 35056 // nothing. 35057 pickAlgorithm (opts, hashes) { 35058 const pickAlgorithm = opts?.pickAlgorithm || getPrioritizedHash 35059 const keys = Object.keys(this).filter(k => { 35060 if (hashes?.length) { 35061 return hashes.includes(k) 35062 } 35063 return true 35064 }) 35065 if (keys.length) { 35066 return keys.reduce((acc, algo) => pickAlgorithm(acc, algo) || acc) 35067 } 35068 // no intersection between this and hashes, 35069 return null 35070 } 35071 } 35072 35073 module.exports.parse = parse 35074 function parse (sri, opts) { 35075 if (!sri) { 35076 return null 35077 } 35078 if (typeof sri === 'string') { 35079 return _parse(sri, opts) 35080 } else if (sri.algorithm && sri.digest) { 35081 const fullSri = new Integrity() 35082 fullSri[sri.algorithm] = [sri] 35083 return _parse(stringify(fullSri, opts), opts) 35084 } else { 35085 return _parse(stringify(sri, opts), opts) 35086 } 35087 } 35088 35089 function _parse (integrity, opts) { 35090 // 3.4.3. Parse metadata 35091 // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata 35092 if (opts?.single) { 35093 return new Hash(integrity, opts) 35094 } 35095 const hashes = integrity.trim().split(/\s+/).reduce((acc, string) => { 35096 const hash = new Hash(string, opts) 35097 if (hash.algorithm && hash.digest) { 35098 const algo = hash.algorithm 35099 if (!acc[algo]) { 35100 acc[algo] = [] 35101 } 35102 acc[algo].push(hash) 35103 } 35104 return acc 35105 }, new Integrity()) 35106 return hashes.isEmpty() ? null : hashes 35107 } 35108 35109 module.exports.stringify = stringify 35110 function stringify (obj, opts) { 35111 if (obj.algorithm && obj.digest) { 35112 return Hash.prototype.toString.call(obj, opts) 35113 } else if (typeof obj === 'string') { 35114 return stringify(parse(obj, opts), opts) 35115 } else { 35116 return Integrity.prototype.toString.call(obj, opts) 35117 } 35118 } 35119 35120 module.exports.fromHex = fromHex 35121 function fromHex (hexDigest, algorithm, opts) { 35122 const optString = getOptString(opts?.options) 35123 return parse( 35124 `${algorithm}-${ 35125 Buffer.from(hexDigest, 'hex').toString('base64') 35126 }${optString}`, opts 35127 ) 35128 } 35129 35130 module.exports.fromData = fromData 35131 function fromData (data, opts) { 35132 const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] 35133 const optString = getOptString(opts?.options) 35134 return algorithms.reduce((acc, algo) => { 35135 const digest = crypto.createHash(algo).update(data).digest('base64') 35136 const hash = new Hash( 35137 `${algo}-${digest}${optString}`, 35138 opts 35139 ) 35140 /* istanbul ignore else - it would be VERY strange if the string we 35141 * just calculated with an algo did not have an algo or digest. 35142 */ 35143 if (hash.algorithm && hash.digest) { 35144 const hashAlgo = hash.algorithm 35145 if (!acc[hashAlgo]) { 35146 acc[hashAlgo] = [] 35147 } 35148 acc[hashAlgo].push(hash) 35149 } 35150 return acc 35151 }, new Integrity()) 35152 } 35153 35154 module.exports.fromStream = fromStream 35155 function fromStream (stream, opts) { 35156 const istream = integrityStream(opts) 35157 return new Promise((resolve, reject) => { 35158 stream.pipe(istream) 35159 stream.on('error', reject) 35160 istream.on('error', reject) 35161 let sri 35162 istream.on('integrity', s => { 35163 sri = s 35164 }) 35165 istream.on('end', () => resolve(sri)) 35166 istream.resume() 35167 }) 35168 } 35169 35170 module.exports.checkData = checkData 35171 function checkData (data, sri, opts) { 35172 sri = parse(sri, opts) 35173 if (!sri || !Object.keys(sri).length) { 35174 if (opts?.error) { 35175 throw Object.assign( 35176 new Error('No valid integrity hashes to check against'), { 35177 code: 'EINTEGRITY', 35178 } 35179 ) 35180 } else { 35181 return false 35182 } 35183 } 35184 const algorithm = sri.pickAlgorithm(opts) 35185 const digest = crypto.createHash(algorithm).update(data).digest('base64') 35186 const newSri = parse({ algorithm, digest }) 35187 const match = newSri.match(sri, opts) 35188 opts = opts || {} 35189 if (match || !(opts.error)) { 35190 return match 35191 } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { 35192 /* eslint-disable-next-line max-len */ 35193 const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) 35194 err.code = 'EBADSIZE' 35195 err.found = data.length 35196 err.expected = opts.size 35197 err.sri = sri 35198 throw err 35199 } else { 35200 /* eslint-disable-next-line max-len */ 35201 const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) 35202 err.code = 'EINTEGRITY' 35203 err.found = newSri 35204 err.expected = sri 35205 err.algorithm = algorithm 35206 err.sri = sri 35207 throw err 35208 } 35209 } 35210 35211 module.exports.checkStream = checkStream 35212 function checkStream (stream, sri, opts) { 35213 opts = opts || Object.create(null) 35214 opts.integrity = sri 35215 sri = parse(sri, opts) 35216 if (!sri || !Object.keys(sri).length) { 35217 return Promise.reject(Object.assign( 35218 new Error('No valid integrity hashes to check against'), { 35219 code: 'EINTEGRITY', 35220 } 35221 )) 35222 } 35223 const checker = integrityStream(opts) 35224 return new Promise((resolve, reject) => { 35225 stream.pipe(checker) 35226 stream.on('error', reject) 35227 checker.on('error', reject) 35228 let verified 35229 checker.on('verified', s => { 35230 verified = s 35231 }) 35232 checker.on('end', () => resolve(verified)) 35233 checker.resume() 35234 }) 35235 } 35236 35237 module.exports.integrityStream = integrityStream 35238 function integrityStream (opts = Object.create(null)) { 35239 return new IntegrityStream(opts) 35240 } 35241 35242 module.exports.create = createIntegrity 35243 function createIntegrity (opts) { 35244 const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] 35245 const optString = getOptString(opts?.options) 35246 35247 const hashes = algorithms.map(crypto.createHash) 35248 35249 return { 35250 update: function (chunk, enc) { 35251 hashes.forEach(h => h.update(chunk, enc)) 35252 return this 35253 }, 35254 digest: function (enc) { 35255 const integrity = algorithms.reduce((acc, algo) => { 35256 const digest = hashes.shift().digest('base64') 35257 const hash = new Hash( 35258 `${algo}-${digest}${optString}`, 35259 opts 35260 ) 35261 /* istanbul ignore else - it would be VERY strange if the hash we 35262 * just calculated with an algo did not have an algo or digest. 35263 */ 35264 if (hash.algorithm && hash.digest) { 35265 const hashAlgo = hash.algorithm 35266 if (!acc[hashAlgo]) { 35267 acc[hashAlgo] = [] 35268 } 35269 acc[hashAlgo].push(hash) 35270 } 35271 return acc 35272 }, new Integrity()) 35273 35274 return integrity 35275 }, 35276 } 35277 } 35278 35279 const NODE_HASHES = crypto.getHashes() 35280 35281 // This is a Best Effort™ at a reasonable priority for hash algos 35282 const DEFAULT_PRIORITY = [ 35283 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', 35284 // TODO - it's unclear _which_ of these Node will actually use as its name 35285 // for the algorithm, so we guesswork it based on the OpenSSL names. 35286 'sha3', 35287 'sha3-256', 'sha3-384', 'sha3-512', 35288 'sha3_256', 'sha3_384', 'sha3_512', 35289 ].filter(algo => NODE_HASHES.includes(algo)) 35290 35291 function getPrioritizedHash (algo1, algo2) { 35292 /* eslint-disable-next-line max-len */ 35293 return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) 35294 ? algo1 35295 : algo2 35296 } 35297 35298 35299 /***/ }), 35300 35301 /***/ 9318: 35302 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 35303 35304 "use strict"; 35305 35306 const os = __nccwpck_require__(2037); 35307 const tty = __nccwpck_require__(6224); 35308 const hasFlag = __nccwpck_require__(1621); 35309 35310 const {env} = process; 35311 35312 let forceColor; 35313 if (hasFlag('no-color') || 35314 hasFlag('no-colors') || 35315 hasFlag('color=false') || 35316 hasFlag('color=never')) { 35317 forceColor = 0; 35318 } else if (hasFlag('color') || 35319 hasFlag('colors') || 35320 hasFlag('color=true') || 35321 hasFlag('color=always')) { 35322 forceColor = 1; 35323 } 35324 35325 if ('FORCE_COLOR' in env) { 35326 if (env.FORCE_COLOR === 'true') { 35327 forceColor = 1; 35328 } else if (env.FORCE_COLOR === 'false') { 35329 forceColor = 0; 35330 } else { 35331 forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); 35332 } 35333 } 35334 35335 function translateLevel(level) { 35336 if (level === 0) { 35337 return false; 35338 } 35339 35340 return { 35341 level, 35342 hasBasic: true, 35343 has256: level >= 2, 35344 has16m: level >= 3 35345 }; 35346 } 35347 35348 function supportsColor(haveStream, streamIsTTY) { 35349 if (forceColor === 0) { 35350 return 0; 35351 } 35352 35353 if (hasFlag('color=16m') || 35354 hasFlag('color=full') || 35355 hasFlag('color=truecolor')) { 35356 return 3; 35357 } 35358 35359 if (hasFlag('color=256')) { 35360 return 2; 35361 } 35362 35363 if (haveStream && !streamIsTTY && forceColor === undefined) { 35364 return 0; 35365 } 35366 35367 const min = forceColor || 0; 35368 35369 if (env.TERM === 'dumb') { 35370 return min; 35371 } 35372 35373 if (process.platform === 'win32') { 35374 // Windows 10 build 10586 is the first Windows release that supports 256 colors. 35375 // Windows 10 build 14931 is the first release that supports 16m/TrueColor. 35376 const osRelease = os.release().split('.'); 35377 if ( 35378 Number(osRelease[0]) >= 10 && 35379 Number(osRelease[2]) >= 10586 35380 ) { 35381 return Number(osRelease[2]) >= 14931 ? 3 : 2; 35382 } 35383 35384 return 1; 35385 } 35386 35387 if ('CI' in env) { 35388 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { 35389 return 1; 35390 } 35391 35392 return min; 35393 } 35394 35395 if ('TEAMCITY_VERSION' in env) { 35396 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; 35397 } 35398 35399 if (env.COLORTERM === 'truecolor') { 35400 return 3; 35401 } 35402 35403 if ('TERM_PROGRAM' in env) { 35404 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); 35405 35406 switch (env.TERM_PROGRAM) { 35407 case 'iTerm.app': 35408 return version >= 3 ? 3 : 2; 35409 case 'Apple_Terminal': 35410 return 2; 35411 // No default 35412 } 35413 } 35414 35415 if (/-256(color)?$/i.test(env.TERM)) { 35416 return 2; 35417 } 35418 35419 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { 35420 return 1; 35421 } 35422 35423 if ('COLORTERM' in env) { 35424 return 1; 35425 } 35426 35427 return min; 35428 } 35429 35430 function getSupportLevel(stream) { 35431 const level = supportsColor(stream, stream && stream.isTTY); 35432 return translateLevel(level); 35433 } 35434 35435 module.exports = { 35436 supportsColor: getSupportLevel, 35437 stdout: translateLevel(supportsColor(true, tty.isatty(1))), 35438 stderr: translateLevel(supportsColor(true, tty.isatty(2))) 35439 }; 35440 35441 35442 /***/ }), 35443 35444 /***/ 6484: 35445 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 35446 35447 "use strict"; 35448 35449 // Copyright 2023 SLSA Authors 35450 // 35451 // Licensed under the Apache License, Version 2.0 (the "License"); 35452 // you may not use this file except in compliance with the License. 35453 // You may obtain a copy of the License at 35454 // 35455 // http://www.apache.org/licenses/LICENSE-2.0 35456 // 35457 // Unless required by applicable law or agreed to in writing, software 35458 // distributed under the License is distributed on an "AS IS" BASIS, 35459 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35460 // See the License for the specific language governing permissions and 35461 // limitations under the License. 35462 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 35463 if (k2 === undefined) k2 = k; 35464 var desc = Object.getOwnPropertyDescriptor(m, k); 35465 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 35466 desc = { enumerable: true, get: function() { return m[k]; } }; 35467 } 35468 Object.defineProperty(o, k2, desc); 35469 }) : (function(o, m, k, k2) { 35470 if (k2 === undefined) k2 = k; 35471 o[k2] = m[k]; 35472 })); 35473 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 35474 Object.defineProperty(o, "default", { enumerable: true, value: v }); 35475 }) : function(o, v) { 35476 o["default"] = v; 35477 }); 35478 var __importStar = (this && this.__importStar) || function (mod) { 35479 if (mod && mod.__esModule) return mod; 35480 var result = {}; 35481 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 35482 __setModuleDefault(result, mod); 35483 return result; 35484 }; 35485 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 35486 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 35487 return new (P || (P = Promise))(function (resolve, reject) { 35488 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 35489 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 35490 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 35491 step((generator = generator.apply(thisArg, _arguments || [])).next()); 35492 }); 35493 }; 35494 var __importDefault = (this && this.__importDefault) || function (mod) { 35495 return (mod && mod.__esModule) ? mod : { "default": mod }; 35496 }; 35497 Object.defineProperty(exports, "__esModule", ({ value: true })); 35498 exports.safePromises_stat = exports.safePromises_readdir = exports.safeExistsSync = exports.safeRmdirSync = exports.safeUnlinkSync = exports.safeReadFileSync = exports.safeMkdirSync = exports.safeWriteFileSync = exports.resolvePathInput = exports.safeFileSha256 = exports.getGitHubWorkspace = void 0; 35499 const crypto = __importStar(__nccwpck_require__(6113)); 35500 const fs_1 = __importDefault(__nccwpck_require__(7147)); 35501 const path_1 = __importDefault(__nccwpck_require__(1017)); 35502 const process_1 = __importDefault(__nccwpck_require__(7282)); 35503 // This function is for unit tests. 35504 // We need to set the working directory to the tscommon/ directory 35505 // instead of the GITHUB_WORKSPACE. 35506 function getGitHubWorkspace() { 35507 const wdt = process_1.default.env.UNIT_TESTS_WD || ""; 35508 if (wdt) { 35509 return wdt; 35510 } 35511 return process_1.default.env.GITHUB_WORKSPACE || ""; 35512 } 35513 exports.getGitHubWorkspace = getGitHubWorkspace; 35514 // safeFileSha256 returns the hex-formatted sha256 sum of the contents of an 35515 // untrusted file path. 35516 function safeFileSha256(untrustedPath) { 35517 const untrustedFile = safeReadFileSync(untrustedPath); 35518 return crypto.createHash("sha256").update(untrustedFile).digest("hex"); 35519 } 35520 exports.safeFileSha256 = safeFileSha256; 35521 // Detect directory traversal for input file. 35522 // This function is exported for unit tests only. 35523 function resolvePathInput(input, write) { 35524 const wd = getGitHubWorkspace(); 35525 const resolvedInput = path_1.default.resolve(input); 35526 // Allowed files for read only. 35527 const allowedReadFiles = [process_1.default.env.GITHUB_EVENT_PATH || ""]; 35528 for (const allowedReadFile of allowedReadFiles) { 35529 if (allowedReadFile === resolvedInput) { 35530 if (write) { 35531 throw Error(`unsafe write path ${resolvedInput}`); 35532 } 35533 return resolvedInput; 35534 } 35535 } 35536 // Allowed directories for read and write. 35537 const allowedDirs = [wd, "/tmp", process_1.default.env.RUNNER_TEMP || ""]; 35538 for (const allowedDir of allowedDirs) { 35539 // NOTE: we call 'resolve' to normalize the directory name. 35540 const resolvedAllowedDir = path_1.default.resolve(allowedDir); 35541 if ((resolvedInput + path_1.default.sep).startsWith(resolvedAllowedDir + path_1.default.sep)) { 35542 return resolvedInput; 35543 } 35544 } 35545 throw Error(`unsafe path ${resolvedInput}`); 35546 } 35547 exports.resolvePathInput = resolvePathInput; 35548 // Safe write function. 35549 function safeWriteFileSync(outputFn, data) { 35550 const safeOutputFn = resolvePathInput(outputFn, true); 35551 // WARNING: if the call fails, the type of the error is not 'Error'. 35552 fs_1.default.writeFileSync(safeOutputFn, data, { 35553 flag: "wx", 35554 mode: 0o600, 35555 }); 35556 } 35557 exports.safeWriteFileSync = safeWriteFileSync; 35558 // Safe mkdir function. 35559 function safeMkdirSync(outputFn, options) { 35560 const safeOutputFn = resolvePathInput(outputFn, true); 35561 fs_1.default.mkdirSync(safeOutputFn, options); 35562 } 35563 exports.safeMkdirSync = safeMkdirSync; 35564 // Safe read file function. 35565 function safeReadFileSync(inputFn) { 35566 const safeInputFn = resolvePathInput(inputFn, false); 35567 return fs_1.default.readFileSync(safeInputFn); 35568 } 35569 exports.safeReadFileSync = safeReadFileSync; 35570 // Safe unlink function. 35571 function safeUnlinkSync(inputFn) { 35572 const safeInputFn = resolvePathInput(inputFn, true); 35573 return fs_1.default.unlinkSync(safeInputFn); 35574 } 35575 exports.safeUnlinkSync = safeUnlinkSync; 35576 // Safe remove directory function. 35577 function safeRmdirSync(dir, options) { 35578 const safeDir = resolvePathInput(dir, true); 35579 return fs_1.default.rmdirSync(safeDir, options); 35580 } 35581 exports.safeRmdirSync = safeRmdirSync; 35582 // Safe exist function. 35583 function safeExistsSync(inputFn) { 35584 const safeInputFn = resolvePathInput(inputFn, false); 35585 return fs_1.default.existsSync(safeInputFn); 35586 } 35587 exports.safeExistsSync = safeExistsSync; 35588 // Safe readdir function. 35589 function safePromises_readdir(inputFn) { 35590 return __awaiter(this, void 0, void 0, function* () { 35591 const safeInputFn = resolvePathInput(inputFn, false); 35592 return fs_1.default.promises.readdir(safeInputFn); 35593 }); 35594 } 35595 exports.safePromises_readdir = safePromises_readdir; 35596 // Safe stat function. 35597 function safePromises_stat(inputFn) { 35598 return __awaiter(this, void 0, void 0, function* () { 35599 const safeInputFn = resolvePathInput(inputFn, true); 35600 return fs_1.default.promises.stat(safeInputFn); 35601 }); 35602 } 35603 exports.safePromises_stat = safePromises_stat; 35604 35605 35606 /***/ }), 35607 35608 /***/ 6634: 35609 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 35610 35611 "use strict"; 35612 35613 // Copyright 2023 SLSA Authors 35614 // 35615 // Licensed under the Apache License, Version 2.0 (the "License"); 35616 // you may not use this file except in compliance with the License. 35617 // You may obtain a copy of the License at 35618 // 35619 // http://www.apache.org/licenses/LICENSE-2.0 35620 // 35621 // Unless required by applicable law or agreed to in writing, software 35622 // distributed under the License is distributed on an "AS IS" BASIS, 35623 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35624 // See the License for the specific language governing permissions and 35625 // limitations under the License. 35626 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 35627 if (k2 === undefined) k2 = k; 35628 var desc = Object.getOwnPropertyDescriptor(m, k); 35629 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 35630 desc = { enumerable: true, get: function() { return m[k]; } }; 35631 } 35632 Object.defineProperty(o, k2, desc); 35633 }) : (function(o, m, k, k2) { 35634 if (k2 === undefined) k2 = k; 35635 o[k2] = m[k]; 35636 })); 35637 var __exportStar = (this && this.__exportStar) || function(m, exports) { 35638 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); 35639 }; 35640 Object.defineProperty(exports, "__esModule", ({ value: true })); 35641 __exportStar(__nccwpck_require__(6484), exports); 35642 35643 35644 /***/ }), 35645 35646 /***/ 9530: 35647 /***/ ((__unused_webpack_module, exports) => { 35648 35649 "use strict"; 35650 35651 Object.defineProperty(exports, "__esModule", ({ value: true })); 35652 exports.defaultConfig = void 0; 35653 exports.defaultConfig = { 35654 maxRootRotations: 32, 35655 maxDelegations: 32, 35656 rootMaxLength: 512000, //bytes 35657 timestampMaxLength: 16384, // bytes 35658 snapshotMaxLength: 2000000, // bytes 35659 targetsMaxLength: 5000000, // bytes 35660 prefixTargetsWithHash: true, 35661 fetchTimeout: 100000, // milliseconds 35662 fetchRetries: undefined, 35663 fetchRetry: 2, 35664 }; 35665 35666 35667 /***/ }), 35668 35669 /***/ 7040: 35670 /***/ ((__unused_webpack_module, exports) => { 35671 35672 "use strict"; 35673 35674 Object.defineProperty(exports, "__esModule", ({ value: true })); 35675 exports.DownloadHTTPError = exports.DownloadLengthMismatchError = exports.DownloadError = exports.ExpiredMetadataError = exports.EqualVersionError = exports.BadVersionError = exports.RepositoryError = exports.PersistError = exports.RuntimeError = exports.ValueError = void 0; 35676 // An error about insufficient values 35677 class ValueError extends Error { 35678 } 35679 exports.ValueError = ValueError; 35680 class RuntimeError extends Error { 35681 } 35682 exports.RuntimeError = RuntimeError; 35683 class PersistError extends Error { 35684 } 35685 exports.PersistError = PersistError; 35686 // An error with a repository's state, such as a missing file. 35687 // It covers all exceptions that come from the repository side when 35688 // looking from the perspective of users of metadata API or ngclient. 35689 class RepositoryError extends Error { 35690 } 35691 exports.RepositoryError = RepositoryError; 35692 // An error for metadata that contains an invalid version number. 35693 class BadVersionError extends RepositoryError { 35694 } 35695 exports.BadVersionError = BadVersionError; 35696 // An error for metadata containing a previously verified version number. 35697 class EqualVersionError extends BadVersionError { 35698 } 35699 exports.EqualVersionError = EqualVersionError; 35700 // Indicate that a TUF Metadata file has expired. 35701 class ExpiredMetadataError extends RepositoryError { 35702 } 35703 exports.ExpiredMetadataError = ExpiredMetadataError; 35704 //----- Download Errors ------------------------------------------------------- 35705 // An error occurred while attempting to download a file. 35706 class DownloadError extends Error { 35707 } 35708 exports.DownloadError = DownloadError; 35709 // Indicate that a mismatch of lengths was seen while downloading a file 35710 class DownloadLengthMismatchError extends DownloadError { 35711 } 35712 exports.DownloadLengthMismatchError = DownloadLengthMismatchError; 35713 // Returned by FetcherInterface implementations for HTTP errors. 35714 class DownloadHTTPError extends DownloadError { 35715 constructor(message, statusCode) { 35716 super(message); 35717 this.statusCode = statusCode; 35718 } 35719 } 35720 exports.DownloadHTTPError = DownloadHTTPError; 35721 35722 35723 /***/ }), 35724 35725 /***/ 5991: 35726 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 35727 35728 "use strict"; 35729 35730 var __importDefault = (this && this.__importDefault) || function (mod) { 35731 return (mod && mod.__esModule) ? mod : { "default": mod }; 35732 }; 35733 Object.defineProperty(exports, "__esModule", ({ value: true })); 35734 exports.DefaultFetcher = exports.BaseFetcher = void 0; 35735 const debug_1 = __importDefault(__nccwpck_require__(8237)); 35736 const fs_1 = __importDefault(__nccwpck_require__(7147)); 35737 const make_fetch_happen_1 = __importDefault(__nccwpck_require__(9525)); 35738 const util_1 = __importDefault(__nccwpck_require__(3837)); 35739 const error_1 = __nccwpck_require__(7040); 35740 const tmpfile_1 = __nccwpck_require__(6400); 35741 const log = (0, debug_1.default)('tuf:fetch'); 35742 class BaseFetcher { 35743 // Download file from given URL. The file is downloaded to a temporary 35744 // location and then passed to the given handler. The handler is responsible 35745 // for moving the file to its final location. The temporary file is deleted 35746 // after the handler returns. 35747 async downloadFile(url, maxLength, handler) { 35748 return (0, tmpfile_1.withTempFile)(async (tmpFile) => { 35749 const reader = await this.fetch(url); 35750 let numberOfBytesReceived = 0; 35751 const fileStream = fs_1.default.createWriteStream(tmpFile); 35752 // Read the stream a chunk at a time so that we can check 35753 // the length of the file as we go 35754 try { 35755 for await (const chunk of reader) { 35756 const bufferChunk = Buffer.from(chunk); 35757 numberOfBytesReceived += bufferChunk.length; 35758 if (numberOfBytesReceived > maxLength) { 35759 throw new error_1.DownloadLengthMismatchError('Max length reached'); 35760 } 35761 await writeBufferToStream(fileStream, bufferChunk); 35762 } 35763 } 35764 finally { 35765 // Make sure we always close the stream 35766 await util_1.default.promisify(fileStream.close).bind(fileStream)(); 35767 } 35768 return handler(tmpFile); 35769 }); 35770 } 35771 // Download bytes from given URL. 35772 async downloadBytes(url, maxLength) { 35773 return this.downloadFile(url, maxLength, async (file) => { 35774 const stream = fs_1.default.createReadStream(file); 35775 const chunks = []; 35776 for await (const chunk of stream) { 35777 chunks.push(chunk); 35778 } 35779 return Buffer.concat(chunks); 35780 }); 35781 } 35782 } 35783 exports.BaseFetcher = BaseFetcher; 35784 class DefaultFetcher extends BaseFetcher { 35785 constructor(options = {}) { 35786 super(); 35787 this.timeout = options.timeout; 35788 this.retry = options.retry; 35789 } 35790 async fetch(url) { 35791 log('GET %s', url); 35792 const response = await (0, make_fetch_happen_1.default)(url, { 35793 timeout: this.timeout, 35794 retry: this.retry, 35795 }); 35796 if (!response.ok || !response?.body) { 35797 throw new error_1.DownloadHTTPError('Failed to download', response.status); 35798 } 35799 return response.body; 35800 } 35801 } 35802 exports.DefaultFetcher = DefaultFetcher; 35803 const writeBufferToStream = async (stream, buffer) => { 35804 return new Promise((resolve, reject) => { 35805 stream.write(buffer, (err) => { 35806 if (err) { 35807 reject(err); 35808 } 35809 resolve(true); 35810 }); 35811 }); 35812 }; 35813 35814 35815 /***/ }), 35816 35817 /***/ 9475: 35818 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 35819 35820 "use strict"; 35821 35822 Object.defineProperty(exports, "__esModule", ({ value: true })); 35823 exports.Updater = exports.BaseFetcher = exports.TargetFile = void 0; 35824 var models_1 = __nccwpck_require__(5833); 35825 Object.defineProperty(exports, "TargetFile", ({ enumerable: true, get: function () { return models_1.TargetFile; } })); 35826 var fetcher_1 = __nccwpck_require__(5991); 35827 Object.defineProperty(exports, "BaseFetcher", ({ enumerable: true, get: function () { return fetcher_1.BaseFetcher; } })); 35828 var updater_1 = __nccwpck_require__(7977); 35829 Object.defineProperty(exports, "Updater", ({ enumerable: true, get: function () { return updater_1.Updater; } })); 35830 35831 35832 /***/ }), 35833 35834 /***/ 7001: 35835 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 35836 35837 "use strict"; 35838 35839 Object.defineProperty(exports, "__esModule", ({ value: true })); 35840 exports.TrustedMetadataStore = void 0; 35841 const models_1 = __nccwpck_require__(5833); 35842 const error_1 = __nccwpck_require__(7040); 35843 class TrustedMetadataStore { 35844 constructor(rootData) { 35845 this.trustedSet = {}; 35846 // Client workflow 5.1: record fixed update start time 35847 this.referenceTime = new Date(); 35848 // Client workflow 5.2: load trusted root metadata 35849 this.loadTrustedRoot(rootData); 35850 } 35851 get root() { 35852 if (!this.trustedSet.root) { 35853 throw new ReferenceError('No trusted root metadata'); 35854 } 35855 return this.trustedSet.root; 35856 } 35857 get timestamp() { 35858 return this.trustedSet.timestamp; 35859 } 35860 get snapshot() { 35861 return this.trustedSet.snapshot; 35862 } 35863 get targets() { 35864 return this.trustedSet.targets; 35865 } 35866 getRole(name) { 35867 return this.trustedSet[name]; 35868 } 35869 updateRoot(bytesBuffer) { 35870 const data = JSON.parse(bytesBuffer.toString('utf8')); 35871 const newRoot = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data); 35872 if (newRoot.signed.type != models_1.MetadataKind.Root) { 35873 throw new error_1.RepositoryError(`Expected 'root', got ${newRoot.signed.type}`); 35874 } 35875 // Client workflow 5.4: check for arbitrary software attack 35876 this.root.verifyDelegate(models_1.MetadataKind.Root, newRoot); 35877 // Client workflow 5.5: check for rollback attack 35878 if (newRoot.signed.version != this.root.signed.version + 1) { 35879 throw new error_1.BadVersionError(`Expected version ${this.root.signed.version + 1}, got ${newRoot.signed.version}`); 35880 } 35881 // Check that new root is signed by self 35882 newRoot.verifyDelegate(models_1.MetadataKind.Root, newRoot); 35883 // Client workflow 5.7: set new root as trusted root 35884 this.trustedSet.root = newRoot; 35885 return newRoot; 35886 } 35887 updateTimestamp(bytesBuffer) { 35888 if (this.snapshot) { 35889 throw new error_1.RuntimeError('Cannot update timestamp after snapshot'); 35890 } 35891 if (this.root.signed.isExpired(this.referenceTime)) { 35892 throw new error_1.ExpiredMetadataError('Final root.json is expired'); 35893 } 35894 const data = JSON.parse(bytesBuffer.toString('utf8')); 35895 const newTimestamp = models_1.Metadata.fromJSON(models_1.MetadataKind.Timestamp, data); 35896 if (newTimestamp.signed.type != models_1.MetadataKind.Timestamp) { 35897 throw new error_1.RepositoryError(`Expected 'timestamp', got ${newTimestamp.signed.type}`); 35898 } 35899 // Client workflow 5.4.2: check for arbitrary software attack 35900 this.root.verifyDelegate(models_1.MetadataKind.Timestamp, newTimestamp); 35901 if (this.timestamp) { 35902 // Prevent rolling back timestamp version 35903 // Client workflow 5.4.3.1: check for rollback attack 35904 if (newTimestamp.signed.version < this.timestamp.signed.version) { 35905 throw new error_1.BadVersionError(`New timestamp version ${newTimestamp.signed.version} is less than current version ${this.timestamp.signed.version}`); 35906 } 35907 // Keep using old timestamp if versions are equal. 35908 if (newTimestamp.signed.version === this.timestamp.signed.version) { 35909 throw new error_1.EqualVersionError(`New timestamp version ${newTimestamp.signed.version} is equal to current version ${this.timestamp.signed.version}`); 35910 } 35911 // Prevent rolling back snapshot version 35912 // Client workflow 5.4.3.2: check for rollback attack 35913 const snapshotMeta = this.timestamp.signed.snapshotMeta; 35914 const newSnapshotMeta = newTimestamp.signed.snapshotMeta; 35915 if (newSnapshotMeta.version < snapshotMeta.version) { 35916 throw new error_1.BadVersionError(`New snapshot version ${newSnapshotMeta.version} is less than current version ${snapshotMeta.version}`); 35917 } 35918 } 35919 // expiry not checked to allow old timestamp to be used for rollback 35920 // protection of new timestamp: expiry is checked in update_snapshot 35921 this.trustedSet.timestamp = newTimestamp; 35922 // Client workflow 5.4.4: check for freeze attack 35923 this.checkFinalTimestamp(); 35924 return newTimestamp; 35925 } 35926 updateSnapshot(bytesBuffer, trusted = false) { 35927 if (!this.timestamp) { 35928 throw new error_1.RuntimeError('Cannot update snapshot before timestamp'); 35929 } 35930 if (this.targets) { 35931 throw new error_1.RuntimeError('Cannot update snapshot after targets'); 35932 } 35933 // Snapshot cannot be loaded if final timestamp is expired 35934 this.checkFinalTimestamp(); 35935 const snapshotMeta = this.timestamp.signed.snapshotMeta; 35936 // Verify non-trusted data against the hashes in timestamp, if any. 35937 // Trusted snapshot data has already been verified once. 35938 // Client workflow 5.5.2: check against timestamp role's snaphsot hash 35939 if (!trusted) { 35940 snapshotMeta.verify(bytesBuffer); 35941 } 35942 const data = JSON.parse(bytesBuffer.toString('utf8')); 35943 const newSnapshot = models_1.Metadata.fromJSON(models_1.MetadataKind.Snapshot, data); 35944 if (newSnapshot.signed.type != models_1.MetadataKind.Snapshot) { 35945 throw new error_1.RepositoryError(`Expected 'snapshot', got ${newSnapshot.signed.type}`); 35946 } 35947 // Client workflow 5.5.3: check for arbitrary software attack 35948 this.root.verifyDelegate(models_1.MetadataKind.Snapshot, newSnapshot); 35949 // version check against meta version (5.5.4) is deferred to allow old 35950 // snapshot to be used in rollback protection 35951 // Client workflow 5.5.5: check for rollback attack 35952 if (this.snapshot) { 35953 Object.entries(this.snapshot.signed.meta).forEach(([fileName, fileInfo]) => { 35954 const newFileInfo = newSnapshot.signed.meta[fileName]; 35955 if (!newFileInfo) { 35956 throw new error_1.RepositoryError(`Missing file ${fileName} in new snapshot`); 35957 } 35958 if (newFileInfo.version < fileInfo.version) { 35959 throw new error_1.BadVersionError(`New version ${newFileInfo.version} of ${fileName} is less than current version ${fileInfo.version}`); 35960 } 35961 }); 35962 } 35963 this.trustedSet.snapshot = newSnapshot; 35964 // snapshot is loaded, but we raise if it's not valid _final_ snapshot 35965 // Client workflow 5.5.4 & 5.5.6 35966 this.checkFinalSnapsnot(); 35967 return newSnapshot; 35968 } 35969 updateDelegatedTargets(bytesBuffer, roleName, delegatorName) { 35970 if (!this.snapshot) { 35971 throw new error_1.RuntimeError('Cannot update delegated targets before snapshot'); 35972 } 35973 // Targets cannot be loaded if final snapshot is expired or its version 35974 // does not match meta version in timestamp. 35975 this.checkFinalSnapsnot(); 35976 const delegator = this.trustedSet[delegatorName]; 35977 if (!delegator) { 35978 throw new error_1.RuntimeError(`No trusted ${delegatorName} metadata`); 35979 } 35980 // Extract metadata for the delegated role from snapshot 35981 const meta = this.snapshot.signed.meta?.[`${roleName}.json`]; 35982 if (!meta) { 35983 throw new error_1.RepositoryError(`Missing ${roleName}.json in snapshot`); 35984 } 35985 // Client workflow 5.6.2: check against snapshot role's targets hash 35986 meta.verify(bytesBuffer); 35987 const data = JSON.parse(bytesBuffer.toString('utf8')); 35988 const newDelegate = models_1.Metadata.fromJSON(models_1.MetadataKind.Targets, data); 35989 if (newDelegate.signed.type != models_1.MetadataKind.Targets) { 35990 throw new error_1.RepositoryError(`Expected 'targets', got ${newDelegate.signed.type}`); 35991 } 35992 // Client workflow 5.6.3: check for arbitrary software attack 35993 delegator.verifyDelegate(roleName, newDelegate); 35994 // Client workflow 5.6.4: Check against snapshot role’s targets version 35995 const version = newDelegate.signed.version; 35996 if (version != meta.version) { 35997 throw new error_1.BadVersionError(`Version ${version} of ${roleName} does not match snapshot version ${meta.version}`); 35998 } 35999 // Client workflow 5.6.5: check for a freeze attack 36000 if (newDelegate.signed.isExpired(this.referenceTime)) { 36001 throw new error_1.ExpiredMetadataError(`${roleName}.json is expired`); 36002 } 36003 this.trustedSet[roleName] = newDelegate; 36004 } 36005 // Verifies and loads data as trusted root metadata. 36006 // Note that an expired initial root is still considered valid. 36007 loadTrustedRoot(bytesBuffer) { 36008 const data = JSON.parse(bytesBuffer.toString('utf8')); 36009 const root = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data); 36010 if (root.signed.type != models_1.MetadataKind.Root) { 36011 throw new error_1.RepositoryError(`Expected 'root', got ${root.signed.type}`); 36012 } 36013 root.verifyDelegate(models_1.MetadataKind.Root, root); 36014 this.trustedSet['root'] = root; 36015 } 36016 checkFinalTimestamp() { 36017 // Timestamp MUST be loaded 36018 if (!this.timestamp) { 36019 throw new ReferenceError('No trusted timestamp metadata'); 36020 } 36021 // Client workflow 5.4.4: check for freeze attack 36022 if (this.timestamp.signed.isExpired(this.referenceTime)) { 36023 throw new error_1.ExpiredMetadataError('Final timestamp.json is expired'); 36024 } 36025 } 36026 checkFinalSnapsnot() { 36027 // Snapshot and timestamp MUST be loaded 36028 if (!this.snapshot) { 36029 throw new ReferenceError('No trusted snapshot metadata'); 36030 } 36031 if (!this.timestamp) { 36032 throw new ReferenceError('No trusted timestamp metadata'); 36033 } 36034 // Client workflow 5.5.6: check for freeze attack 36035 if (this.snapshot.signed.isExpired(this.referenceTime)) { 36036 throw new error_1.ExpiredMetadataError('snapshot.json is expired'); 36037 } 36038 // Client workflow 5.5.4: check against timestamp role’s snapshot version 36039 const snapshotMeta = this.timestamp.signed.snapshotMeta; 36040 if (this.snapshot.signed.version !== snapshotMeta.version) { 36041 throw new error_1.BadVersionError("Snapshot version doesn't match timestamp"); 36042 } 36043 } 36044 } 36045 exports.TrustedMetadataStore = TrustedMetadataStore; 36046 36047 36048 /***/ }), 36049 36050 /***/ 7977: 36051 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 36052 36053 "use strict"; 36054 36055 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 36056 if (k2 === undefined) k2 = k; 36057 var desc = Object.getOwnPropertyDescriptor(m, k); 36058 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 36059 desc = { enumerable: true, get: function() { return m[k]; } }; 36060 } 36061 Object.defineProperty(o, k2, desc); 36062 }) : (function(o, m, k, k2) { 36063 if (k2 === undefined) k2 = k; 36064 o[k2] = m[k]; 36065 })); 36066 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 36067 Object.defineProperty(o, "default", { enumerable: true, value: v }); 36068 }) : function(o, v) { 36069 o["default"] = v; 36070 }); 36071 var __importStar = (this && this.__importStar) || function (mod) { 36072 if (mod && mod.__esModule) return mod; 36073 var result = {}; 36074 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 36075 __setModuleDefault(result, mod); 36076 return result; 36077 }; 36078 var __importDefault = (this && this.__importDefault) || function (mod) { 36079 return (mod && mod.__esModule) ? mod : { "default": mod }; 36080 }; 36081 Object.defineProperty(exports, "__esModule", ({ value: true })); 36082 exports.Updater = void 0; 36083 const models_1 = __nccwpck_require__(5833); 36084 const debug_1 = __importDefault(__nccwpck_require__(8237)); 36085 const fs = __importStar(__nccwpck_require__(7147)); 36086 const path = __importStar(__nccwpck_require__(1017)); 36087 const config_1 = __nccwpck_require__(9530); 36088 const error_1 = __nccwpck_require__(7040); 36089 const fetcher_1 = __nccwpck_require__(5991); 36090 const store_1 = __nccwpck_require__(7001); 36091 const url = __importStar(__nccwpck_require__(5961)); 36092 const log = (0, debug_1.default)('tuf:cache'); 36093 class Updater { 36094 constructor(options) { 36095 const { metadataDir, metadataBaseUrl, targetDir, targetBaseUrl, fetcher, config, } = options; 36096 this.dir = metadataDir; 36097 this.metadataBaseUrl = metadataBaseUrl; 36098 this.targetDir = targetDir; 36099 this.targetBaseUrl = targetBaseUrl; 36100 this.forceCache = options.forceCache ?? false; 36101 const data = this.loadLocalMetadata(models_1.MetadataKind.Root); 36102 this.trustedSet = new store_1.TrustedMetadataStore(data); 36103 this.config = { ...config_1.defaultConfig, ...config }; 36104 this.fetcher = 36105 fetcher || 36106 new fetcher_1.DefaultFetcher({ 36107 timeout: this.config.fetchTimeout, 36108 retry: this.config.fetchRetries ?? this.config.fetchRetry, 36109 }); 36110 } 36111 // refresh and load the metadata before downloading the target 36112 // refresh should be called once after the client is initialized 36113 async refresh() { 36114 // If forceCache is true, try to load the timestamp from local storage 36115 // without fetching it from the remote. Otherwise, load the root and 36116 // timestamp from the remote per the TUF spec. 36117 if (this.forceCache) { 36118 // If anything fails, load the root and timestamp from the remote. This 36119 // should cover any situation where the local metadata is corrupted or 36120 // expired. 36121 try { 36122 await this.loadTimestamp({ checkRemote: false }); 36123 } 36124 catch (error) { 36125 await this.loadRoot(); 36126 await this.loadTimestamp(); 36127 } 36128 } 36129 else { 36130 await this.loadRoot(); 36131 await this.loadTimestamp(); 36132 } 36133 await this.loadSnapshot(); 36134 await this.loadTargets(models_1.MetadataKind.Targets, models_1.MetadataKind.Root); 36135 } 36136 // Returns the TargetFile instance with information for the given target path. 36137 // 36138 // Implicitly calls refresh if it hasn't already been called. 36139 async getTargetInfo(targetPath) { 36140 if (!this.trustedSet.targets) { 36141 await this.refresh(); 36142 } 36143 return this.preorderDepthFirstWalk(targetPath); 36144 } 36145 async downloadTarget(targetInfo, filePath, targetBaseUrl) { 36146 const targetPath = filePath || this.generateTargetPath(targetInfo); 36147 if (!targetBaseUrl) { 36148 if (!this.targetBaseUrl) { 36149 throw new error_1.ValueError('Target base URL not set'); 36150 } 36151 targetBaseUrl = this.targetBaseUrl; 36152 } 36153 let targetFilePath = targetInfo.path; 36154 const consistentSnapshot = this.trustedSet.root.signed.consistentSnapshot; 36155 if (consistentSnapshot && this.config.prefixTargetsWithHash) { 36156 const hashes = Object.values(targetInfo.hashes); 36157 const { dir, base } = path.parse(targetFilePath); 36158 const filename = `${hashes[0]}.${base}`; 36159 targetFilePath = dir ? `${dir}/${filename}` : filename; 36160 } 36161 const targetUrl = url.join(targetBaseUrl, targetFilePath); 36162 // Client workflow 5.7.3: download target file 36163 await this.fetcher.downloadFile(targetUrl, targetInfo.length, async (fileName) => { 36164 // Verify hashes and length of downloaded file 36165 await targetInfo.verify(fs.createReadStream(fileName)); 36166 // Copy file to target path 36167 log('WRITE %s', targetPath); 36168 fs.copyFileSync(fileName, targetPath); 36169 }); 36170 return targetPath; 36171 } 36172 async findCachedTarget(targetInfo, filePath) { 36173 if (!filePath) { 36174 filePath = this.generateTargetPath(targetInfo); 36175 } 36176 try { 36177 if (fs.existsSync(filePath)) { 36178 await targetInfo.verify(fs.createReadStream(filePath)); 36179 return filePath; 36180 } 36181 } 36182 catch (error) { 36183 return; // File not found 36184 } 36185 return; // File not found 36186 } 36187 loadLocalMetadata(fileName) { 36188 const filePath = path.join(this.dir, `${fileName}.json`); 36189 log('READ %s', filePath); 36190 return fs.readFileSync(filePath); 36191 } 36192 // Sequentially load and persist on local disk every newer root metadata 36193 // version available on the remote. 36194 // Client workflow 5.3: update root role 36195 async loadRoot() { 36196 // Client workflow 5.3.2: version of trusted root metadata file 36197 const rootVersion = this.trustedSet.root.signed.version; 36198 const lowerBound = rootVersion + 1; 36199 const upperBound = lowerBound + this.config.maxRootRotations; 36200 for (let version = lowerBound; version <= upperBound; version++) { 36201 const rootUrl = url.join(this.metadataBaseUrl, `${version}.root.json`); 36202 try { 36203 // Client workflow 5.3.3: download new root metadata file 36204 const bytesData = await this.fetcher.downloadBytes(rootUrl, this.config.rootMaxLength); 36205 // Client workflow 5.3.4 - 5.4.7 36206 this.trustedSet.updateRoot(bytesData); 36207 // Client workflow 5.3.8: persist root metadata file 36208 this.persistMetadata(models_1.MetadataKind.Root, bytesData); 36209 } 36210 catch (error) { 36211 break; 36212 } 36213 } 36214 } 36215 // Load local and remote timestamp metadata. 36216 // Client workflow 5.4: update timestamp role 36217 async loadTimestamp({ checkRemote } = { checkRemote: true }) { 36218 // Load local and remote timestamp metadata 36219 try { 36220 const data = this.loadLocalMetadata(models_1.MetadataKind.Timestamp); 36221 this.trustedSet.updateTimestamp(data); 36222 // If checkRemote is disabled, return here to avoid fetching the remote 36223 // timestamp metadata. 36224 if (!checkRemote) { 36225 return; 36226 } 36227 } 36228 catch (error) { 36229 // continue 36230 } 36231 //Load from remote (whether local load succeeded or not) 36232 const timestampUrl = url.join(this.metadataBaseUrl, 'timestamp.json'); 36233 // Client workflow 5.4.1: download timestamp metadata file 36234 const bytesData = await this.fetcher.downloadBytes(timestampUrl, this.config.timestampMaxLength); 36235 try { 36236 // Client workflow 5.4.2 - 5.4.4 36237 this.trustedSet.updateTimestamp(bytesData); 36238 } 36239 catch (error) { 36240 // If new timestamp version is same as current, discardd the new one. 36241 // This is normal and should NOT raise an error. 36242 if (error instanceof error_1.EqualVersionError) { 36243 return; 36244 } 36245 // Re-raise any other error 36246 throw error; 36247 } 36248 // Client workflow 5.4.5: persist timestamp metadata 36249 this.persistMetadata(models_1.MetadataKind.Timestamp, bytesData); 36250 } 36251 // Load local and remote snapshot metadata. 36252 // Client workflow 5.5: update snapshot role 36253 async loadSnapshot() { 36254 //Load local (and if needed remote) snapshot metadata 36255 try { 36256 const data = this.loadLocalMetadata(models_1.MetadataKind.Snapshot); 36257 this.trustedSet.updateSnapshot(data, true); 36258 } 36259 catch (error) { 36260 if (!this.trustedSet.timestamp) { 36261 throw new ReferenceError('No timestamp metadata'); 36262 } 36263 const snapshotMeta = this.trustedSet.timestamp.signed.snapshotMeta; 36264 const maxLength = snapshotMeta.length || this.config.snapshotMaxLength; 36265 const version = this.trustedSet.root.signed.consistentSnapshot 36266 ? snapshotMeta.version 36267 : undefined; 36268 const snapshotUrl = url.join(this.metadataBaseUrl, version ? `${version}.snapshot.json` : 'snapshot.json'); 36269 try { 36270 // Client workflow 5.5.1: download snapshot metadata file 36271 const bytesData = await this.fetcher.downloadBytes(snapshotUrl, maxLength); 36272 // Client workflow 5.5.2 - 5.5.6 36273 this.trustedSet.updateSnapshot(bytesData); 36274 // Client workflow 5.5.7: persist snapshot metadata file 36275 this.persistMetadata(models_1.MetadataKind.Snapshot, bytesData); 36276 } 36277 catch (error) { 36278 throw new error_1.RuntimeError(`Unable to load snapshot metadata error ${error}`); 36279 } 36280 } 36281 } 36282 // Load local and remote targets metadata. 36283 // Client workflow 5.6: update targets role 36284 async loadTargets(role, parentRole) { 36285 if (this.trustedSet.getRole(role)) { 36286 return this.trustedSet.getRole(role); 36287 } 36288 try { 36289 const buffer = this.loadLocalMetadata(role); 36290 this.trustedSet.updateDelegatedTargets(buffer, role, parentRole); 36291 } 36292 catch (error) { 36293 // Local 'role' does not exist or is invalid: update from remote 36294 if (!this.trustedSet.snapshot) { 36295 throw new ReferenceError('No snapshot metadata'); 36296 } 36297 const metaInfo = this.trustedSet.snapshot.signed.meta[`${role}.json`]; 36298 // TODO: use length for fetching 36299 const maxLength = metaInfo.length || this.config.targetsMaxLength; 36300 const version = this.trustedSet.root.signed.consistentSnapshot 36301 ? metaInfo.version 36302 : undefined; 36303 const metadataUrl = url.join(this.metadataBaseUrl, version ? `${version}.${role}.json` : `${role}.json`); 36304 try { 36305 // Client workflow 5.6.1: download targets metadata file 36306 const bytesData = await this.fetcher.downloadBytes(metadataUrl, maxLength); 36307 // Client workflow 5.6.2 - 5.6.6 36308 this.trustedSet.updateDelegatedTargets(bytesData, role, parentRole); 36309 // Client workflow 5.6.7: persist targets metadata file 36310 this.persistMetadata(role, bytesData); 36311 } 36312 catch (error) { 36313 throw new error_1.RuntimeError(`Unable to load targets error ${error}`); 36314 } 36315 } 36316 return this.trustedSet.getRole(role); 36317 } 36318 async preorderDepthFirstWalk(targetPath) { 36319 // Interrogates the tree of target delegations in order of appearance 36320 // (which implicitly order trustworthiness), and returns the matching 36321 // target found in the most trusted role. 36322 // List of delegations to be interrogated. A (role, parent role) pair 36323 // is needed to load and verify the delegated targets metadata. 36324 const delegationsToVisit = [ 36325 { 36326 roleName: models_1.MetadataKind.Targets, 36327 parentRoleName: models_1.MetadataKind.Root, 36328 }, 36329 ]; 36330 const visitedRoleNames = new Set(); 36331 // Client workflow 5.6.7: preorder depth-first traversal of the graph of 36332 // target delegations 36333 while (visitedRoleNames.size <= this.config.maxDelegations && 36334 delegationsToVisit.length > 0) { 36335 // Pop the role name from the top of the stack. 36336 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 36337 const { roleName, parentRoleName } = delegationsToVisit.pop(); 36338 // Skip any visited current role to prevent cycles. 36339 // Client workflow 5.6.7.1: skip already-visited roles 36340 if (visitedRoleNames.has(roleName)) { 36341 continue; 36342 } 36343 // The metadata for 'role_name' must be downloaded/updated before 36344 // its targets, delegations, and child roles can be inspected. 36345 const targets = (await this.loadTargets(roleName, parentRoleName)) 36346 ?.signed; 36347 if (!targets) { 36348 continue; 36349 } 36350 const target = targets.targets?.[targetPath]; 36351 if (target) { 36352 return target; 36353 } 36354 // After preorder check, add current role to set of visited roles. 36355 visitedRoleNames.add(roleName); 36356 if (targets.delegations) { 36357 const childRolesToVisit = []; 36358 // NOTE: This may be a slow operation if there are many delegated roles. 36359 const rolesForTarget = targets.delegations.rolesForTarget(targetPath); 36360 for (const { role: childName, terminating } of rolesForTarget) { 36361 childRolesToVisit.push({ 36362 roleName: childName, 36363 parentRoleName: roleName, 36364 }); 36365 // Client workflow 5.6.7.2.1 36366 if (terminating) { 36367 delegationsToVisit.splice(0); // empty the array 36368 break; 36369 } 36370 } 36371 childRolesToVisit.reverse(); 36372 delegationsToVisit.push(...childRolesToVisit); 36373 } 36374 } 36375 return; // no matching target found 36376 } 36377 generateTargetPath(targetInfo) { 36378 if (!this.targetDir) { 36379 throw new error_1.ValueError('Target directory not set'); 36380 } 36381 // URL encode target path 36382 const filePath = encodeURIComponent(targetInfo.path); 36383 return path.join(this.targetDir, filePath); 36384 } 36385 persistMetadata(metaDataName, bytesData) { 36386 try { 36387 const filePath = path.join(this.dir, `${metaDataName}.json`); 36388 log('WRITE %s', filePath); 36389 fs.writeFileSync(filePath, bytesData.toString('utf8')); 36390 } 36391 catch (error) { 36392 throw new error_1.PersistError(`Failed to persist metadata ${metaDataName} error: ${error}`); 36393 } 36394 } 36395 } 36396 exports.Updater = Updater; 36397 36398 36399 /***/ }), 36400 36401 /***/ 6400: 36402 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 36403 36404 "use strict"; 36405 36406 var __importDefault = (this && this.__importDefault) || function (mod) { 36407 return (mod && mod.__esModule) ? mod : { "default": mod }; 36408 }; 36409 Object.defineProperty(exports, "__esModule", ({ value: true })); 36410 exports.withTempFile = void 0; 36411 const promises_1 = __importDefault(__nccwpck_require__(3292)); 36412 const os_1 = __importDefault(__nccwpck_require__(2037)); 36413 const path_1 = __importDefault(__nccwpck_require__(1017)); 36414 // Invokes the given handler with the path to a temporary file. The file 36415 // is deleted after the handler returns. 36416 const withTempFile = async (handler) => withTempDir(async (dir) => handler(path_1.default.join(dir, 'tempfile'))); 36417 exports.withTempFile = withTempFile; 36418 // Invokes the given handler with a temporary directory. The directory is 36419 // deleted after the handler returns. 36420 const withTempDir = async (handler) => { 36421 const tmpDir = await promises_1.default.realpath(os_1.default.tmpdir()); 36422 const dir = await promises_1.default.mkdtemp(tmpDir + path_1.default.sep); 36423 try { 36424 return await handler(dir); 36425 } 36426 finally { 36427 await promises_1.default.rm(dir, { force: true, recursive: true, maxRetries: 3 }); 36428 } 36429 }; 36430 36431 36432 /***/ }), 36433 36434 /***/ 5961: 36435 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 36436 36437 "use strict"; 36438 36439 Object.defineProperty(exports, "__esModule", ({ value: true })); 36440 exports.join = void 0; 36441 const url_1 = __nccwpck_require__(7310); 36442 function join(base, path) { 36443 return new url_1.URL(ensureTrailingSlash(base) + removeLeadingSlash(path)).toString(); 36444 } 36445 exports.join = join; 36446 function ensureTrailingSlash(path) { 36447 return path.endsWith('/') ? path : path + '/'; 36448 } 36449 function removeLeadingSlash(path) { 36450 return path.startsWith('/') ? path.slice(1) : path; 36451 } 36452 36453 36454 /***/ }), 36455 36456 /***/ 4294: 36457 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 36458 36459 module.exports = __nccwpck_require__(4219); 36460 36461 36462 /***/ }), 36463 36464 /***/ 4219: 36465 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 36466 36467 "use strict"; 36468 36469 36470 var net = __nccwpck_require__(1808); 36471 var tls = __nccwpck_require__(4404); 36472 var http = __nccwpck_require__(3685); 36473 var https = __nccwpck_require__(5687); 36474 var events = __nccwpck_require__(2361); 36475 var assert = __nccwpck_require__(9491); 36476 var util = __nccwpck_require__(3837); 36477 36478 36479 exports.httpOverHttp = httpOverHttp; 36480 exports.httpsOverHttp = httpsOverHttp; 36481 exports.httpOverHttps = httpOverHttps; 36482 exports.httpsOverHttps = httpsOverHttps; 36483 36484 36485 function httpOverHttp(options) { 36486 var agent = new TunnelingAgent(options); 36487 agent.request = http.request; 36488 return agent; 36489 } 36490 36491 function httpsOverHttp(options) { 36492 var agent = new TunnelingAgent(options); 36493 agent.request = http.request; 36494 agent.createSocket = createSecureSocket; 36495 agent.defaultPort = 443; 36496 return agent; 36497 } 36498 36499 function httpOverHttps(options) { 36500 var agent = new TunnelingAgent(options); 36501 agent.request = https.request; 36502 return agent; 36503 } 36504 36505 function httpsOverHttps(options) { 36506 var agent = new TunnelingAgent(options); 36507 agent.request = https.request; 36508 agent.createSocket = createSecureSocket; 36509 agent.defaultPort = 443; 36510 return agent; 36511 } 36512 36513 36514 function TunnelingAgent(options) { 36515 var self = this; 36516 self.options = options || {}; 36517 self.proxyOptions = self.options.proxy || {}; 36518 self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; 36519 self.requests = []; 36520 self.sockets = []; 36521 36522 self.on('free', function onFree(socket, host, port, localAddress) { 36523 var options = toOptions(host, port, localAddress); 36524 for (var i = 0, len = self.requests.length; i < len; ++i) { 36525 var pending = self.requests[i]; 36526 if (pending.host === options.host && pending.port === options.port) { 36527 // Detect the request to connect same origin server, 36528 // reuse the connection. 36529 self.requests.splice(i, 1); 36530 pending.request.onSocket(socket); 36531 return; 36532 } 36533 } 36534 socket.destroy(); 36535 self.removeSocket(socket); 36536 }); 36537 } 36538 util.inherits(TunnelingAgent, events.EventEmitter); 36539 36540 TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { 36541 var self = this; 36542 var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); 36543 36544 if (self.sockets.length >= this.maxSockets) { 36545 // We are over limit so we'll add it to the queue. 36546 self.requests.push(options); 36547 return; 36548 } 36549 36550 // If we are under maxSockets create a new one. 36551 self.createSocket(options, function(socket) { 36552 socket.on('free', onFree); 36553 socket.on('close', onCloseOrRemove); 36554 socket.on('agentRemove', onCloseOrRemove); 36555 req.onSocket(socket); 36556 36557 function onFree() { 36558 self.emit('free', socket, options); 36559 } 36560 36561 function onCloseOrRemove(err) { 36562 self.removeSocket(socket); 36563 socket.removeListener('free', onFree); 36564 socket.removeListener('close', onCloseOrRemove); 36565 socket.removeListener('agentRemove', onCloseOrRemove); 36566 } 36567 }); 36568 }; 36569 36570 TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { 36571 var self = this; 36572 var placeholder = {}; 36573 self.sockets.push(placeholder); 36574 36575 var connectOptions = mergeOptions({}, self.proxyOptions, { 36576 method: 'CONNECT', 36577 path: options.host + ':' + options.port, 36578 agent: false, 36579 headers: { 36580 host: options.host + ':' + options.port 36581 } 36582 }); 36583 if (options.localAddress) { 36584 connectOptions.localAddress = options.localAddress; 36585 } 36586 if (connectOptions.proxyAuth) { 36587 connectOptions.headers = connectOptions.headers || {}; 36588 connectOptions.headers['Proxy-Authorization'] = 'Basic ' + 36589 new Buffer(connectOptions.proxyAuth).toString('base64'); 36590 } 36591 36592 debug('making CONNECT request'); 36593 var connectReq = self.request(connectOptions); 36594 connectReq.useChunkedEncodingByDefault = false; // for v0.6 36595 connectReq.once('response', onResponse); // for v0.6 36596 connectReq.once('upgrade', onUpgrade); // for v0.6 36597 connectReq.once('connect', onConnect); // for v0.7 or later 36598 connectReq.once('error', onError); 36599 connectReq.end(); 36600 36601 function onResponse(res) { 36602 // Very hacky. This is necessary to avoid http-parser leaks. 36603 res.upgrade = true; 36604 } 36605 36606 function onUpgrade(res, socket, head) { 36607 // Hacky. 36608 process.nextTick(function() { 36609 onConnect(res, socket, head); 36610 }); 36611 } 36612 36613 function onConnect(res, socket, head) { 36614 connectReq.removeAllListeners(); 36615 socket.removeAllListeners(); 36616 36617 if (res.statusCode !== 200) { 36618 debug('tunneling socket could not be established, statusCode=%d', 36619 res.statusCode); 36620 socket.destroy(); 36621 var error = new Error('tunneling socket could not be established, ' + 36622 'statusCode=' + res.statusCode); 36623 error.code = 'ECONNRESET'; 36624 options.request.emit('error', error); 36625 self.removeSocket(placeholder); 36626 return; 36627 } 36628 if (head.length > 0) { 36629 debug('got illegal response body from proxy'); 36630 socket.destroy(); 36631 var error = new Error('got illegal response body from proxy'); 36632 error.code = 'ECONNRESET'; 36633 options.request.emit('error', error); 36634 self.removeSocket(placeholder); 36635 return; 36636 } 36637 debug('tunneling connection has established'); 36638 self.sockets[self.sockets.indexOf(placeholder)] = socket; 36639 return cb(socket); 36640 } 36641 36642 function onError(cause) { 36643 connectReq.removeAllListeners(); 36644 36645 debug('tunneling socket could not be established, cause=%s\n', 36646 cause.message, cause.stack); 36647 var error = new Error('tunneling socket could not be established, ' + 36648 'cause=' + cause.message); 36649 error.code = 'ECONNRESET'; 36650 options.request.emit('error', error); 36651 self.removeSocket(placeholder); 36652 } 36653 }; 36654 36655 TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { 36656 var pos = this.sockets.indexOf(socket) 36657 if (pos === -1) { 36658 return; 36659 } 36660 this.sockets.splice(pos, 1); 36661 36662 var pending = this.requests.shift(); 36663 if (pending) { 36664 // If we have pending requests and a socket gets closed a new one 36665 // needs to be created to take over in the pool for the one that closed. 36666 this.createSocket(pending, function(socket) { 36667 pending.request.onSocket(socket); 36668 }); 36669 } 36670 }; 36671 36672 function createSecureSocket(options, cb) { 36673 var self = this; 36674 TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { 36675 var hostHeader = options.request.getHeader('host'); 36676 var tlsOptions = mergeOptions({}, self.options, { 36677 socket: socket, 36678 servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host 36679 }); 36680 36681 // 0 is dummy port for v0.6 36682 var secureSocket = tls.connect(0, tlsOptions); 36683 self.sockets[self.sockets.indexOf(socket)] = secureSocket; 36684 cb(secureSocket); 36685 }); 36686 } 36687 36688 36689 function toOptions(host, port, localAddress) { 36690 if (typeof host === 'string') { // since v0.10 36691 return { 36692 host: host, 36693 port: port, 36694 localAddress: localAddress 36695 }; 36696 } 36697 return host; // for v0.11 or later 36698 } 36699 36700 function mergeOptions(target) { 36701 for (var i = 1, len = arguments.length; i < len; ++i) { 36702 var overrides = arguments[i]; 36703 if (typeof overrides === 'object') { 36704 var keys = Object.keys(overrides); 36705 for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { 36706 var k = keys[j]; 36707 if (overrides[k] !== undefined) { 36708 target[k] = overrides[k]; 36709 } 36710 } 36711 } 36712 } 36713 return target; 36714 } 36715 36716 36717 var debug; 36718 if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { 36719 debug = function() { 36720 var args = Array.prototype.slice.call(arguments); 36721 if (typeof args[0] === 'string') { 36722 args[0] = 'TUNNEL: ' + args[0]; 36723 } else { 36724 args.unshift('TUNNEL:'); 36725 } 36726 console.error.apply(console, args); 36727 } 36728 } else { 36729 debug = function() {}; 36730 } 36731 exports.debug = debug; // for test 36732 36733 36734 /***/ }), 36735 36736 /***/ 1773: 36737 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 36738 36739 "use strict"; 36740 36741 36742 const Client = __nccwpck_require__(3598) 36743 const Dispatcher = __nccwpck_require__(412) 36744 const errors = __nccwpck_require__(8045) 36745 const Pool = __nccwpck_require__(4634) 36746 const BalancedPool = __nccwpck_require__(7931) 36747 const Agent = __nccwpck_require__(7890) 36748 const util = __nccwpck_require__(3983) 36749 const { InvalidArgumentError } = errors 36750 const api = __nccwpck_require__(4059) 36751 const buildConnector = __nccwpck_require__(2067) 36752 const MockClient = __nccwpck_require__(8687) 36753 const MockAgent = __nccwpck_require__(6771) 36754 const MockPool = __nccwpck_require__(6193) 36755 const mockErrors = __nccwpck_require__(888) 36756 const ProxyAgent = __nccwpck_require__(7858) 36757 const RetryHandler = __nccwpck_require__(2286) 36758 const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) 36759 const DecoratorHandler = __nccwpck_require__(6930) 36760 const RedirectHandler = __nccwpck_require__(2860) 36761 const createRedirectInterceptor = __nccwpck_require__(8861) 36762 36763 let hasCrypto 36764 try { 36765 __nccwpck_require__(6113) 36766 hasCrypto = true 36767 } catch { 36768 hasCrypto = false 36769 } 36770 36771 Object.assign(Dispatcher.prototype, api) 36772 36773 module.exports.Dispatcher = Dispatcher 36774 module.exports.Client = Client 36775 module.exports.Pool = Pool 36776 module.exports.BalancedPool = BalancedPool 36777 module.exports.Agent = Agent 36778 module.exports.ProxyAgent = ProxyAgent 36779 module.exports.RetryHandler = RetryHandler 36780 36781 module.exports.DecoratorHandler = DecoratorHandler 36782 module.exports.RedirectHandler = RedirectHandler 36783 module.exports.createRedirectInterceptor = createRedirectInterceptor 36784 36785 module.exports.buildConnector = buildConnector 36786 module.exports.errors = errors 36787 36788 function makeDispatcher (fn) { 36789 return (url, opts, handler) => { 36790 if (typeof opts === 'function') { 36791 handler = opts 36792 opts = null 36793 } 36794 36795 if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { 36796 throw new InvalidArgumentError('invalid url') 36797 } 36798 36799 if (opts != null && typeof opts !== 'object') { 36800 throw new InvalidArgumentError('invalid opts') 36801 } 36802 36803 if (opts && opts.path != null) { 36804 if (typeof opts.path !== 'string') { 36805 throw new InvalidArgumentError('invalid opts.path') 36806 } 36807 36808 let path = opts.path 36809 if (!opts.path.startsWith('/')) { 36810 path = `/${path}` 36811 } 36812 36813 url = new URL(util.parseOrigin(url).origin + path) 36814 } else { 36815 if (!opts) { 36816 opts = typeof url === 'object' ? url : {} 36817 } 36818 36819 url = util.parseURL(url) 36820 } 36821 36822 const { agent, dispatcher = getGlobalDispatcher() } = opts 36823 36824 if (agent) { 36825 throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') 36826 } 36827 36828 return fn.call(dispatcher, { 36829 ...opts, 36830 origin: url.origin, 36831 path: url.search ? `${url.pathname}${url.search}` : url.pathname, 36832 method: opts.method || (opts.body ? 'PUT' : 'GET') 36833 }, handler) 36834 } 36835 } 36836 36837 module.exports.setGlobalDispatcher = setGlobalDispatcher 36838 module.exports.getGlobalDispatcher = getGlobalDispatcher 36839 36840 if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { 36841 let fetchImpl = null 36842 module.exports.fetch = async function fetch (resource) { 36843 if (!fetchImpl) { 36844 fetchImpl = (__nccwpck_require__(4881).fetch) 36845 } 36846 36847 try { 36848 return await fetchImpl(...arguments) 36849 } catch (err) { 36850 if (typeof err === 'object') { 36851 Error.captureStackTrace(err, this) 36852 } 36853 36854 throw err 36855 } 36856 } 36857 module.exports.Headers = __nccwpck_require__(554).Headers 36858 module.exports.Response = __nccwpck_require__(7823).Response 36859 module.exports.Request = __nccwpck_require__(8359).Request 36860 module.exports.FormData = __nccwpck_require__(2015).FormData 36861 module.exports.File = __nccwpck_require__(8511).File 36862 module.exports.FileReader = __nccwpck_require__(1446).FileReader 36863 36864 const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1246) 36865 36866 module.exports.setGlobalOrigin = setGlobalOrigin 36867 module.exports.getGlobalOrigin = getGlobalOrigin 36868 36869 const { CacheStorage } = __nccwpck_require__(7907) 36870 const { kConstruct } = __nccwpck_require__(9174) 36871 36872 // Cache & CacheStorage are tightly coupled with fetch. Even if it may run 36873 // in an older version of Node, it doesn't have any use without fetch. 36874 module.exports.caches = new CacheStorage(kConstruct) 36875 } 36876 36877 if (util.nodeMajor >= 16) { 36878 const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(1724) 36879 36880 module.exports.deleteCookie = deleteCookie 36881 module.exports.getCookies = getCookies 36882 module.exports.getSetCookies = getSetCookies 36883 module.exports.setCookie = setCookie 36884 36885 const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) 36886 36887 module.exports.parseMIMEType = parseMIMEType 36888 module.exports.serializeAMimeType = serializeAMimeType 36889 } 36890 36891 if (util.nodeMajor >= 18 && hasCrypto) { 36892 const { WebSocket } = __nccwpck_require__(4284) 36893 36894 module.exports.WebSocket = WebSocket 36895 } 36896 36897 module.exports.request = makeDispatcher(api.request) 36898 module.exports.stream = makeDispatcher(api.stream) 36899 module.exports.pipeline = makeDispatcher(api.pipeline) 36900 module.exports.connect = makeDispatcher(api.connect) 36901 module.exports.upgrade = makeDispatcher(api.upgrade) 36902 36903 module.exports.MockClient = MockClient 36904 module.exports.MockPool = MockPool 36905 module.exports.MockAgent = MockAgent 36906 module.exports.mockErrors = mockErrors 36907 36908 36909 /***/ }), 36910 36911 /***/ 7890: 36912 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 36913 36914 "use strict"; 36915 36916 36917 const { InvalidArgumentError } = __nccwpck_require__(8045) 36918 const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(2785) 36919 const DispatcherBase = __nccwpck_require__(4839) 36920 const Pool = __nccwpck_require__(4634) 36921 const Client = __nccwpck_require__(3598) 36922 const util = __nccwpck_require__(3983) 36923 const createRedirectInterceptor = __nccwpck_require__(8861) 36924 const { WeakRef, FinalizationRegistry } = __nccwpck_require__(6436)() 36925 36926 const kOnConnect = Symbol('onConnect') 36927 const kOnDisconnect = Symbol('onDisconnect') 36928 const kOnConnectionError = Symbol('onConnectionError') 36929 const kMaxRedirections = Symbol('maxRedirections') 36930 const kOnDrain = Symbol('onDrain') 36931 const kFactory = Symbol('factory') 36932 const kFinalizer = Symbol('finalizer') 36933 const kOptions = Symbol('options') 36934 36935 function defaultFactory (origin, opts) { 36936 return opts && opts.connections === 1 36937 ? new Client(origin, opts) 36938 : new Pool(origin, opts) 36939 } 36940 36941 class Agent extends DispatcherBase { 36942 constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { 36943 super() 36944 36945 if (typeof factory !== 'function') { 36946 throw new InvalidArgumentError('factory must be a function.') 36947 } 36948 36949 if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { 36950 throw new InvalidArgumentError('connect must be a function or an object') 36951 } 36952 36953 if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { 36954 throw new InvalidArgumentError('maxRedirections must be a positive number') 36955 } 36956 36957 if (connect && typeof connect !== 'function') { 36958 connect = { ...connect } 36959 } 36960 36961 this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) 36962 ? options.interceptors.Agent 36963 : [createRedirectInterceptor({ maxRedirections })] 36964 36965 this[kOptions] = { ...util.deepClone(options), connect } 36966 this[kOptions].interceptors = options.interceptors 36967 ? { ...options.interceptors } 36968 : undefined 36969 this[kMaxRedirections] = maxRedirections 36970 this[kFactory] = factory 36971 this[kClients] = new Map() 36972 this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { 36973 const ref = this[kClients].get(key) 36974 if (ref !== undefined && ref.deref() === undefined) { 36975 this[kClients].delete(key) 36976 } 36977 }) 36978 36979 const agent = this 36980 36981 this[kOnDrain] = (origin, targets) => { 36982 agent.emit('drain', origin, [agent, ...targets]) 36983 } 36984 36985 this[kOnConnect] = (origin, targets) => { 36986 agent.emit('connect', origin, [agent, ...targets]) 36987 } 36988 36989 this[kOnDisconnect] = (origin, targets, err) => { 36990 agent.emit('disconnect', origin, [agent, ...targets], err) 36991 } 36992 36993 this[kOnConnectionError] = (origin, targets, err) => { 36994 agent.emit('connectionError', origin, [agent, ...targets], err) 36995 } 36996 } 36997 36998 get [kRunning] () { 36999 let ret = 0 37000 for (const ref of this[kClients].values()) { 37001 const client = ref.deref() 37002 /* istanbul ignore next: gc is undeterministic */ 37003 if (client) { 37004 ret += client[kRunning] 37005 } 37006 } 37007 return ret 37008 } 37009 37010 [kDispatch] (opts, handler) { 37011 let key 37012 if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { 37013 key = String(opts.origin) 37014 } else { 37015 throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') 37016 } 37017 37018 const ref = this[kClients].get(key) 37019 37020 let dispatcher = ref ? ref.deref() : null 37021 if (!dispatcher) { 37022 dispatcher = this[kFactory](opts.origin, this[kOptions]) 37023 .on('drain', this[kOnDrain]) 37024 .on('connect', this[kOnConnect]) 37025 .on('disconnect', this[kOnDisconnect]) 37026 .on('connectionError', this[kOnConnectionError]) 37027 37028 this[kClients].set(key, new WeakRef(dispatcher)) 37029 this[kFinalizer].register(dispatcher, key) 37030 } 37031 37032 return dispatcher.dispatch(opts, handler) 37033 } 37034 37035 async [kClose] () { 37036 const closePromises = [] 37037 for (const ref of this[kClients].values()) { 37038 const client = ref.deref() 37039 /* istanbul ignore else: gc is undeterministic */ 37040 if (client) { 37041 closePromises.push(client.close()) 37042 } 37043 } 37044 37045 await Promise.all(closePromises) 37046 } 37047 37048 async [kDestroy] (err) { 37049 const destroyPromises = [] 37050 for (const ref of this[kClients].values()) { 37051 const client = ref.deref() 37052 /* istanbul ignore else: gc is undeterministic */ 37053 if (client) { 37054 destroyPromises.push(client.destroy(err)) 37055 } 37056 } 37057 37058 await Promise.all(destroyPromises) 37059 } 37060 } 37061 37062 module.exports = Agent 37063 37064 37065 /***/ }), 37066 37067 /***/ 7032: 37068 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37069 37070 const { addAbortListener } = __nccwpck_require__(3983) 37071 const { RequestAbortedError } = __nccwpck_require__(8045) 37072 37073 const kListener = Symbol('kListener') 37074 const kSignal = Symbol('kSignal') 37075 37076 function abort (self) { 37077 if (self.abort) { 37078 self.abort() 37079 } else { 37080 self.onError(new RequestAbortedError()) 37081 } 37082 } 37083 37084 function addSignal (self, signal) { 37085 self[kSignal] = null 37086 self[kListener] = null 37087 37088 if (!signal) { 37089 return 37090 } 37091 37092 if (signal.aborted) { 37093 abort(self) 37094 return 37095 } 37096 37097 self[kSignal] = signal 37098 self[kListener] = () => { 37099 abort(self) 37100 } 37101 37102 addAbortListener(self[kSignal], self[kListener]) 37103 } 37104 37105 function removeSignal (self) { 37106 if (!self[kSignal]) { 37107 return 37108 } 37109 37110 if ('removeEventListener' in self[kSignal]) { 37111 self[kSignal].removeEventListener('abort', self[kListener]) 37112 } else { 37113 self[kSignal].removeListener('abort', self[kListener]) 37114 } 37115 37116 self[kSignal] = null 37117 self[kListener] = null 37118 } 37119 37120 module.exports = { 37121 addSignal, 37122 removeSignal 37123 } 37124 37125 37126 /***/ }), 37127 37128 /***/ 9744: 37129 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37130 37131 "use strict"; 37132 37133 37134 const { AsyncResource } = __nccwpck_require__(852) 37135 const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) 37136 const util = __nccwpck_require__(3983) 37137 const { addSignal, removeSignal } = __nccwpck_require__(7032) 37138 37139 class ConnectHandler extends AsyncResource { 37140 constructor (opts, callback) { 37141 if (!opts || typeof opts !== 'object') { 37142 throw new InvalidArgumentError('invalid opts') 37143 } 37144 37145 if (typeof callback !== 'function') { 37146 throw new InvalidArgumentError('invalid callback') 37147 } 37148 37149 const { signal, opaque, responseHeaders } = opts 37150 37151 if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { 37152 throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') 37153 } 37154 37155 super('UNDICI_CONNECT') 37156 37157 this.opaque = opaque || null 37158 this.responseHeaders = responseHeaders || null 37159 this.callback = callback 37160 this.abort = null 37161 37162 addSignal(this, signal) 37163 } 37164 37165 onConnect (abort, context) { 37166 if (!this.callback) { 37167 throw new RequestAbortedError() 37168 } 37169 37170 this.abort = abort 37171 this.context = context 37172 } 37173 37174 onHeaders () { 37175 throw new SocketError('bad connect', null) 37176 } 37177 37178 onUpgrade (statusCode, rawHeaders, socket) { 37179 const { callback, opaque, context } = this 37180 37181 removeSignal(this) 37182 37183 this.callback = null 37184 37185 let headers = rawHeaders 37186 // Indicates is an HTTP2Session 37187 if (headers != null) { 37188 headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37189 } 37190 37191 this.runInAsyncScope(callback, null, null, { 37192 statusCode, 37193 headers, 37194 socket, 37195 opaque, 37196 context 37197 }) 37198 } 37199 37200 onError (err) { 37201 const { callback, opaque } = this 37202 37203 removeSignal(this) 37204 37205 if (callback) { 37206 this.callback = null 37207 queueMicrotask(() => { 37208 this.runInAsyncScope(callback, null, err, { opaque }) 37209 }) 37210 } 37211 } 37212 } 37213 37214 function connect (opts, callback) { 37215 if (callback === undefined) { 37216 return new Promise((resolve, reject) => { 37217 connect.call(this, opts, (err, data) => { 37218 return err ? reject(err) : resolve(data) 37219 }) 37220 }) 37221 } 37222 37223 try { 37224 const connectHandler = new ConnectHandler(opts, callback) 37225 this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) 37226 } catch (err) { 37227 if (typeof callback !== 'function') { 37228 throw err 37229 } 37230 const opaque = opts && opts.opaque 37231 queueMicrotask(() => callback(err, { opaque })) 37232 } 37233 } 37234 37235 module.exports = connect 37236 37237 37238 /***/ }), 37239 37240 /***/ 8752: 37241 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37242 37243 "use strict"; 37244 37245 37246 const { 37247 Readable, 37248 Duplex, 37249 PassThrough 37250 } = __nccwpck_require__(2781) 37251 const { 37252 InvalidArgumentError, 37253 InvalidReturnValueError, 37254 RequestAbortedError 37255 } = __nccwpck_require__(8045) 37256 const util = __nccwpck_require__(3983) 37257 const { AsyncResource } = __nccwpck_require__(852) 37258 const { addSignal, removeSignal } = __nccwpck_require__(7032) 37259 const assert = __nccwpck_require__(9491) 37260 37261 const kResume = Symbol('resume') 37262 37263 class PipelineRequest extends Readable { 37264 constructor () { 37265 super({ autoDestroy: true }) 37266 37267 this[kResume] = null 37268 } 37269 37270 _read () { 37271 const { [kResume]: resume } = this 37272 37273 if (resume) { 37274 this[kResume] = null 37275 resume() 37276 } 37277 } 37278 37279 _destroy (err, callback) { 37280 this._read() 37281 37282 callback(err) 37283 } 37284 } 37285 37286 class PipelineResponse extends Readable { 37287 constructor (resume) { 37288 super({ autoDestroy: true }) 37289 this[kResume] = resume 37290 } 37291 37292 _read () { 37293 this[kResume]() 37294 } 37295 37296 _destroy (err, callback) { 37297 if (!err && !this._readableState.endEmitted) { 37298 err = new RequestAbortedError() 37299 } 37300 37301 callback(err) 37302 } 37303 } 37304 37305 class PipelineHandler extends AsyncResource { 37306 constructor (opts, handler) { 37307 if (!opts || typeof opts !== 'object') { 37308 throw new InvalidArgumentError('invalid opts') 37309 } 37310 37311 if (typeof handler !== 'function') { 37312 throw new InvalidArgumentError('invalid handler') 37313 } 37314 37315 const { signal, method, opaque, onInfo, responseHeaders } = opts 37316 37317 if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { 37318 throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') 37319 } 37320 37321 if (method === 'CONNECT') { 37322 throw new InvalidArgumentError('invalid method') 37323 } 37324 37325 if (onInfo && typeof onInfo !== 'function') { 37326 throw new InvalidArgumentError('invalid onInfo callback') 37327 } 37328 37329 super('UNDICI_PIPELINE') 37330 37331 this.opaque = opaque || null 37332 this.responseHeaders = responseHeaders || null 37333 this.handler = handler 37334 this.abort = null 37335 this.context = null 37336 this.onInfo = onInfo || null 37337 37338 this.req = new PipelineRequest().on('error', util.nop) 37339 37340 this.ret = new Duplex({ 37341 readableObjectMode: opts.objectMode, 37342 autoDestroy: true, 37343 read: () => { 37344 const { body } = this 37345 37346 if (body && body.resume) { 37347 body.resume() 37348 } 37349 }, 37350 write: (chunk, encoding, callback) => { 37351 const { req } = this 37352 37353 if (req.push(chunk, encoding) || req._readableState.destroyed) { 37354 callback() 37355 } else { 37356 req[kResume] = callback 37357 } 37358 }, 37359 destroy: (err, callback) => { 37360 const { body, req, res, ret, abort } = this 37361 37362 if (!err && !ret._readableState.endEmitted) { 37363 err = new RequestAbortedError() 37364 } 37365 37366 if (abort && err) { 37367 abort() 37368 } 37369 37370 util.destroy(body, err) 37371 util.destroy(req, err) 37372 util.destroy(res, err) 37373 37374 removeSignal(this) 37375 37376 callback(err) 37377 } 37378 }).on('prefinish', () => { 37379 const { req } = this 37380 37381 // Node < 15 does not call _final in same tick. 37382 req.push(null) 37383 }) 37384 37385 this.res = null 37386 37387 addSignal(this, signal) 37388 } 37389 37390 onConnect (abort, context) { 37391 const { ret, res } = this 37392 37393 assert(!res, 'pipeline cannot be retried') 37394 37395 if (ret.destroyed) { 37396 throw new RequestAbortedError() 37397 } 37398 37399 this.abort = abort 37400 this.context = context 37401 } 37402 37403 onHeaders (statusCode, rawHeaders, resume) { 37404 const { opaque, handler, context } = this 37405 37406 if (statusCode < 200) { 37407 if (this.onInfo) { 37408 const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37409 this.onInfo({ statusCode, headers }) 37410 } 37411 return 37412 } 37413 37414 this.res = new PipelineResponse(resume) 37415 37416 let body 37417 try { 37418 this.handler = null 37419 const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37420 body = this.runInAsyncScope(handler, null, { 37421 statusCode, 37422 headers, 37423 opaque, 37424 body: this.res, 37425 context 37426 }) 37427 } catch (err) { 37428 this.res.on('error', util.nop) 37429 throw err 37430 } 37431 37432 if (!body || typeof body.on !== 'function') { 37433 throw new InvalidReturnValueError('expected Readable') 37434 } 37435 37436 body 37437 .on('data', (chunk) => { 37438 const { ret, body } = this 37439 37440 if (!ret.push(chunk) && body.pause) { 37441 body.pause() 37442 } 37443 }) 37444 .on('error', (err) => { 37445 const { ret } = this 37446 37447 util.destroy(ret, err) 37448 }) 37449 .on('end', () => { 37450 const { ret } = this 37451 37452 ret.push(null) 37453 }) 37454 .on('close', () => { 37455 const { ret } = this 37456 37457 if (!ret._readableState.ended) { 37458 util.destroy(ret, new RequestAbortedError()) 37459 } 37460 }) 37461 37462 this.body = body 37463 } 37464 37465 onData (chunk) { 37466 const { res } = this 37467 return res.push(chunk) 37468 } 37469 37470 onComplete (trailers) { 37471 const { res } = this 37472 res.push(null) 37473 } 37474 37475 onError (err) { 37476 const { ret } = this 37477 this.handler = null 37478 util.destroy(ret, err) 37479 } 37480 } 37481 37482 function pipeline (opts, handler) { 37483 try { 37484 const pipelineHandler = new PipelineHandler(opts, handler) 37485 this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) 37486 return pipelineHandler.ret 37487 } catch (err) { 37488 return new PassThrough().destroy(err) 37489 } 37490 } 37491 37492 module.exports = pipeline 37493 37494 37495 /***/ }), 37496 37497 /***/ 5448: 37498 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37499 37500 "use strict"; 37501 37502 37503 const Readable = __nccwpck_require__(3858) 37504 const { 37505 InvalidArgumentError, 37506 RequestAbortedError 37507 } = __nccwpck_require__(8045) 37508 const util = __nccwpck_require__(3983) 37509 const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) 37510 const { AsyncResource } = __nccwpck_require__(852) 37511 const { addSignal, removeSignal } = __nccwpck_require__(7032) 37512 37513 class RequestHandler extends AsyncResource { 37514 constructor (opts, callback) { 37515 if (!opts || typeof opts !== 'object') { 37516 throw new InvalidArgumentError('invalid opts') 37517 } 37518 37519 const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts 37520 37521 try { 37522 if (typeof callback !== 'function') { 37523 throw new InvalidArgumentError('invalid callback') 37524 } 37525 37526 if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { 37527 throw new InvalidArgumentError('invalid highWaterMark') 37528 } 37529 37530 if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { 37531 throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') 37532 } 37533 37534 if (method === 'CONNECT') { 37535 throw new InvalidArgumentError('invalid method') 37536 } 37537 37538 if (onInfo && typeof onInfo !== 'function') { 37539 throw new InvalidArgumentError('invalid onInfo callback') 37540 } 37541 37542 super('UNDICI_REQUEST') 37543 } catch (err) { 37544 if (util.isStream(body)) { 37545 util.destroy(body.on('error', util.nop), err) 37546 } 37547 throw err 37548 } 37549 37550 this.responseHeaders = responseHeaders || null 37551 this.opaque = opaque || null 37552 this.callback = callback 37553 this.res = null 37554 this.abort = null 37555 this.body = body 37556 this.trailers = {} 37557 this.context = null 37558 this.onInfo = onInfo || null 37559 this.throwOnError = throwOnError 37560 this.highWaterMark = highWaterMark 37561 37562 if (util.isStream(body)) { 37563 body.on('error', (err) => { 37564 this.onError(err) 37565 }) 37566 } 37567 37568 addSignal(this, signal) 37569 } 37570 37571 onConnect (abort, context) { 37572 if (!this.callback) { 37573 throw new RequestAbortedError() 37574 } 37575 37576 this.abort = abort 37577 this.context = context 37578 } 37579 37580 onHeaders (statusCode, rawHeaders, resume, statusMessage) { 37581 const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this 37582 37583 const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37584 37585 if (statusCode < 200) { 37586 if (this.onInfo) { 37587 this.onInfo({ statusCode, headers }) 37588 } 37589 return 37590 } 37591 37592 const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers 37593 const contentType = parsedHeaders['content-type'] 37594 const body = new Readable({ resume, abort, contentType, highWaterMark }) 37595 37596 this.callback = null 37597 this.res = body 37598 if (callback !== null) { 37599 if (this.throwOnError && statusCode >= 400) { 37600 this.runInAsyncScope(getResolveErrorBodyCallback, null, 37601 { callback, body, contentType, statusCode, statusMessage, headers } 37602 ) 37603 } else { 37604 this.runInAsyncScope(callback, null, null, { 37605 statusCode, 37606 headers, 37607 trailers: this.trailers, 37608 opaque, 37609 body, 37610 context 37611 }) 37612 } 37613 } 37614 } 37615 37616 onData (chunk) { 37617 const { res } = this 37618 return res.push(chunk) 37619 } 37620 37621 onComplete (trailers) { 37622 const { res } = this 37623 37624 removeSignal(this) 37625 37626 util.parseHeaders(trailers, this.trailers) 37627 37628 res.push(null) 37629 } 37630 37631 onError (err) { 37632 const { res, callback, body, opaque } = this 37633 37634 removeSignal(this) 37635 37636 if (callback) { 37637 // TODO: Does this need queueMicrotask? 37638 this.callback = null 37639 queueMicrotask(() => { 37640 this.runInAsyncScope(callback, null, err, { opaque }) 37641 }) 37642 } 37643 37644 if (res) { 37645 this.res = null 37646 // Ensure all queued handlers are invoked before destroying res. 37647 queueMicrotask(() => { 37648 util.destroy(res, err) 37649 }) 37650 } 37651 37652 if (body) { 37653 this.body = null 37654 util.destroy(body, err) 37655 } 37656 } 37657 } 37658 37659 function request (opts, callback) { 37660 if (callback === undefined) { 37661 return new Promise((resolve, reject) => { 37662 request.call(this, opts, (err, data) => { 37663 return err ? reject(err) : resolve(data) 37664 }) 37665 }) 37666 } 37667 37668 try { 37669 this.dispatch(opts, new RequestHandler(opts, callback)) 37670 } catch (err) { 37671 if (typeof callback !== 'function') { 37672 throw err 37673 } 37674 const opaque = opts && opts.opaque 37675 queueMicrotask(() => callback(err, { opaque })) 37676 } 37677 } 37678 37679 module.exports = request 37680 module.exports.RequestHandler = RequestHandler 37681 37682 37683 /***/ }), 37684 37685 /***/ 5395: 37686 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37687 37688 "use strict"; 37689 37690 37691 const { finished, PassThrough } = __nccwpck_require__(2781) 37692 const { 37693 InvalidArgumentError, 37694 InvalidReturnValueError, 37695 RequestAbortedError 37696 } = __nccwpck_require__(8045) 37697 const util = __nccwpck_require__(3983) 37698 const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) 37699 const { AsyncResource } = __nccwpck_require__(852) 37700 const { addSignal, removeSignal } = __nccwpck_require__(7032) 37701 37702 class StreamHandler extends AsyncResource { 37703 constructor (opts, factory, callback) { 37704 if (!opts || typeof opts !== 'object') { 37705 throw new InvalidArgumentError('invalid opts') 37706 } 37707 37708 const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts 37709 37710 try { 37711 if (typeof callback !== 'function') { 37712 throw new InvalidArgumentError('invalid callback') 37713 } 37714 37715 if (typeof factory !== 'function') { 37716 throw new InvalidArgumentError('invalid factory') 37717 } 37718 37719 if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { 37720 throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') 37721 } 37722 37723 if (method === 'CONNECT') { 37724 throw new InvalidArgumentError('invalid method') 37725 } 37726 37727 if (onInfo && typeof onInfo !== 'function') { 37728 throw new InvalidArgumentError('invalid onInfo callback') 37729 } 37730 37731 super('UNDICI_STREAM') 37732 } catch (err) { 37733 if (util.isStream(body)) { 37734 util.destroy(body.on('error', util.nop), err) 37735 } 37736 throw err 37737 } 37738 37739 this.responseHeaders = responseHeaders || null 37740 this.opaque = opaque || null 37741 this.factory = factory 37742 this.callback = callback 37743 this.res = null 37744 this.abort = null 37745 this.context = null 37746 this.trailers = null 37747 this.body = body 37748 this.onInfo = onInfo || null 37749 this.throwOnError = throwOnError || false 37750 37751 if (util.isStream(body)) { 37752 body.on('error', (err) => { 37753 this.onError(err) 37754 }) 37755 } 37756 37757 addSignal(this, signal) 37758 } 37759 37760 onConnect (abort, context) { 37761 if (!this.callback) { 37762 throw new RequestAbortedError() 37763 } 37764 37765 this.abort = abort 37766 this.context = context 37767 } 37768 37769 onHeaders (statusCode, rawHeaders, resume, statusMessage) { 37770 const { factory, opaque, context, callback, responseHeaders } = this 37771 37772 const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37773 37774 if (statusCode < 200) { 37775 if (this.onInfo) { 37776 this.onInfo({ statusCode, headers }) 37777 } 37778 return 37779 } 37780 37781 this.factory = null 37782 37783 let res 37784 37785 if (this.throwOnError && statusCode >= 400) { 37786 const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers 37787 const contentType = parsedHeaders['content-type'] 37788 res = new PassThrough() 37789 37790 this.callback = null 37791 this.runInAsyncScope(getResolveErrorBodyCallback, null, 37792 { callback, body: res, contentType, statusCode, statusMessage, headers } 37793 ) 37794 } else { 37795 if (factory === null) { 37796 return 37797 } 37798 37799 res = this.runInAsyncScope(factory, null, { 37800 statusCode, 37801 headers, 37802 opaque, 37803 context 37804 }) 37805 37806 if ( 37807 !res || 37808 typeof res.write !== 'function' || 37809 typeof res.end !== 'function' || 37810 typeof res.on !== 'function' 37811 ) { 37812 throw new InvalidReturnValueError('expected Writable') 37813 } 37814 37815 // TODO: Avoid finished. It registers an unnecessary amount of listeners. 37816 finished(res, { readable: false }, (err) => { 37817 const { callback, res, opaque, trailers, abort } = this 37818 37819 this.res = null 37820 if (err || !res.readable) { 37821 util.destroy(res, err) 37822 } 37823 37824 this.callback = null 37825 this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) 37826 37827 if (err) { 37828 abort() 37829 } 37830 }) 37831 } 37832 37833 res.on('drain', resume) 37834 37835 this.res = res 37836 37837 const needDrain = res.writableNeedDrain !== undefined 37838 ? res.writableNeedDrain 37839 : res._writableState && res._writableState.needDrain 37840 37841 return needDrain !== true 37842 } 37843 37844 onData (chunk) { 37845 const { res } = this 37846 37847 return res ? res.write(chunk) : true 37848 } 37849 37850 onComplete (trailers) { 37851 const { res } = this 37852 37853 removeSignal(this) 37854 37855 if (!res) { 37856 return 37857 } 37858 37859 this.trailers = util.parseHeaders(trailers) 37860 37861 res.end() 37862 } 37863 37864 onError (err) { 37865 const { res, callback, opaque, body } = this 37866 37867 removeSignal(this) 37868 37869 this.factory = null 37870 37871 if (res) { 37872 this.res = null 37873 util.destroy(res, err) 37874 } else if (callback) { 37875 this.callback = null 37876 queueMicrotask(() => { 37877 this.runInAsyncScope(callback, null, err, { opaque }) 37878 }) 37879 } 37880 37881 if (body) { 37882 this.body = null 37883 util.destroy(body, err) 37884 } 37885 } 37886 } 37887 37888 function stream (opts, factory, callback) { 37889 if (callback === undefined) { 37890 return new Promise((resolve, reject) => { 37891 stream.call(this, opts, factory, (err, data) => { 37892 return err ? reject(err) : resolve(data) 37893 }) 37894 }) 37895 } 37896 37897 try { 37898 this.dispatch(opts, new StreamHandler(opts, factory, callback)) 37899 } catch (err) { 37900 if (typeof callback !== 'function') { 37901 throw err 37902 } 37903 const opaque = opts && opts.opaque 37904 queueMicrotask(() => callback(err, { opaque })) 37905 } 37906 } 37907 37908 module.exports = stream 37909 37910 37911 /***/ }), 37912 37913 /***/ 6923: 37914 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 37915 37916 "use strict"; 37917 37918 37919 const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) 37920 const { AsyncResource } = __nccwpck_require__(852) 37921 const util = __nccwpck_require__(3983) 37922 const { addSignal, removeSignal } = __nccwpck_require__(7032) 37923 const assert = __nccwpck_require__(9491) 37924 37925 class UpgradeHandler extends AsyncResource { 37926 constructor (opts, callback) { 37927 if (!opts || typeof opts !== 'object') { 37928 throw new InvalidArgumentError('invalid opts') 37929 } 37930 37931 if (typeof callback !== 'function') { 37932 throw new InvalidArgumentError('invalid callback') 37933 } 37934 37935 const { signal, opaque, responseHeaders } = opts 37936 37937 if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { 37938 throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') 37939 } 37940 37941 super('UNDICI_UPGRADE') 37942 37943 this.responseHeaders = responseHeaders || null 37944 this.opaque = opaque || null 37945 this.callback = callback 37946 this.abort = null 37947 this.context = null 37948 37949 addSignal(this, signal) 37950 } 37951 37952 onConnect (abort, context) { 37953 if (!this.callback) { 37954 throw new RequestAbortedError() 37955 } 37956 37957 this.abort = abort 37958 this.context = null 37959 } 37960 37961 onHeaders () { 37962 throw new SocketError('bad upgrade', null) 37963 } 37964 37965 onUpgrade (statusCode, rawHeaders, socket) { 37966 const { callback, opaque, context } = this 37967 37968 assert.strictEqual(statusCode, 101) 37969 37970 removeSignal(this) 37971 37972 this.callback = null 37973 const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) 37974 this.runInAsyncScope(callback, null, null, { 37975 headers, 37976 socket, 37977 opaque, 37978 context 37979 }) 37980 } 37981 37982 onError (err) { 37983 const { callback, opaque } = this 37984 37985 removeSignal(this) 37986 37987 if (callback) { 37988 this.callback = null 37989 queueMicrotask(() => { 37990 this.runInAsyncScope(callback, null, err, { opaque }) 37991 }) 37992 } 37993 } 37994 } 37995 37996 function upgrade (opts, callback) { 37997 if (callback === undefined) { 37998 return new Promise((resolve, reject) => { 37999 upgrade.call(this, opts, (err, data) => { 38000 return err ? reject(err) : resolve(data) 38001 }) 38002 }) 38003 } 38004 38005 try { 38006 const upgradeHandler = new UpgradeHandler(opts, callback) 38007 this.dispatch({ 38008 ...opts, 38009 method: opts.method || 'GET', 38010 upgrade: opts.protocol || 'Websocket' 38011 }, upgradeHandler) 38012 } catch (err) { 38013 if (typeof callback !== 'function') { 38014 throw err 38015 } 38016 const opaque = opts && opts.opaque 38017 queueMicrotask(() => callback(err, { opaque })) 38018 } 38019 } 38020 38021 module.exports = upgrade 38022 38023 38024 /***/ }), 38025 38026 /***/ 4059: 38027 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 38028 38029 "use strict"; 38030 38031 38032 module.exports.request = __nccwpck_require__(5448) 38033 module.exports.stream = __nccwpck_require__(5395) 38034 module.exports.pipeline = __nccwpck_require__(8752) 38035 module.exports.upgrade = __nccwpck_require__(6923) 38036 module.exports.connect = __nccwpck_require__(9744) 38037 38038 38039 /***/ }), 38040 38041 /***/ 3858: 38042 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 38043 38044 "use strict"; 38045 // Ported from https://github.com/nodejs/undici/pull/907 38046 38047 38048 38049 const assert = __nccwpck_require__(9491) 38050 const { Readable } = __nccwpck_require__(2781) 38051 const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8045) 38052 const util = __nccwpck_require__(3983) 38053 const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3983) 38054 38055 let Blob 38056 38057 const kConsume = Symbol('kConsume') 38058 const kReading = Symbol('kReading') 38059 const kBody = Symbol('kBody') 38060 const kAbort = Symbol('abort') 38061 const kContentType = Symbol('kContentType') 38062 38063 const noop = () => {} 38064 38065 module.exports = class BodyReadable extends Readable { 38066 constructor ({ 38067 resume, 38068 abort, 38069 contentType = '', 38070 highWaterMark = 64 * 1024 // Same as nodejs fs streams. 38071 }) { 38072 super({ 38073 autoDestroy: true, 38074 read: resume, 38075 highWaterMark 38076 }) 38077 38078 this._readableState.dataEmitted = false 38079 38080 this[kAbort] = abort 38081 this[kConsume] = null 38082 this[kBody] = null 38083 this[kContentType] = contentType 38084 38085 // Is stream being consumed through Readable API? 38086 // This is an optimization so that we avoid checking 38087 // for 'data' and 'readable' listeners in the hot path 38088 // inside push(). 38089 this[kReading] = false 38090 } 38091 38092 destroy (err) { 38093 if (this.destroyed) { 38094 // Node < 16 38095 return this 38096 } 38097 38098 if (!err && !this._readableState.endEmitted) { 38099 err = new RequestAbortedError() 38100 } 38101 38102 if (err) { 38103 this[kAbort]() 38104 } 38105 38106 return super.destroy(err) 38107 } 38108 38109 emit (ev, ...args) { 38110 if (ev === 'data') { 38111 // Node < 16.7 38112 this._readableState.dataEmitted = true 38113 } else if (ev === 'error') { 38114 // Node < 16 38115 this._readableState.errorEmitted = true 38116 } 38117 return super.emit(ev, ...args) 38118 } 38119 38120 on (ev, ...args) { 38121 if (ev === 'data' || ev === 'readable') { 38122 this[kReading] = true 38123 } 38124 return super.on(ev, ...args) 38125 } 38126 38127 addListener (ev, ...args) { 38128 return this.on(ev, ...args) 38129 } 38130 38131 off (ev, ...args) { 38132 const ret = super.off(ev, ...args) 38133 if (ev === 'data' || ev === 'readable') { 38134 this[kReading] = ( 38135 this.listenerCount('data') > 0 || 38136 this.listenerCount('readable') > 0 38137 ) 38138 } 38139 return ret 38140 } 38141 38142 removeListener (ev, ...args) { 38143 return this.off(ev, ...args) 38144 } 38145 38146 push (chunk) { 38147 if (this[kConsume] && chunk !== null && this.readableLength === 0) { 38148 consumePush(this[kConsume], chunk) 38149 return this[kReading] ? super.push(chunk) : true 38150 } 38151 return super.push(chunk) 38152 } 38153 38154 // https://fetch.spec.whatwg.org/#dom-body-text 38155 async text () { 38156 return consume(this, 'text') 38157 } 38158 38159 // https://fetch.spec.whatwg.org/#dom-body-json 38160 async json () { 38161 return consume(this, 'json') 38162 } 38163 38164 // https://fetch.spec.whatwg.org/#dom-body-blob 38165 async blob () { 38166 return consume(this, 'blob') 38167 } 38168 38169 // https://fetch.spec.whatwg.org/#dom-body-arraybuffer 38170 async arrayBuffer () { 38171 return consume(this, 'arrayBuffer') 38172 } 38173 38174 // https://fetch.spec.whatwg.org/#dom-body-formdata 38175 async formData () { 38176 // TODO: Implement. 38177 throw new NotSupportedError() 38178 } 38179 38180 // https://fetch.spec.whatwg.org/#dom-body-bodyused 38181 get bodyUsed () { 38182 return util.isDisturbed(this) 38183 } 38184 38185 // https://fetch.spec.whatwg.org/#dom-body-body 38186 get body () { 38187 if (!this[kBody]) { 38188 this[kBody] = ReadableStreamFrom(this) 38189 if (this[kConsume]) { 38190 // TODO: Is this the best way to force a lock? 38191 this[kBody].getReader() // Ensure stream is locked. 38192 assert(this[kBody].locked) 38193 } 38194 } 38195 return this[kBody] 38196 } 38197 38198 dump (opts) { 38199 let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 38200 const signal = opts && opts.signal 38201 38202 if (signal) { 38203 try { 38204 if (typeof signal !== 'object' || !('aborted' in signal)) { 38205 throw new InvalidArgumentError('signal must be an AbortSignal') 38206 } 38207 util.throwIfAborted(signal) 38208 } catch (err) { 38209 return Promise.reject(err) 38210 } 38211 } 38212 38213 if (this.closed) { 38214 return Promise.resolve(null) 38215 } 38216 38217 return new Promise((resolve, reject) => { 38218 const signalListenerCleanup = signal 38219 ? util.addAbortListener(signal, () => { 38220 this.destroy() 38221 }) 38222 : noop 38223 38224 this 38225 .on('close', function () { 38226 signalListenerCleanup() 38227 if (signal && signal.aborted) { 38228 reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) 38229 } else { 38230 resolve(null) 38231 } 38232 }) 38233 .on('error', noop) 38234 .on('data', function (chunk) { 38235 limit -= chunk.length 38236 if (limit <= 0) { 38237 this.destroy() 38238 } 38239 }) 38240 .resume() 38241 }) 38242 } 38243 } 38244 38245 // https://streams.spec.whatwg.org/#readablestream-locked 38246 function isLocked (self) { 38247 // Consume is an implicit lock. 38248 return (self[kBody] && self[kBody].locked === true) || self[kConsume] 38249 } 38250 38251 // https://fetch.spec.whatwg.org/#body-unusable 38252 function isUnusable (self) { 38253 return util.isDisturbed(self) || isLocked(self) 38254 } 38255 38256 async function consume (stream, type) { 38257 if (isUnusable(stream)) { 38258 throw new TypeError('unusable') 38259 } 38260 38261 assert(!stream[kConsume]) 38262 38263 return new Promise((resolve, reject) => { 38264 stream[kConsume] = { 38265 type, 38266 stream, 38267 resolve, 38268 reject, 38269 length: 0, 38270 body: [] 38271 } 38272 38273 stream 38274 .on('error', function (err) { 38275 consumeFinish(this[kConsume], err) 38276 }) 38277 .on('close', function () { 38278 if (this[kConsume].body !== null) { 38279 consumeFinish(this[kConsume], new RequestAbortedError()) 38280 } 38281 }) 38282 38283 process.nextTick(consumeStart, stream[kConsume]) 38284 }) 38285 } 38286 38287 function consumeStart (consume) { 38288 if (consume.body === null) { 38289 return 38290 } 38291 38292 const { _readableState: state } = consume.stream 38293 38294 for (const chunk of state.buffer) { 38295 consumePush(consume, chunk) 38296 } 38297 38298 if (state.endEmitted) { 38299 consumeEnd(this[kConsume]) 38300 } else { 38301 consume.stream.on('end', function () { 38302 consumeEnd(this[kConsume]) 38303 }) 38304 } 38305 38306 consume.stream.resume() 38307 38308 while (consume.stream.read() != null) { 38309 // Loop 38310 } 38311 } 38312 38313 function consumeEnd (consume) { 38314 const { type, body, resolve, stream, length } = consume 38315 38316 try { 38317 if (type === 'text') { 38318 resolve(toUSVString(Buffer.concat(body))) 38319 } else if (type === 'json') { 38320 resolve(JSON.parse(Buffer.concat(body))) 38321 } else if (type === 'arrayBuffer') { 38322 const dst = new Uint8Array(length) 38323 38324 let pos = 0 38325 for (const buf of body) { 38326 dst.set(buf, pos) 38327 pos += buf.byteLength 38328 } 38329 38330 resolve(dst.buffer) 38331 } else if (type === 'blob') { 38332 if (!Blob) { 38333 Blob = (__nccwpck_require__(4300).Blob) 38334 } 38335 resolve(new Blob(body, { type: stream[kContentType] })) 38336 } 38337 38338 consumeFinish(consume) 38339 } catch (err) { 38340 stream.destroy(err) 38341 } 38342 } 38343 38344 function consumePush (consume, chunk) { 38345 consume.length += chunk.length 38346 consume.body.push(chunk) 38347 } 38348 38349 function consumeFinish (consume, err) { 38350 if (consume.body === null) { 38351 return 38352 } 38353 38354 if (err) { 38355 consume.reject(err) 38356 } else { 38357 consume.resolve() 38358 } 38359 38360 consume.type = null 38361 consume.stream = null 38362 consume.resolve = null 38363 consume.reject = null 38364 consume.length = 0 38365 consume.body = null 38366 } 38367 38368 38369 /***/ }), 38370 38371 /***/ 7474: 38372 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 38373 38374 const assert = __nccwpck_require__(9491) 38375 const { 38376 ResponseStatusCodeError 38377 } = __nccwpck_require__(8045) 38378 const { toUSVString } = __nccwpck_require__(3983) 38379 38380 async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { 38381 assert(body) 38382 38383 let chunks = [] 38384 let limit = 0 38385 38386 for await (const chunk of body) { 38387 chunks.push(chunk) 38388 limit += chunk.length 38389 if (limit > 128 * 1024) { 38390 chunks = null 38391 break 38392 } 38393 } 38394 38395 if (statusCode === 204 || !contentType || !chunks) { 38396 process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) 38397 return 38398 } 38399 38400 try { 38401 if (contentType.startsWith('application/json')) { 38402 const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) 38403 process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) 38404 return 38405 } 38406 38407 if (contentType.startsWith('text/')) { 38408 const payload = toUSVString(Buffer.concat(chunks)) 38409 process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) 38410 return 38411 } 38412 } catch (err) { 38413 // Process in a fallback if error 38414 } 38415 38416 process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) 38417 } 38418 38419 module.exports = { getResolveErrorBodyCallback } 38420 38421 38422 /***/ }), 38423 38424 /***/ 7931: 38425 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 38426 38427 "use strict"; 38428 38429 38430 const { 38431 BalancedPoolMissingUpstreamError, 38432 InvalidArgumentError 38433 } = __nccwpck_require__(8045) 38434 const { 38435 PoolBase, 38436 kClients, 38437 kNeedDrain, 38438 kAddClient, 38439 kRemoveClient, 38440 kGetDispatcher 38441 } = __nccwpck_require__(3198) 38442 const Pool = __nccwpck_require__(4634) 38443 const { kUrl, kInterceptors } = __nccwpck_require__(2785) 38444 const { parseOrigin } = __nccwpck_require__(3983) 38445 const kFactory = Symbol('factory') 38446 38447 const kOptions = Symbol('options') 38448 const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') 38449 const kCurrentWeight = Symbol('kCurrentWeight') 38450 const kIndex = Symbol('kIndex') 38451 const kWeight = Symbol('kWeight') 38452 const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') 38453 const kErrorPenalty = Symbol('kErrorPenalty') 38454 38455 function getGreatestCommonDivisor (a, b) { 38456 if (b === 0) return a 38457 return getGreatestCommonDivisor(b, a % b) 38458 } 38459 38460 function defaultFactory (origin, opts) { 38461 return new Pool(origin, opts) 38462 } 38463 38464 class BalancedPool extends PoolBase { 38465 constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { 38466 super() 38467 38468 this[kOptions] = opts 38469 this[kIndex] = -1 38470 this[kCurrentWeight] = 0 38471 38472 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 38473 this[kErrorPenalty] = this[kOptions].errorPenalty || 15 38474 38475 if (!Array.isArray(upstreams)) { 38476 upstreams = [upstreams] 38477 } 38478 38479 if (typeof factory !== 'function') { 38480 throw new InvalidArgumentError('factory must be a function.') 38481 } 38482 38483 this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) 38484 ? opts.interceptors.BalancedPool 38485 : [] 38486 this[kFactory] = factory 38487 38488 for (const upstream of upstreams) { 38489 this.addUpstream(upstream) 38490 } 38491 this._updateBalancedPoolStats() 38492 } 38493 38494 addUpstream (upstream) { 38495 const upstreamOrigin = parseOrigin(upstream).origin 38496 38497 if (this[kClients].find((pool) => ( 38498 pool[kUrl].origin === upstreamOrigin && 38499 pool.closed !== true && 38500 pool.destroyed !== true 38501 ))) { 38502 return this 38503 } 38504 const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) 38505 38506 this[kAddClient](pool) 38507 pool.on('connect', () => { 38508 pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) 38509 }) 38510 38511 pool.on('connectionError', () => { 38512 pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) 38513 this._updateBalancedPoolStats() 38514 }) 38515 38516 pool.on('disconnect', (...args) => { 38517 const err = args[2] 38518 if (err && err.code === 'UND_ERR_SOCKET') { 38519 // decrease the weight of the pool. 38520 pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) 38521 this._updateBalancedPoolStats() 38522 } 38523 }) 38524 38525 for (const client of this[kClients]) { 38526 client[kWeight] = this[kMaxWeightPerServer] 38527 } 38528 38529 this._updateBalancedPoolStats() 38530 38531 return this 38532 } 38533 38534 _updateBalancedPoolStats () { 38535 this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) 38536 } 38537 38538 removeUpstream (upstream) { 38539 const upstreamOrigin = parseOrigin(upstream).origin 38540 38541 const pool = this[kClients].find((pool) => ( 38542 pool[kUrl].origin === upstreamOrigin && 38543 pool.closed !== true && 38544 pool.destroyed !== true 38545 )) 38546 38547 if (pool) { 38548 this[kRemoveClient](pool) 38549 } 38550 38551 return this 38552 } 38553 38554 get upstreams () { 38555 return this[kClients] 38556 .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) 38557 .map((p) => p[kUrl].origin) 38558 } 38559 38560 [kGetDispatcher] () { 38561 // We validate that pools is greater than 0, 38562 // otherwise we would have to wait until an upstream 38563 // is added, which might never happen. 38564 if (this[kClients].length === 0) { 38565 throw new BalancedPoolMissingUpstreamError() 38566 } 38567 38568 const dispatcher = this[kClients].find(dispatcher => ( 38569 !dispatcher[kNeedDrain] && 38570 dispatcher.closed !== true && 38571 dispatcher.destroyed !== true 38572 )) 38573 38574 if (!dispatcher) { 38575 return 38576 } 38577 38578 const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) 38579 38580 if (allClientsBusy) { 38581 return 38582 } 38583 38584 let counter = 0 38585 38586 let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) 38587 38588 while (counter++ < this[kClients].length) { 38589 this[kIndex] = (this[kIndex] + 1) % this[kClients].length 38590 const pool = this[kClients][this[kIndex]] 38591 38592 // find pool index with the largest weight 38593 if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { 38594 maxWeightIndex = this[kIndex] 38595 } 38596 38597 // decrease the current weight every `this[kClients].length`. 38598 if (this[kIndex] === 0) { 38599 // Set the current weight to the next lower weight. 38600 this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] 38601 38602 if (this[kCurrentWeight] <= 0) { 38603 this[kCurrentWeight] = this[kMaxWeightPerServer] 38604 } 38605 } 38606 if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { 38607 return pool 38608 } 38609 } 38610 38611 this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] 38612 this[kIndex] = maxWeightIndex 38613 return this[kClients][maxWeightIndex] 38614 } 38615 } 38616 38617 module.exports = BalancedPool 38618 38619 38620 /***/ }), 38621 38622 /***/ 6101: 38623 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 38624 38625 "use strict"; 38626 38627 38628 const { kConstruct } = __nccwpck_require__(9174) 38629 const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(2396) 38630 const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3983) 38631 const { kHeadersList } = __nccwpck_require__(2785) 38632 const { webidl } = __nccwpck_require__(1744) 38633 const { Response, cloneResponse } = __nccwpck_require__(7823) 38634 const { Request } = __nccwpck_require__(8359) 38635 const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) 38636 const { fetching } = __nccwpck_require__(4881) 38637 const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(2538) 38638 const assert = __nccwpck_require__(9491) 38639 const { getGlobalDispatcher } = __nccwpck_require__(1892) 38640 38641 /** 38642 * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation 38643 * @typedef {Object} CacheBatchOperation 38644 * @property {'delete' | 'put'} type 38645 * @property {any} request 38646 * @property {any} response 38647 * @property {import('../../types/cache').CacheQueryOptions} options 38648 */ 38649 38650 /** 38651 * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list 38652 * @typedef {[any, any][]} requestResponseList 38653 */ 38654 38655 class Cache { 38656 /** 38657 * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list 38658 * @type {requestResponseList} 38659 */ 38660 #relevantRequestResponseList 38661 38662 constructor () { 38663 if (arguments[0] !== kConstruct) { 38664 webidl.illegalConstructor() 38665 } 38666 38667 this.#relevantRequestResponseList = arguments[1] 38668 } 38669 38670 async match (request, options = {}) { 38671 webidl.brandCheck(this, Cache) 38672 webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) 38673 38674 request = webidl.converters.RequestInfo(request) 38675 options = webidl.converters.CacheQueryOptions(options) 38676 38677 const p = await this.matchAll(request, options) 38678 38679 if (p.length === 0) { 38680 return 38681 } 38682 38683 return p[0] 38684 } 38685 38686 async matchAll (request = undefined, options = {}) { 38687 webidl.brandCheck(this, Cache) 38688 38689 if (request !== undefined) request = webidl.converters.RequestInfo(request) 38690 options = webidl.converters.CacheQueryOptions(options) 38691 38692 // 1. 38693 let r = null 38694 38695 // 2. 38696 if (request !== undefined) { 38697 if (request instanceof Request) { 38698 // 2.1.1 38699 r = request[kState] 38700 38701 // 2.1.2 38702 if (r.method !== 'GET' && !options.ignoreMethod) { 38703 return [] 38704 } 38705 } else if (typeof request === 'string') { 38706 // 2.2.1 38707 r = new Request(request)[kState] 38708 } 38709 } 38710 38711 // 5. 38712 // 5.1 38713 const responses = [] 38714 38715 // 5.2 38716 if (request === undefined) { 38717 // 5.2.1 38718 for (const requestResponse of this.#relevantRequestResponseList) { 38719 responses.push(requestResponse[1]) 38720 } 38721 } else { // 5.3 38722 // 5.3.1 38723 const requestResponses = this.#queryCache(r, options) 38724 38725 // 5.3.2 38726 for (const requestResponse of requestResponses) { 38727 responses.push(requestResponse[1]) 38728 } 38729 } 38730 38731 // 5.4 38732 // We don't implement CORs so we don't need to loop over the responses, yay! 38733 38734 // 5.5.1 38735 const responseList = [] 38736 38737 // 5.5.2 38738 for (const response of responses) { 38739 // 5.5.2.1 38740 const responseObject = new Response(response.body?.source ?? null) 38741 const body = responseObject[kState].body 38742 responseObject[kState] = response 38743 responseObject[kState].body = body 38744 responseObject[kHeaders][kHeadersList] = response.headersList 38745 responseObject[kHeaders][kGuard] = 'immutable' 38746 38747 responseList.push(responseObject) 38748 } 38749 38750 // 6. 38751 return Object.freeze(responseList) 38752 } 38753 38754 async add (request) { 38755 webidl.brandCheck(this, Cache) 38756 webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) 38757 38758 request = webidl.converters.RequestInfo(request) 38759 38760 // 1. 38761 const requests = [request] 38762 38763 // 2. 38764 const responseArrayPromise = this.addAll(requests) 38765 38766 // 3. 38767 return await responseArrayPromise 38768 } 38769 38770 async addAll (requests) { 38771 webidl.brandCheck(this, Cache) 38772 webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) 38773 38774 requests = webidl.converters['sequence<RequestInfo>'](requests) 38775 38776 // 1. 38777 const responsePromises = [] 38778 38779 // 2. 38780 const requestList = [] 38781 38782 // 3. 38783 for (const request of requests) { 38784 if (typeof request === 'string') { 38785 continue 38786 } 38787 38788 // 3.1 38789 const r = request[kState] 38790 38791 // 3.2 38792 if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { 38793 throw webidl.errors.exception({ 38794 header: 'Cache.addAll', 38795 message: 'Expected http/s scheme when method is not GET.' 38796 }) 38797 } 38798 } 38799 38800 // 4. 38801 /** @type {ReturnType<typeof fetching>[]} */ 38802 const fetchControllers = [] 38803 38804 // 5. 38805 for (const request of requests) { 38806 // 5.1 38807 const r = new Request(request)[kState] 38808 38809 // 5.2 38810 if (!urlIsHttpHttpsScheme(r.url)) { 38811 throw webidl.errors.exception({ 38812 header: 'Cache.addAll', 38813 message: 'Expected http/s scheme.' 38814 }) 38815 } 38816 38817 // 5.4 38818 r.initiator = 'fetch' 38819 r.destination = 'subresource' 38820 38821 // 5.5 38822 requestList.push(r) 38823 38824 // 5.6 38825 const responsePromise = createDeferredPromise() 38826 38827 // 5.7 38828 fetchControllers.push(fetching({ 38829 request: r, 38830 dispatcher: getGlobalDispatcher(), 38831 processResponse (response) { 38832 // 1. 38833 if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { 38834 responsePromise.reject(webidl.errors.exception({ 38835 header: 'Cache.addAll', 38836 message: 'Received an invalid status code or the request failed.' 38837 })) 38838 } else if (response.headersList.contains('vary')) { // 2. 38839 // 2.1 38840 const fieldValues = getFieldValues(response.headersList.get('vary')) 38841 38842 // 2.2 38843 for (const fieldValue of fieldValues) { 38844 // 2.2.1 38845 if (fieldValue === '*') { 38846 responsePromise.reject(webidl.errors.exception({ 38847 header: 'Cache.addAll', 38848 message: 'invalid vary field value' 38849 })) 38850 38851 for (const controller of fetchControllers) { 38852 controller.abort() 38853 } 38854 38855 return 38856 } 38857 } 38858 } 38859 }, 38860 processResponseEndOfBody (response) { 38861 // 1. 38862 if (response.aborted) { 38863 responsePromise.reject(new DOMException('aborted', 'AbortError')) 38864 return 38865 } 38866 38867 // 2. 38868 responsePromise.resolve(response) 38869 } 38870 })) 38871 38872 // 5.8 38873 responsePromises.push(responsePromise.promise) 38874 } 38875 38876 // 6. 38877 const p = Promise.all(responsePromises) 38878 38879 // 7. 38880 const responses = await p 38881 38882 // 7.1 38883 const operations = [] 38884 38885 // 7.2 38886 let index = 0 38887 38888 // 7.3 38889 for (const response of responses) { 38890 // 7.3.1 38891 /** @type {CacheBatchOperation} */ 38892 const operation = { 38893 type: 'put', // 7.3.2 38894 request: requestList[index], // 7.3.3 38895 response // 7.3.4 38896 } 38897 38898 operations.push(operation) // 7.3.5 38899 38900 index++ // 7.3.6 38901 } 38902 38903 // 7.5 38904 const cacheJobPromise = createDeferredPromise() 38905 38906 // 7.6.1 38907 let errorData = null 38908 38909 // 7.6.2 38910 try { 38911 this.#batchCacheOperations(operations) 38912 } catch (e) { 38913 errorData = e 38914 } 38915 38916 // 7.6.3 38917 queueMicrotask(() => { 38918 // 7.6.3.1 38919 if (errorData === null) { 38920 cacheJobPromise.resolve(undefined) 38921 } else { 38922 // 7.6.3.2 38923 cacheJobPromise.reject(errorData) 38924 } 38925 }) 38926 38927 // 7.7 38928 return cacheJobPromise.promise 38929 } 38930 38931 async put (request, response) { 38932 webidl.brandCheck(this, Cache) 38933 webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) 38934 38935 request = webidl.converters.RequestInfo(request) 38936 response = webidl.converters.Response(response) 38937 38938 // 1. 38939 let innerRequest = null 38940 38941 // 2. 38942 if (request instanceof Request) { 38943 innerRequest = request[kState] 38944 } else { // 3. 38945 innerRequest = new Request(request)[kState] 38946 } 38947 38948 // 4. 38949 if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { 38950 throw webidl.errors.exception({ 38951 header: 'Cache.put', 38952 message: 'Expected an http/s scheme when method is not GET' 38953 }) 38954 } 38955 38956 // 5. 38957 const innerResponse = response[kState] 38958 38959 // 6. 38960 if (innerResponse.status === 206) { 38961 throw webidl.errors.exception({ 38962 header: 'Cache.put', 38963 message: 'Got 206 status' 38964 }) 38965 } 38966 38967 // 7. 38968 if (innerResponse.headersList.contains('vary')) { 38969 // 7.1. 38970 const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) 38971 38972 // 7.2. 38973 for (const fieldValue of fieldValues) { 38974 // 7.2.1 38975 if (fieldValue === '*') { 38976 throw webidl.errors.exception({ 38977 header: 'Cache.put', 38978 message: 'Got * vary field value' 38979 }) 38980 } 38981 } 38982 } 38983 38984 // 8. 38985 if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { 38986 throw webidl.errors.exception({ 38987 header: 'Cache.put', 38988 message: 'Response body is locked or disturbed' 38989 }) 38990 } 38991 38992 // 9. 38993 const clonedResponse = cloneResponse(innerResponse) 38994 38995 // 10. 38996 const bodyReadPromise = createDeferredPromise() 38997 38998 // 11. 38999 if (innerResponse.body != null) { 39000 // 11.1 39001 const stream = innerResponse.body.stream 39002 39003 // 11.2 39004 const reader = stream.getReader() 39005 39006 // 11.3 39007 readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) 39008 } else { 39009 bodyReadPromise.resolve(undefined) 39010 } 39011 39012 // 12. 39013 /** @type {CacheBatchOperation[]} */ 39014 const operations = [] 39015 39016 // 13. 39017 /** @type {CacheBatchOperation} */ 39018 const operation = { 39019 type: 'put', // 14. 39020 request: innerRequest, // 15. 39021 response: clonedResponse // 16. 39022 } 39023 39024 // 17. 39025 operations.push(operation) 39026 39027 // 19. 39028 const bytes = await bodyReadPromise.promise 39029 39030 if (clonedResponse.body != null) { 39031 clonedResponse.body.source = bytes 39032 } 39033 39034 // 19.1 39035 const cacheJobPromise = createDeferredPromise() 39036 39037 // 19.2.1 39038 let errorData = null 39039 39040 // 19.2.2 39041 try { 39042 this.#batchCacheOperations(operations) 39043 } catch (e) { 39044 errorData = e 39045 } 39046 39047 // 19.2.3 39048 queueMicrotask(() => { 39049 // 19.2.3.1 39050 if (errorData === null) { 39051 cacheJobPromise.resolve() 39052 } else { // 19.2.3.2 39053 cacheJobPromise.reject(errorData) 39054 } 39055 }) 39056 39057 return cacheJobPromise.promise 39058 } 39059 39060 async delete (request, options = {}) { 39061 webidl.brandCheck(this, Cache) 39062 webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) 39063 39064 request = webidl.converters.RequestInfo(request) 39065 options = webidl.converters.CacheQueryOptions(options) 39066 39067 /** 39068 * @type {Request} 39069 */ 39070 let r = null 39071 39072 if (request instanceof Request) { 39073 r = request[kState] 39074 39075 if (r.method !== 'GET' && !options.ignoreMethod) { 39076 return false 39077 } 39078 } else { 39079 assert(typeof request === 'string') 39080 39081 r = new Request(request)[kState] 39082 } 39083 39084 /** @type {CacheBatchOperation[]} */ 39085 const operations = [] 39086 39087 /** @type {CacheBatchOperation} */ 39088 const operation = { 39089 type: 'delete', 39090 request: r, 39091 options 39092 } 39093 39094 operations.push(operation) 39095 39096 const cacheJobPromise = createDeferredPromise() 39097 39098 let errorData = null 39099 let requestResponses 39100 39101 try { 39102 requestResponses = this.#batchCacheOperations(operations) 39103 } catch (e) { 39104 errorData = e 39105 } 39106 39107 queueMicrotask(() => { 39108 if (errorData === null) { 39109 cacheJobPromise.resolve(!!requestResponses?.length) 39110 } else { 39111 cacheJobPromise.reject(errorData) 39112 } 39113 }) 39114 39115 return cacheJobPromise.promise 39116 } 39117 39118 /** 39119 * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys 39120 * @param {any} request 39121 * @param {import('../../types/cache').CacheQueryOptions} options 39122 * @returns {readonly Request[]} 39123 */ 39124 async keys (request = undefined, options = {}) { 39125 webidl.brandCheck(this, Cache) 39126 39127 if (request !== undefined) request = webidl.converters.RequestInfo(request) 39128 options = webidl.converters.CacheQueryOptions(options) 39129 39130 // 1. 39131 let r = null 39132 39133 // 2. 39134 if (request !== undefined) { 39135 // 2.1 39136 if (request instanceof Request) { 39137 // 2.1.1 39138 r = request[kState] 39139 39140 // 2.1.2 39141 if (r.method !== 'GET' && !options.ignoreMethod) { 39142 return [] 39143 } 39144 } else if (typeof request === 'string') { // 2.2 39145 r = new Request(request)[kState] 39146 } 39147 } 39148 39149 // 4. 39150 const promise = createDeferredPromise() 39151 39152 // 5. 39153 // 5.1 39154 const requests = [] 39155 39156 // 5.2 39157 if (request === undefined) { 39158 // 5.2.1 39159 for (const requestResponse of this.#relevantRequestResponseList) { 39160 // 5.2.1.1 39161 requests.push(requestResponse[0]) 39162 } 39163 } else { // 5.3 39164 // 5.3.1 39165 const requestResponses = this.#queryCache(r, options) 39166 39167 // 5.3.2 39168 for (const requestResponse of requestResponses) { 39169 // 5.3.2.1 39170 requests.push(requestResponse[0]) 39171 } 39172 } 39173 39174 // 5.4 39175 queueMicrotask(() => { 39176 // 5.4.1 39177 const requestList = [] 39178 39179 // 5.4.2 39180 for (const request of requests) { 39181 const requestObject = new Request('https://a') 39182 requestObject[kState] = request 39183 requestObject[kHeaders][kHeadersList] = request.headersList 39184 requestObject[kHeaders][kGuard] = 'immutable' 39185 requestObject[kRealm] = request.client 39186 39187 // 5.4.2.1 39188 requestList.push(requestObject) 39189 } 39190 39191 // 5.4.3 39192 promise.resolve(Object.freeze(requestList)) 39193 }) 39194 39195 return promise.promise 39196 } 39197 39198 /** 39199 * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm 39200 * @param {CacheBatchOperation[]} operations 39201 * @returns {requestResponseList} 39202 */ 39203 #batchCacheOperations (operations) { 39204 // 1. 39205 const cache = this.#relevantRequestResponseList 39206 39207 // 2. 39208 const backupCache = [...cache] 39209 39210 // 3. 39211 const addedItems = [] 39212 39213 // 4.1 39214 const resultList = [] 39215 39216 try { 39217 // 4.2 39218 for (const operation of operations) { 39219 // 4.2.1 39220 if (operation.type !== 'delete' && operation.type !== 'put') { 39221 throw webidl.errors.exception({ 39222 header: 'Cache.#batchCacheOperations', 39223 message: 'operation type does not match "delete" or "put"' 39224 }) 39225 } 39226 39227 // 4.2.2 39228 if (operation.type === 'delete' && operation.response != null) { 39229 throw webidl.errors.exception({ 39230 header: 'Cache.#batchCacheOperations', 39231 message: 'delete operation should not have an associated response' 39232 }) 39233 } 39234 39235 // 4.2.3 39236 if (this.#queryCache(operation.request, operation.options, addedItems).length) { 39237 throw new DOMException('???', 'InvalidStateError') 39238 } 39239 39240 // 4.2.4 39241 let requestResponses 39242 39243 // 4.2.5 39244 if (operation.type === 'delete') { 39245 // 4.2.5.1 39246 requestResponses = this.#queryCache(operation.request, operation.options) 39247 39248 // TODO: the spec is wrong, this is needed to pass WPTs 39249 if (requestResponses.length === 0) { 39250 return [] 39251 } 39252 39253 // 4.2.5.2 39254 for (const requestResponse of requestResponses) { 39255 const idx = cache.indexOf(requestResponse) 39256 assert(idx !== -1) 39257 39258 // 4.2.5.2.1 39259 cache.splice(idx, 1) 39260 } 39261 } else if (operation.type === 'put') { // 4.2.6 39262 // 4.2.6.1 39263 if (operation.response == null) { 39264 throw webidl.errors.exception({ 39265 header: 'Cache.#batchCacheOperations', 39266 message: 'put operation should have an associated response' 39267 }) 39268 } 39269 39270 // 4.2.6.2 39271 const r = operation.request 39272 39273 // 4.2.6.3 39274 if (!urlIsHttpHttpsScheme(r.url)) { 39275 throw webidl.errors.exception({ 39276 header: 'Cache.#batchCacheOperations', 39277 message: 'expected http or https scheme' 39278 }) 39279 } 39280 39281 // 4.2.6.4 39282 if (r.method !== 'GET') { 39283 throw webidl.errors.exception({ 39284 header: 'Cache.#batchCacheOperations', 39285 message: 'not get method' 39286 }) 39287 } 39288 39289 // 4.2.6.5 39290 if (operation.options != null) { 39291 throw webidl.errors.exception({ 39292 header: 'Cache.#batchCacheOperations', 39293 message: 'options must not be defined' 39294 }) 39295 } 39296 39297 // 4.2.6.6 39298 requestResponses = this.#queryCache(operation.request) 39299 39300 // 4.2.6.7 39301 for (const requestResponse of requestResponses) { 39302 const idx = cache.indexOf(requestResponse) 39303 assert(idx !== -1) 39304 39305 // 4.2.6.7.1 39306 cache.splice(idx, 1) 39307 } 39308 39309 // 4.2.6.8 39310 cache.push([operation.request, operation.response]) 39311 39312 // 4.2.6.10 39313 addedItems.push([operation.request, operation.response]) 39314 } 39315 39316 // 4.2.7 39317 resultList.push([operation.request, operation.response]) 39318 } 39319 39320 // 4.3 39321 return resultList 39322 } catch (e) { // 5. 39323 // 5.1 39324 this.#relevantRequestResponseList.length = 0 39325 39326 // 5.2 39327 this.#relevantRequestResponseList = backupCache 39328 39329 // 5.3 39330 throw e 39331 } 39332 } 39333 39334 /** 39335 * @see https://w3c.github.io/ServiceWorker/#query-cache 39336 * @param {any} requestQuery 39337 * @param {import('../../types/cache').CacheQueryOptions} options 39338 * @param {requestResponseList} targetStorage 39339 * @returns {requestResponseList} 39340 */ 39341 #queryCache (requestQuery, options, targetStorage) { 39342 /** @type {requestResponseList} */ 39343 const resultList = [] 39344 39345 const storage = targetStorage ?? this.#relevantRequestResponseList 39346 39347 for (const requestResponse of storage) { 39348 const [cachedRequest, cachedResponse] = requestResponse 39349 if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { 39350 resultList.push(requestResponse) 39351 } 39352 } 39353 39354 return resultList 39355 } 39356 39357 /** 39358 * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm 39359 * @param {any} requestQuery 39360 * @param {any} request 39361 * @param {any | null} response 39362 * @param {import('../../types/cache').CacheQueryOptions | undefined} options 39363 * @returns {boolean} 39364 */ 39365 #requestMatchesCachedItem (requestQuery, request, response = null, options) { 39366 // if (options?.ignoreMethod === false && request.method === 'GET') { 39367 // return false 39368 // } 39369 39370 const queryURL = new URL(requestQuery.url) 39371 39372 const cachedURL = new URL(request.url) 39373 39374 if (options?.ignoreSearch) { 39375 cachedURL.search = '' 39376 39377 queryURL.search = '' 39378 } 39379 39380 if (!urlEquals(queryURL, cachedURL, true)) { 39381 return false 39382 } 39383 39384 if ( 39385 response == null || 39386 options?.ignoreVary || 39387 !response.headersList.contains('vary') 39388 ) { 39389 return true 39390 } 39391 39392 const fieldValues = getFieldValues(response.headersList.get('vary')) 39393 39394 for (const fieldValue of fieldValues) { 39395 if (fieldValue === '*') { 39396 return false 39397 } 39398 39399 const requestValue = request.headersList.get(fieldValue) 39400 const queryValue = requestQuery.headersList.get(fieldValue) 39401 39402 // If one has the header and the other doesn't, or one has 39403 // a different value than the other, return false 39404 if (requestValue !== queryValue) { 39405 return false 39406 } 39407 } 39408 39409 return true 39410 } 39411 } 39412 39413 Object.defineProperties(Cache.prototype, { 39414 [Symbol.toStringTag]: { 39415 value: 'Cache', 39416 configurable: true 39417 }, 39418 match: kEnumerableProperty, 39419 matchAll: kEnumerableProperty, 39420 add: kEnumerableProperty, 39421 addAll: kEnumerableProperty, 39422 put: kEnumerableProperty, 39423 delete: kEnumerableProperty, 39424 keys: kEnumerableProperty 39425 }) 39426 39427 const cacheQueryOptionConverters = [ 39428 { 39429 key: 'ignoreSearch', 39430 converter: webidl.converters.boolean, 39431 defaultValue: false 39432 }, 39433 { 39434 key: 'ignoreMethod', 39435 converter: webidl.converters.boolean, 39436 defaultValue: false 39437 }, 39438 { 39439 key: 'ignoreVary', 39440 converter: webidl.converters.boolean, 39441 defaultValue: false 39442 } 39443 ] 39444 39445 webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) 39446 39447 webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ 39448 ...cacheQueryOptionConverters, 39449 { 39450 key: 'cacheName', 39451 converter: webidl.converters.DOMString 39452 } 39453 ]) 39454 39455 webidl.converters.Response = webidl.interfaceConverter(Response) 39456 39457 webidl.converters['sequence<RequestInfo>'] = webidl.sequenceConverter( 39458 webidl.converters.RequestInfo 39459 ) 39460 39461 module.exports = { 39462 Cache 39463 } 39464 39465 39466 /***/ }), 39467 39468 /***/ 7907: 39469 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 39470 39471 "use strict"; 39472 39473 39474 const { kConstruct } = __nccwpck_require__(9174) 39475 const { Cache } = __nccwpck_require__(6101) 39476 const { webidl } = __nccwpck_require__(1744) 39477 const { kEnumerableProperty } = __nccwpck_require__(3983) 39478 39479 class CacheStorage { 39480 /** 39481 * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map 39482 * @type {Map<string, import('./cache').requestResponseList} 39483 */ 39484 #caches = new Map() 39485 39486 constructor () { 39487 if (arguments[0] !== kConstruct) { 39488 webidl.illegalConstructor() 39489 } 39490 } 39491 39492 async match (request, options = {}) { 39493 webidl.brandCheck(this, CacheStorage) 39494 webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' }) 39495 39496 request = webidl.converters.RequestInfo(request) 39497 options = webidl.converters.MultiCacheQueryOptions(options) 39498 39499 // 1. 39500 if (options.cacheName != null) { 39501 // 1.1.1.1 39502 if (this.#caches.has(options.cacheName)) { 39503 // 1.1.1.1.1 39504 const cacheList = this.#caches.get(options.cacheName) 39505 const cache = new Cache(kConstruct, cacheList) 39506 39507 return await cache.match(request, options) 39508 } 39509 } else { // 2. 39510 // 2.2 39511 for (const cacheList of this.#caches.values()) { 39512 const cache = new Cache(kConstruct, cacheList) 39513 39514 // 2.2.1.2 39515 const response = await cache.match(request, options) 39516 39517 if (response !== undefined) { 39518 return response 39519 } 39520 } 39521 } 39522 } 39523 39524 /** 39525 * @see https://w3c.github.io/ServiceWorker/#cache-storage-has 39526 * @param {string} cacheName 39527 * @returns {Promise<boolean>} 39528 */ 39529 async has (cacheName) { 39530 webidl.brandCheck(this, CacheStorage) 39531 webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) 39532 39533 cacheName = webidl.converters.DOMString(cacheName) 39534 39535 // 2.1.1 39536 // 2.2 39537 return this.#caches.has(cacheName) 39538 } 39539 39540 /** 39541 * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open 39542 * @param {string} cacheName 39543 * @returns {Promise<Cache>} 39544 */ 39545 async open (cacheName) { 39546 webidl.brandCheck(this, CacheStorage) 39547 webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) 39548 39549 cacheName = webidl.converters.DOMString(cacheName) 39550 39551 // 2.1 39552 if (this.#caches.has(cacheName)) { 39553 // await caches.open('v1') !== await caches.open('v1') 39554 39555 // 2.1.1 39556 const cache = this.#caches.get(cacheName) 39557 39558 // 2.1.1.1 39559 return new Cache(kConstruct, cache) 39560 } 39561 39562 // 2.2 39563 const cache = [] 39564 39565 // 2.3 39566 this.#caches.set(cacheName, cache) 39567 39568 // 2.4 39569 return new Cache(kConstruct, cache) 39570 } 39571 39572 /** 39573 * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete 39574 * @param {string} cacheName 39575 * @returns {Promise<boolean>} 39576 */ 39577 async delete (cacheName) { 39578 webidl.brandCheck(this, CacheStorage) 39579 webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) 39580 39581 cacheName = webidl.converters.DOMString(cacheName) 39582 39583 return this.#caches.delete(cacheName) 39584 } 39585 39586 /** 39587 * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys 39588 * @returns {string[]} 39589 */ 39590 async keys () { 39591 webidl.brandCheck(this, CacheStorage) 39592 39593 // 2.1 39594 const keys = this.#caches.keys() 39595 39596 // 2.2 39597 return [...keys] 39598 } 39599 } 39600 39601 Object.defineProperties(CacheStorage.prototype, { 39602 [Symbol.toStringTag]: { 39603 value: 'CacheStorage', 39604 configurable: true 39605 }, 39606 match: kEnumerableProperty, 39607 has: kEnumerableProperty, 39608 open: kEnumerableProperty, 39609 delete: kEnumerableProperty, 39610 keys: kEnumerableProperty 39611 }) 39612 39613 module.exports = { 39614 CacheStorage 39615 } 39616 39617 39618 /***/ }), 39619 39620 /***/ 9174: 39621 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 39622 39623 "use strict"; 39624 39625 39626 module.exports = { 39627 kConstruct: (__nccwpck_require__(2785).kConstruct) 39628 } 39629 39630 39631 /***/ }), 39632 39633 /***/ 2396: 39634 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 39635 39636 "use strict"; 39637 39638 39639 const assert = __nccwpck_require__(9491) 39640 const { URLSerializer } = __nccwpck_require__(685) 39641 const { isValidHeaderName } = __nccwpck_require__(2538) 39642 39643 /** 39644 * @see https://url.spec.whatwg.org/#concept-url-equals 39645 * @param {URL} A 39646 * @param {URL} B 39647 * @param {boolean | undefined} excludeFragment 39648 * @returns {boolean} 39649 */ 39650 function urlEquals (A, B, excludeFragment = false) { 39651 const serializedA = URLSerializer(A, excludeFragment) 39652 39653 const serializedB = URLSerializer(B, excludeFragment) 39654 39655 return serializedA === serializedB 39656 } 39657 39658 /** 39659 * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 39660 * @param {string} header 39661 */ 39662 function fieldValues (header) { 39663 assert(header !== null) 39664 39665 const values = [] 39666 39667 for (let value of header.split(',')) { 39668 value = value.trim() 39669 39670 if (!value.length) { 39671 continue 39672 } else if (!isValidHeaderName(value)) { 39673 continue 39674 } 39675 39676 values.push(value) 39677 } 39678 39679 return values 39680 } 39681 39682 module.exports = { 39683 urlEquals, 39684 fieldValues 39685 } 39686 39687 39688 /***/ }), 39689 39690 /***/ 3598: 39691 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 39692 39693 "use strict"; 39694 // @ts-check 39695 39696 39697 39698 /* global WebAssembly */ 39699 39700 const assert = __nccwpck_require__(9491) 39701 const net = __nccwpck_require__(1808) 39702 const http = __nccwpck_require__(3685) 39703 const { pipeline } = __nccwpck_require__(2781) 39704 const util = __nccwpck_require__(3983) 39705 const timers = __nccwpck_require__(9459) 39706 const Request = __nccwpck_require__(2905) 39707 const DispatcherBase = __nccwpck_require__(4839) 39708 const { 39709 RequestContentLengthMismatchError, 39710 ResponseContentLengthMismatchError, 39711 InvalidArgumentError, 39712 RequestAbortedError, 39713 HeadersTimeoutError, 39714 HeadersOverflowError, 39715 SocketError, 39716 InformationalError, 39717 BodyTimeoutError, 39718 HTTPParserError, 39719 ResponseExceededMaxSizeError, 39720 ClientDestroyedError 39721 } = __nccwpck_require__(8045) 39722 const buildConnector = __nccwpck_require__(2067) 39723 const { 39724 kUrl, 39725 kReset, 39726 kServerName, 39727 kClient, 39728 kBusy, 39729 kParser, 39730 kConnect, 39731 kBlocking, 39732 kResuming, 39733 kRunning, 39734 kPending, 39735 kSize, 39736 kWriting, 39737 kQueue, 39738 kConnected, 39739 kConnecting, 39740 kNeedDrain, 39741 kNoRef, 39742 kKeepAliveDefaultTimeout, 39743 kHostHeader, 39744 kPendingIdx, 39745 kRunningIdx, 39746 kError, 39747 kPipelining, 39748 kSocket, 39749 kKeepAliveTimeoutValue, 39750 kMaxHeadersSize, 39751 kKeepAliveMaxTimeout, 39752 kKeepAliveTimeoutThreshold, 39753 kHeadersTimeout, 39754 kBodyTimeout, 39755 kStrictContentLength, 39756 kConnector, 39757 kMaxRedirections, 39758 kMaxRequests, 39759 kCounter, 39760 kClose, 39761 kDestroy, 39762 kDispatch, 39763 kInterceptors, 39764 kLocalAddress, 39765 kMaxResponseSize, 39766 kHTTPConnVersion, 39767 // HTTP2 39768 kHost, 39769 kHTTP2Session, 39770 kHTTP2SessionState, 39771 kHTTP2BuildRequest, 39772 kHTTP2CopyHeaders, 39773 kHTTP1BuildRequest 39774 } = __nccwpck_require__(2785) 39775 39776 /** @type {import('http2')} */ 39777 let http2 39778 try { 39779 http2 = __nccwpck_require__(5158) 39780 } catch { 39781 // @ts-ignore 39782 http2 = { constants: {} } 39783 } 39784 39785 const { 39786 constants: { 39787 HTTP2_HEADER_AUTHORITY, 39788 HTTP2_HEADER_METHOD, 39789 HTTP2_HEADER_PATH, 39790 HTTP2_HEADER_SCHEME, 39791 HTTP2_HEADER_CONTENT_LENGTH, 39792 HTTP2_HEADER_EXPECT, 39793 HTTP2_HEADER_STATUS 39794 } 39795 } = http2 39796 39797 // Experimental 39798 let h2ExperimentalWarned = false 39799 39800 const FastBuffer = Buffer[Symbol.species] 39801 39802 const kClosedResolve = Symbol('kClosedResolve') 39803 39804 const channels = {} 39805 39806 try { 39807 const diagnosticsChannel = __nccwpck_require__(7643) 39808 channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') 39809 channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') 39810 channels.connectError = diagnosticsChannel.channel('undici:client:connectError') 39811 channels.connected = diagnosticsChannel.channel('undici:client:connected') 39812 } catch { 39813 channels.sendHeaders = { hasSubscribers: false } 39814 channels.beforeConnect = { hasSubscribers: false } 39815 channels.connectError = { hasSubscribers: false } 39816 channels.connected = { hasSubscribers: false } 39817 } 39818 39819 /** 39820 * @type {import('../types/client').default} 39821 */ 39822 class Client extends DispatcherBase { 39823 /** 39824 * 39825 * @param {string|URL} url 39826 * @param {import('../types/client').Client.Options} options 39827 */ 39828 constructor (url, { 39829 interceptors, 39830 maxHeaderSize, 39831 headersTimeout, 39832 socketTimeout, 39833 requestTimeout, 39834 connectTimeout, 39835 bodyTimeout, 39836 idleTimeout, 39837 keepAlive, 39838 keepAliveTimeout, 39839 maxKeepAliveTimeout, 39840 keepAliveMaxTimeout, 39841 keepAliveTimeoutThreshold, 39842 socketPath, 39843 pipelining, 39844 tls, 39845 strictContentLength, 39846 maxCachedSessions, 39847 maxRedirections, 39848 connect, 39849 maxRequestsPerClient, 39850 localAddress, 39851 maxResponseSize, 39852 autoSelectFamily, 39853 autoSelectFamilyAttemptTimeout, 39854 // h2 39855 allowH2, 39856 maxConcurrentStreams 39857 } = {}) { 39858 super() 39859 39860 if (keepAlive !== undefined) { 39861 throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') 39862 } 39863 39864 if (socketTimeout !== undefined) { 39865 throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') 39866 } 39867 39868 if (requestTimeout !== undefined) { 39869 throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') 39870 } 39871 39872 if (idleTimeout !== undefined) { 39873 throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') 39874 } 39875 39876 if (maxKeepAliveTimeout !== undefined) { 39877 throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') 39878 } 39879 39880 if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { 39881 throw new InvalidArgumentError('invalid maxHeaderSize') 39882 } 39883 39884 if (socketPath != null && typeof socketPath !== 'string') { 39885 throw new InvalidArgumentError('invalid socketPath') 39886 } 39887 39888 if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { 39889 throw new InvalidArgumentError('invalid connectTimeout') 39890 } 39891 39892 if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { 39893 throw new InvalidArgumentError('invalid keepAliveTimeout') 39894 } 39895 39896 if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { 39897 throw new InvalidArgumentError('invalid keepAliveMaxTimeout') 39898 } 39899 39900 if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { 39901 throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') 39902 } 39903 39904 if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { 39905 throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') 39906 } 39907 39908 if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { 39909 throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') 39910 } 39911 39912 if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { 39913 throw new InvalidArgumentError('connect must be a function or an object') 39914 } 39915 39916 if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { 39917 throw new InvalidArgumentError('maxRedirections must be a positive number') 39918 } 39919 39920 if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { 39921 throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') 39922 } 39923 39924 if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { 39925 throw new InvalidArgumentError('localAddress must be valid string IP address') 39926 } 39927 39928 if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { 39929 throw new InvalidArgumentError('maxResponseSize must be a positive number') 39930 } 39931 39932 if ( 39933 autoSelectFamilyAttemptTimeout != null && 39934 (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) 39935 ) { 39936 throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') 39937 } 39938 39939 // h2 39940 if (allowH2 != null && typeof allowH2 !== 'boolean') { 39941 throw new InvalidArgumentError('allowH2 must be a valid boolean value') 39942 } 39943 39944 if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { 39945 throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') 39946 } 39947 39948 if (typeof connect !== 'function') { 39949 connect = buildConnector({ 39950 ...tls, 39951 maxCachedSessions, 39952 allowH2, 39953 socketPath, 39954 timeout: connectTimeout, 39955 ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), 39956 ...connect 39957 }) 39958 } 39959 39960 this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) 39961 ? interceptors.Client 39962 : [createRedirectInterceptor({ maxRedirections })] 39963 this[kUrl] = util.parseOrigin(url) 39964 this[kConnector] = connect 39965 this[kSocket] = null 39966 this[kPipelining] = pipelining != null ? pipelining : 1 39967 this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize 39968 this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout 39969 this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout 39970 this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold 39971 this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] 39972 this[kServerName] = null 39973 this[kLocalAddress] = localAddress != null ? localAddress : null 39974 this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming 39975 this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming 39976 this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` 39977 this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 39978 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 39979 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength 39980 this[kMaxRedirections] = maxRedirections 39981 this[kMaxRequests] = maxRequestsPerClient 39982 this[kClosedResolve] = null 39983 this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 39984 this[kHTTPConnVersion] = 'h1' 39985 39986 // HTTP/2 39987 this[kHTTP2Session] = null 39988 this[kHTTP2SessionState] = !allowH2 39989 ? null 39990 : { 39991 // streams: null, // Fixed queue of streams - For future support of `push` 39992 openStreams: 0, // Keep track of them to decide wether or not unref the session 39993 maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server 39994 } 39995 this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` 39996 39997 // kQueue is built up of 3 sections separated by 39998 // the kRunningIdx and kPendingIdx indices. 39999 // | complete | running | pending | 40000 // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length 40001 // kRunningIdx points to the first running element. 40002 // kPendingIdx points to the first pending element. 40003 // This implements a fast queue with an amortized 40004 // time of O(1). 40005 40006 this[kQueue] = [] 40007 this[kRunningIdx] = 0 40008 this[kPendingIdx] = 0 40009 } 40010 40011 get pipelining () { 40012 return this[kPipelining] 40013 } 40014 40015 set pipelining (value) { 40016 this[kPipelining] = value 40017 resume(this, true) 40018 } 40019 40020 get [kPending] () { 40021 return this[kQueue].length - this[kPendingIdx] 40022 } 40023 40024 get [kRunning] () { 40025 return this[kPendingIdx] - this[kRunningIdx] 40026 } 40027 40028 get [kSize] () { 40029 return this[kQueue].length - this[kRunningIdx] 40030 } 40031 40032 get [kConnected] () { 40033 return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed 40034 } 40035 40036 get [kBusy] () { 40037 const socket = this[kSocket] 40038 return ( 40039 (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || 40040 (this[kSize] >= (this[kPipelining] || 1)) || 40041 this[kPending] > 0 40042 ) 40043 } 40044 40045 /* istanbul ignore: only used for test */ 40046 [kConnect] (cb) { 40047 connect(this) 40048 this.once('connect', cb) 40049 } 40050 40051 [kDispatch] (opts, handler) { 40052 const origin = opts.origin || this[kUrl].origin 40053 40054 const request = this[kHTTPConnVersion] === 'h2' 40055 ? Request[kHTTP2BuildRequest](origin, opts, handler) 40056 : Request[kHTTP1BuildRequest](origin, opts, handler) 40057 40058 this[kQueue].push(request) 40059 if (this[kResuming]) { 40060 // Do nothing. 40061 } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { 40062 // Wait a tick in case stream/iterator is ended in the same tick. 40063 this[kResuming] = 1 40064 process.nextTick(resume, this) 40065 } else { 40066 resume(this, true) 40067 } 40068 40069 if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { 40070 this[kNeedDrain] = 2 40071 } 40072 40073 return this[kNeedDrain] < 2 40074 } 40075 40076 async [kClose] () { 40077 // TODO: for H2 we need to gracefully flush the remaining enqueued 40078 // request and close each stream. 40079 return new Promise((resolve) => { 40080 if (!this[kSize]) { 40081 resolve(null) 40082 } else { 40083 this[kClosedResolve] = resolve 40084 } 40085 }) 40086 } 40087 40088 async [kDestroy] (err) { 40089 return new Promise((resolve) => { 40090 const requests = this[kQueue].splice(this[kPendingIdx]) 40091 for (let i = 0; i < requests.length; i++) { 40092 const request = requests[i] 40093 errorRequest(this, request, err) 40094 } 40095 40096 const callback = () => { 40097 if (this[kClosedResolve]) { 40098 // TODO (fix): Should we error here with ClientDestroyedError? 40099 this[kClosedResolve]() 40100 this[kClosedResolve] = null 40101 } 40102 resolve() 40103 } 40104 40105 if (this[kHTTP2Session] != null) { 40106 util.destroy(this[kHTTP2Session], err) 40107 this[kHTTP2Session] = null 40108 this[kHTTP2SessionState] = null 40109 } 40110 40111 if (!this[kSocket]) { 40112 queueMicrotask(callback) 40113 } else { 40114 util.destroy(this[kSocket].on('close', callback), err) 40115 } 40116 40117 resume(this) 40118 }) 40119 } 40120 } 40121 40122 function onHttp2SessionError (err) { 40123 assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') 40124 40125 this[kSocket][kError] = err 40126 40127 onError(this[kClient], err) 40128 } 40129 40130 function onHttp2FrameError (type, code, id) { 40131 const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) 40132 40133 if (id === 0) { 40134 this[kSocket][kError] = err 40135 onError(this[kClient], err) 40136 } 40137 } 40138 40139 function onHttp2SessionEnd () { 40140 util.destroy(this, new SocketError('other side closed')) 40141 util.destroy(this[kSocket], new SocketError('other side closed')) 40142 } 40143 40144 function onHTTP2GoAway (code) { 40145 const client = this[kClient] 40146 const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) 40147 client[kSocket] = null 40148 client[kHTTP2Session] = null 40149 40150 if (client.destroyed) { 40151 assert(this[kPending] === 0) 40152 40153 // Fail entire queue. 40154 const requests = client[kQueue].splice(client[kRunningIdx]) 40155 for (let i = 0; i < requests.length; i++) { 40156 const request = requests[i] 40157 errorRequest(this, request, err) 40158 } 40159 } else if (client[kRunning] > 0) { 40160 // Fail head of pipeline. 40161 const request = client[kQueue][client[kRunningIdx]] 40162 client[kQueue][client[kRunningIdx]++] = null 40163 40164 errorRequest(client, request, err) 40165 } 40166 40167 client[kPendingIdx] = client[kRunningIdx] 40168 40169 assert(client[kRunning] === 0) 40170 40171 client.emit('disconnect', 40172 client[kUrl], 40173 [client], 40174 err 40175 ) 40176 40177 resume(client) 40178 } 40179 40180 const constants = __nccwpck_require__(953) 40181 const createRedirectInterceptor = __nccwpck_require__(8861) 40182 const EMPTY_BUF = Buffer.alloc(0) 40183 40184 async function lazyllhttp () { 40185 const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1145) : undefined 40186 40187 let mod 40188 try { 40189 mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(5627), 'base64')) 40190 } catch (e) { 40191 /* istanbul ignore next */ 40192 40193 // We could check if the error was caused by the simd option not 40194 // being enabled, but the occurring of this other error 40195 // * https://github.com/emscripten-core/emscripten/issues/11495 40196 // got me to remove that check to avoid breaking Node 12. 40197 mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(1145), 'base64')) 40198 } 40199 40200 return await WebAssembly.instantiate(mod, { 40201 env: { 40202 /* eslint-disable camelcase */ 40203 40204 wasm_on_url: (p, at, len) => { 40205 /* istanbul ignore next */ 40206 return 0 40207 }, 40208 wasm_on_status: (p, at, len) => { 40209 assert.strictEqual(currentParser.ptr, p) 40210 const start = at - currentBufferPtr + currentBufferRef.byteOffset 40211 return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 40212 }, 40213 wasm_on_message_begin: (p) => { 40214 assert.strictEqual(currentParser.ptr, p) 40215 return currentParser.onMessageBegin() || 0 40216 }, 40217 wasm_on_header_field: (p, at, len) => { 40218 assert.strictEqual(currentParser.ptr, p) 40219 const start = at - currentBufferPtr + currentBufferRef.byteOffset 40220 return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 40221 }, 40222 wasm_on_header_value: (p, at, len) => { 40223 assert.strictEqual(currentParser.ptr, p) 40224 const start = at - currentBufferPtr + currentBufferRef.byteOffset 40225 return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 40226 }, 40227 wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { 40228 assert.strictEqual(currentParser.ptr, p) 40229 return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 40230 }, 40231 wasm_on_body: (p, at, len) => { 40232 assert.strictEqual(currentParser.ptr, p) 40233 const start = at - currentBufferPtr + currentBufferRef.byteOffset 40234 return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 40235 }, 40236 wasm_on_message_complete: (p) => { 40237 assert.strictEqual(currentParser.ptr, p) 40238 return currentParser.onMessageComplete() || 0 40239 } 40240 40241 /* eslint-enable camelcase */ 40242 } 40243 }) 40244 } 40245 40246 let llhttpInstance = null 40247 let llhttpPromise = lazyllhttp() 40248 llhttpPromise.catch() 40249 40250 let currentParser = null 40251 let currentBufferRef = null 40252 let currentBufferSize = 0 40253 let currentBufferPtr = null 40254 40255 const TIMEOUT_HEADERS = 1 40256 const TIMEOUT_BODY = 2 40257 const TIMEOUT_IDLE = 3 40258 40259 class Parser { 40260 constructor (client, socket, { exports }) { 40261 assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) 40262 40263 this.llhttp = exports 40264 this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) 40265 this.client = client 40266 this.socket = socket 40267 this.timeout = null 40268 this.timeoutValue = null 40269 this.timeoutType = null 40270 this.statusCode = null 40271 this.statusText = '' 40272 this.upgrade = false 40273 this.headers = [] 40274 this.headersSize = 0 40275 this.headersMaxSize = client[kMaxHeadersSize] 40276 this.shouldKeepAlive = false 40277 this.paused = false 40278 this.resume = this.resume.bind(this) 40279 40280 this.bytesRead = 0 40281 40282 this.keepAlive = '' 40283 this.contentLength = '' 40284 this.connection = '' 40285 this.maxResponseSize = client[kMaxResponseSize] 40286 } 40287 40288 setTimeout (value, type) { 40289 this.timeoutType = type 40290 if (value !== this.timeoutValue) { 40291 timers.clearTimeout(this.timeout) 40292 if (value) { 40293 this.timeout = timers.setTimeout(onParserTimeout, value, this) 40294 // istanbul ignore else: only for jest 40295 if (this.timeout.unref) { 40296 this.timeout.unref() 40297 } 40298 } else { 40299 this.timeout = null 40300 } 40301 this.timeoutValue = value 40302 } else if (this.timeout) { 40303 // istanbul ignore else: only for jest 40304 if (this.timeout.refresh) { 40305 this.timeout.refresh() 40306 } 40307 } 40308 } 40309 40310 resume () { 40311 if (this.socket.destroyed || !this.paused) { 40312 return 40313 } 40314 40315 assert(this.ptr != null) 40316 assert(currentParser == null) 40317 40318 this.llhttp.llhttp_resume(this.ptr) 40319 40320 assert(this.timeoutType === TIMEOUT_BODY) 40321 if (this.timeout) { 40322 // istanbul ignore else: only for jest 40323 if (this.timeout.refresh) { 40324 this.timeout.refresh() 40325 } 40326 } 40327 40328 this.paused = false 40329 this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. 40330 this.readMore() 40331 } 40332 40333 readMore () { 40334 while (!this.paused && this.ptr) { 40335 const chunk = this.socket.read() 40336 if (chunk === null) { 40337 break 40338 } 40339 this.execute(chunk) 40340 } 40341 } 40342 40343 execute (data) { 40344 assert(this.ptr != null) 40345 assert(currentParser == null) 40346 assert(!this.paused) 40347 40348 const { socket, llhttp } = this 40349 40350 if (data.length > currentBufferSize) { 40351 if (currentBufferPtr) { 40352 llhttp.free(currentBufferPtr) 40353 } 40354 currentBufferSize = Math.ceil(data.length / 4096) * 4096 40355 currentBufferPtr = llhttp.malloc(currentBufferSize) 40356 } 40357 40358 new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) 40359 40360 // Call `execute` on the wasm parser. 40361 // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, 40362 // and finally the length of bytes to parse. 40363 // The return value is an error code or `constants.ERROR.OK`. 40364 try { 40365 let ret 40366 40367 try { 40368 currentBufferRef = data 40369 currentParser = this 40370 ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) 40371 /* eslint-disable-next-line no-useless-catch */ 40372 } catch (err) { 40373 /* istanbul ignore next: difficult to make a test case for */ 40374 throw err 40375 } finally { 40376 currentParser = null 40377 currentBufferRef = null 40378 } 40379 40380 const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr 40381 40382 if (ret === constants.ERROR.PAUSED_UPGRADE) { 40383 this.onUpgrade(data.slice(offset)) 40384 } else if (ret === constants.ERROR.PAUSED) { 40385 this.paused = true 40386 socket.unshift(data.slice(offset)) 40387 } else if (ret !== constants.ERROR.OK) { 40388 const ptr = llhttp.llhttp_get_error_reason(this.ptr) 40389 let message = '' 40390 /* istanbul ignore else: difficult to make a test case for */ 40391 if (ptr) { 40392 const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) 40393 message = 40394 'Response does not match the HTTP/1.1 protocol (' + 40395 Buffer.from(llhttp.memory.buffer, ptr, len).toString() + 40396 ')' 40397 } 40398 throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) 40399 } 40400 } catch (err) { 40401 util.destroy(socket, err) 40402 } 40403 } 40404 40405 destroy () { 40406 assert(this.ptr != null) 40407 assert(currentParser == null) 40408 40409 this.llhttp.llhttp_free(this.ptr) 40410 this.ptr = null 40411 40412 timers.clearTimeout(this.timeout) 40413 this.timeout = null 40414 this.timeoutValue = null 40415 this.timeoutType = null 40416 40417 this.paused = false 40418 } 40419 40420 onStatus (buf) { 40421 this.statusText = buf.toString() 40422 } 40423 40424 onMessageBegin () { 40425 const { socket, client } = this 40426 40427 /* istanbul ignore next: difficult to make a test case for */ 40428 if (socket.destroyed) { 40429 return -1 40430 } 40431 40432 const request = client[kQueue][client[kRunningIdx]] 40433 if (!request) { 40434 return -1 40435 } 40436 } 40437 40438 onHeaderField (buf) { 40439 const len = this.headers.length 40440 40441 if ((len & 1) === 0) { 40442 this.headers.push(buf) 40443 } else { 40444 this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) 40445 } 40446 40447 this.trackHeader(buf.length) 40448 } 40449 40450 onHeaderValue (buf) { 40451 let len = this.headers.length 40452 40453 if ((len & 1) === 1) { 40454 this.headers.push(buf) 40455 len += 1 40456 } else { 40457 this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) 40458 } 40459 40460 const key = this.headers[len - 2] 40461 if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { 40462 this.keepAlive += buf.toString() 40463 } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { 40464 this.connection += buf.toString() 40465 } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { 40466 this.contentLength += buf.toString() 40467 } 40468 40469 this.trackHeader(buf.length) 40470 } 40471 40472 trackHeader (len) { 40473 this.headersSize += len 40474 if (this.headersSize >= this.headersMaxSize) { 40475 util.destroy(this.socket, new HeadersOverflowError()) 40476 } 40477 } 40478 40479 onUpgrade (head) { 40480 const { upgrade, client, socket, headers, statusCode } = this 40481 40482 assert(upgrade) 40483 40484 const request = client[kQueue][client[kRunningIdx]] 40485 assert(request) 40486 40487 assert(!socket.destroyed) 40488 assert(socket === client[kSocket]) 40489 assert(!this.paused) 40490 assert(request.upgrade || request.method === 'CONNECT') 40491 40492 this.statusCode = null 40493 this.statusText = '' 40494 this.shouldKeepAlive = null 40495 40496 assert(this.headers.length % 2 === 0) 40497 this.headers = [] 40498 this.headersSize = 0 40499 40500 socket.unshift(head) 40501 40502 socket[kParser].destroy() 40503 socket[kParser] = null 40504 40505 socket[kClient] = null 40506 socket[kError] = null 40507 socket 40508 .removeListener('error', onSocketError) 40509 .removeListener('readable', onSocketReadable) 40510 .removeListener('end', onSocketEnd) 40511 .removeListener('close', onSocketClose) 40512 40513 client[kSocket] = null 40514 client[kQueue][client[kRunningIdx]++] = null 40515 client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) 40516 40517 try { 40518 request.onUpgrade(statusCode, headers, socket) 40519 } catch (err) { 40520 util.destroy(socket, err) 40521 } 40522 40523 resume(client) 40524 } 40525 40526 onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { 40527 const { client, socket, headers, statusText } = this 40528 40529 /* istanbul ignore next: difficult to make a test case for */ 40530 if (socket.destroyed) { 40531 return -1 40532 } 40533 40534 const request = client[kQueue][client[kRunningIdx]] 40535 40536 /* istanbul ignore next: difficult to make a test case for */ 40537 if (!request) { 40538 return -1 40539 } 40540 40541 assert(!this.upgrade) 40542 assert(this.statusCode < 200) 40543 40544 if (statusCode === 100) { 40545 util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) 40546 return -1 40547 } 40548 40549 /* this can only happen if server is misbehaving */ 40550 if (upgrade && !request.upgrade) { 40551 util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) 40552 return -1 40553 } 40554 40555 assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) 40556 40557 this.statusCode = statusCode 40558 this.shouldKeepAlive = ( 40559 shouldKeepAlive || 40560 // Override llhttp value which does not allow keepAlive for HEAD. 40561 (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') 40562 ) 40563 40564 if (this.statusCode >= 200) { 40565 const bodyTimeout = request.bodyTimeout != null 40566 ? request.bodyTimeout 40567 : client[kBodyTimeout] 40568 this.setTimeout(bodyTimeout, TIMEOUT_BODY) 40569 } else if (this.timeout) { 40570 // istanbul ignore else: only for jest 40571 if (this.timeout.refresh) { 40572 this.timeout.refresh() 40573 } 40574 } 40575 40576 if (request.method === 'CONNECT') { 40577 assert(client[kRunning] === 1) 40578 this.upgrade = true 40579 return 2 40580 } 40581 40582 if (upgrade) { 40583 assert(client[kRunning] === 1) 40584 this.upgrade = true 40585 return 2 40586 } 40587 40588 assert(this.headers.length % 2 === 0) 40589 this.headers = [] 40590 this.headersSize = 0 40591 40592 if (this.shouldKeepAlive && client[kPipelining]) { 40593 const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null 40594 40595 if (keepAliveTimeout != null) { 40596 const timeout = Math.min( 40597 keepAliveTimeout - client[kKeepAliveTimeoutThreshold], 40598 client[kKeepAliveMaxTimeout] 40599 ) 40600 if (timeout <= 0) { 40601 socket[kReset] = true 40602 } else { 40603 client[kKeepAliveTimeoutValue] = timeout 40604 } 40605 } else { 40606 client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] 40607 } 40608 } else { 40609 // Stop more requests from being dispatched. 40610 socket[kReset] = true 40611 } 40612 40613 const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false 40614 40615 if (request.aborted) { 40616 return -1 40617 } 40618 40619 if (request.method === 'HEAD') { 40620 return 1 40621 } 40622 40623 if (statusCode < 200) { 40624 return 1 40625 } 40626 40627 if (socket[kBlocking]) { 40628 socket[kBlocking] = false 40629 resume(client) 40630 } 40631 40632 return pause ? constants.ERROR.PAUSED : 0 40633 } 40634 40635 onBody (buf) { 40636 const { client, socket, statusCode, maxResponseSize } = this 40637 40638 if (socket.destroyed) { 40639 return -1 40640 } 40641 40642 const request = client[kQueue][client[kRunningIdx]] 40643 assert(request) 40644 40645 assert.strictEqual(this.timeoutType, TIMEOUT_BODY) 40646 if (this.timeout) { 40647 // istanbul ignore else: only for jest 40648 if (this.timeout.refresh) { 40649 this.timeout.refresh() 40650 } 40651 } 40652 40653 assert(statusCode >= 200) 40654 40655 if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { 40656 util.destroy(socket, new ResponseExceededMaxSizeError()) 40657 return -1 40658 } 40659 40660 this.bytesRead += buf.length 40661 40662 if (request.onData(buf) === false) { 40663 return constants.ERROR.PAUSED 40664 } 40665 } 40666 40667 onMessageComplete () { 40668 const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this 40669 40670 if (socket.destroyed && (!statusCode || shouldKeepAlive)) { 40671 return -1 40672 } 40673 40674 if (upgrade) { 40675 return 40676 } 40677 40678 const request = client[kQueue][client[kRunningIdx]] 40679 assert(request) 40680 40681 assert(statusCode >= 100) 40682 40683 this.statusCode = null 40684 this.statusText = '' 40685 this.bytesRead = 0 40686 this.contentLength = '' 40687 this.keepAlive = '' 40688 this.connection = '' 40689 40690 assert(this.headers.length % 2 === 0) 40691 this.headers = [] 40692 this.headersSize = 0 40693 40694 if (statusCode < 200) { 40695 return 40696 } 40697 40698 /* istanbul ignore next: should be handled by llhttp? */ 40699 if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { 40700 util.destroy(socket, new ResponseContentLengthMismatchError()) 40701 return -1 40702 } 40703 40704 request.onComplete(headers) 40705 40706 client[kQueue][client[kRunningIdx]++] = null 40707 40708 if (socket[kWriting]) { 40709 assert.strictEqual(client[kRunning], 0) 40710 // Response completed before request. 40711 util.destroy(socket, new InformationalError('reset')) 40712 return constants.ERROR.PAUSED 40713 } else if (!shouldKeepAlive) { 40714 util.destroy(socket, new InformationalError('reset')) 40715 return constants.ERROR.PAUSED 40716 } else if (socket[kReset] && client[kRunning] === 0) { 40717 // Destroy socket once all requests have completed. 40718 // The request at the tail of the pipeline is the one 40719 // that requested reset and no further requests should 40720 // have been queued since then. 40721 util.destroy(socket, new InformationalError('reset')) 40722 return constants.ERROR.PAUSED 40723 } else if (client[kPipelining] === 1) { 40724 // We must wait a full event loop cycle to reuse this socket to make sure 40725 // that non-spec compliant servers are not closing the connection even if they 40726 // said they won't. 40727 setImmediate(resume, client) 40728 } else { 40729 resume(client) 40730 } 40731 } 40732 } 40733 40734 function onParserTimeout (parser) { 40735 const { socket, timeoutType, client } = parser 40736 40737 /* istanbul ignore else */ 40738 if (timeoutType === TIMEOUT_HEADERS) { 40739 if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { 40740 assert(!parser.paused, 'cannot be paused while waiting for headers') 40741 util.destroy(socket, new HeadersTimeoutError()) 40742 } 40743 } else if (timeoutType === TIMEOUT_BODY) { 40744 if (!parser.paused) { 40745 util.destroy(socket, new BodyTimeoutError()) 40746 } 40747 } else if (timeoutType === TIMEOUT_IDLE) { 40748 assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) 40749 util.destroy(socket, new InformationalError('socket idle timeout')) 40750 } 40751 } 40752 40753 function onSocketReadable () { 40754 const { [kParser]: parser } = this 40755 if (parser) { 40756 parser.readMore() 40757 } 40758 } 40759 40760 function onSocketError (err) { 40761 const { [kClient]: client, [kParser]: parser } = this 40762 40763 assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') 40764 40765 if (client[kHTTPConnVersion] !== 'h2') { 40766 // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded 40767 // to the user. 40768 if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { 40769 // We treat all incoming data so for as a valid response. 40770 parser.onMessageComplete() 40771 return 40772 } 40773 } 40774 40775 this[kError] = err 40776 40777 onError(this[kClient], err) 40778 } 40779 40780 function onError (client, err) { 40781 if ( 40782 client[kRunning] === 0 && 40783 err.code !== 'UND_ERR_INFO' && 40784 err.code !== 'UND_ERR_SOCKET' 40785 ) { 40786 // Error is not caused by running request and not a recoverable 40787 // socket error. 40788 40789 assert(client[kPendingIdx] === client[kRunningIdx]) 40790 40791 const requests = client[kQueue].splice(client[kRunningIdx]) 40792 for (let i = 0; i < requests.length; i++) { 40793 const request = requests[i] 40794 errorRequest(client, request, err) 40795 } 40796 assert(client[kSize] === 0) 40797 } 40798 } 40799 40800 function onSocketEnd () { 40801 const { [kParser]: parser, [kClient]: client } = this 40802 40803 if (client[kHTTPConnVersion] !== 'h2') { 40804 if (parser.statusCode && !parser.shouldKeepAlive) { 40805 // We treat all incoming data so far as a valid response. 40806 parser.onMessageComplete() 40807 return 40808 } 40809 } 40810 40811 util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) 40812 } 40813 40814 function onSocketClose () { 40815 const { [kClient]: client, [kParser]: parser } = this 40816 40817 if (client[kHTTPConnVersion] === 'h1' && parser) { 40818 if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { 40819 // We treat all incoming data so far as a valid response. 40820 parser.onMessageComplete() 40821 } 40822 40823 this[kParser].destroy() 40824 this[kParser] = null 40825 } 40826 40827 const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) 40828 40829 client[kSocket] = null 40830 40831 if (client.destroyed) { 40832 assert(client[kPending] === 0) 40833 40834 // Fail entire queue. 40835 const requests = client[kQueue].splice(client[kRunningIdx]) 40836 for (let i = 0; i < requests.length; i++) { 40837 const request = requests[i] 40838 errorRequest(client, request, err) 40839 } 40840 } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { 40841 // Fail head of pipeline. 40842 const request = client[kQueue][client[kRunningIdx]] 40843 client[kQueue][client[kRunningIdx]++] = null 40844 40845 errorRequest(client, request, err) 40846 } 40847 40848 client[kPendingIdx] = client[kRunningIdx] 40849 40850 assert(client[kRunning] === 0) 40851 40852 client.emit('disconnect', client[kUrl], [client], err) 40853 40854 resume(client) 40855 } 40856 40857 async function connect (client) { 40858 assert(!client[kConnecting]) 40859 assert(!client[kSocket]) 40860 40861 let { host, hostname, protocol, port } = client[kUrl] 40862 40863 // Resolve ipv6 40864 if (hostname[0] === '[') { 40865 const idx = hostname.indexOf(']') 40866 40867 assert(idx !== -1) 40868 const ip = hostname.substring(1, idx) 40869 40870 assert(net.isIP(ip)) 40871 hostname = ip 40872 } 40873 40874 client[kConnecting] = true 40875 40876 if (channels.beforeConnect.hasSubscribers) { 40877 channels.beforeConnect.publish({ 40878 connectParams: { 40879 host, 40880 hostname, 40881 protocol, 40882 port, 40883 servername: client[kServerName], 40884 localAddress: client[kLocalAddress] 40885 }, 40886 connector: client[kConnector] 40887 }) 40888 } 40889 40890 try { 40891 const socket = await new Promise((resolve, reject) => { 40892 client[kConnector]({ 40893 host, 40894 hostname, 40895 protocol, 40896 port, 40897 servername: client[kServerName], 40898 localAddress: client[kLocalAddress] 40899 }, (err, socket) => { 40900 if (err) { 40901 reject(err) 40902 } else { 40903 resolve(socket) 40904 } 40905 }) 40906 }) 40907 40908 if (client.destroyed) { 40909 util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) 40910 return 40911 } 40912 40913 client[kConnecting] = false 40914 40915 assert(socket) 40916 40917 const isH2 = socket.alpnProtocol === 'h2' 40918 if (isH2) { 40919 if (!h2ExperimentalWarned) { 40920 h2ExperimentalWarned = true 40921 process.emitWarning('H2 support is experimental, expect them to change at any time.', { 40922 code: 'UNDICI-H2' 40923 }) 40924 } 40925 40926 const session = http2.connect(client[kUrl], { 40927 createConnection: () => socket, 40928 peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams 40929 }) 40930 40931 client[kHTTPConnVersion] = 'h2' 40932 session[kClient] = client 40933 session[kSocket] = socket 40934 session.on('error', onHttp2SessionError) 40935 session.on('frameError', onHttp2FrameError) 40936 session.on('end', onHttp2SessionEnd) 40937 session.on('goaway', onHTTP2GoAway) 40938 session.on('close', onSocketClose) 40939 session.unref() 40940 40941 client[kHTTP2Session] = session 40942 socket[kHTTP2Session] = session 40943 } else { 40944 if (!llhttpInstance) { 40945 llhttpInstance = await llhttpPromise 40946 llhttpPromise = null 40947 } 40948 40949 socket[kNoRef] = false 40950 socket[kWriting] = false 40951 socket[kReset] = false 40952 socket[kBlocking] = false 40953 socket[kParser] = new Parser(client, socket, llhttpInstance) 40954 } 40955 40956 socket[kCounter] = 0 40957 socket[kMaxRequests] = client[kMaxRequests] 40958 socket[kClient] = client 40959 socket[kError] = null 40960 40961 socket 40962 .on('error', onSocketError) 40963 .on('readable', onSocketReadable) 40964 .on('end', onSocketEnd) 40965 .on('close', onSocketClose) 40966 40967 client[kSocket] = socket 40968 40969 if (channels.connected.hasSubscribers) { 40970 channels.connected.publish({ 40971 connectParams: { 40972 host, 40973 hostname, 40974 protocol, 40975 port, 40976 servername: client[kServerName], 40977 localAddress: client[kLocalAddress] 40978 }, 40979 connector: client[kConnector], 40980 socket 40981 }) 40982 } 40983 client.emit('connect', client[kUrl], [client]) 40984 } catch (err) { 40985 if (client.destroyed) { 40986 return 40987 } 40988 40989 client[kConnecting] = false 40990 40991 if (channels.connectError.hasSubscribers) { 40992 channels.connectError.publish({ 40993 connectParams: { 40994 host, 40995 hostname, 40996 protocol, 40997 port, 40998 servername: client[kServerName], 40999 localAddress: client[kLocalAddress] 41000 }, 41001 connector: client[kConnector], 41002 error: err 41003 }) 41004 } 41005 41006 if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { 41007 assert(client[kRunning] === 0) 41008 while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { 41009 const request = client[kQueue][client[kPendingIdx]++] 41010 errorRequest(client, request, err) 41011 } 41012 } else { 41013 onError(client, err) 41014 } 41015 41016 client.emit('connectionError', client[kUrl], [client], err) 41017 } 41018 41019 resume(client) 41020 } 41021 41022 function emitDrain (client) { 41023 client[kNeedDrain] = 0 41024 client.emit('drain', client[kUrl], [client]) 41025 } 41026 41027 function resume (client, sync) { 41028 if (client[kResuming] === 2) { 41029 return 41030 } 41031 41032 client[kResuming] = 2 41033 41034 _resume(client, sync) 41035 client[kResuming] = 0 41036 41037 if (client[kRunningIdx] > 256) { 41038 client[kQueue].splice(0, client[kRunningIdx]) 41039 client[kPendingIdx] -= client[kRunningIdx] 41040 client[kRunningIdx] = 0 41041 } 41042 } 41043 41044 function _resume (client, sync) { 41045 while (true) { 41046 if (client.destroyed) { 41047 assert(client[kPending] === 0) 41048 return 41049 } 41050 41051 if (client[kClosedResolve] && !client[kSize]) { 41052 client[kClosedResolve]() 41053 client[kClosedResolve] = null 41054 return 41055 } 41056 41057 const socket = client[kSocket] 41058 41059 if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { 41060 if (client[kSize] === 0) { 41061 if (!socket[kNoRef] && socket.unref) { 41062 socket.unref() 41063 socket[kNoRef] = true 41064 } 41065 } else if (socket[kNoRef] && socket.ref) { 41066 socket.ref() 41067 socket[kNoRef] = false 41068 } 41069 41070 if (client[kSize] === 0) { 41071 if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { 41072 socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) 41073 } 41074 } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { 41075 if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { 41076 const request = client[kQueue][client[kRunningIdx]] 41077 const headersTimeout = request.headersTimeout != null 41078 ? request.headersTimeout 41079 : client[kHeadersTimeout] 41080 socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) 41081 } 41082 } 41083 } 41084 41085 if (client[kBusy]) { 41086 client[kNeedDrain] = 2 41087 } else if (client[kNeedDrain] === 2) { 41088 if (sync) { 41089 client[kNeedDrain] = 1 41090 process.nextTick(emitDrain, client) 41091 } else { 41092 emitDrain(client) 41093 } 41094 continue 41095 } 41096 41097 if (client[kPending] === 0) { 41098 return 41099 } 41100 41101 if (client[kRunning] >= (client[kPipelining] || 1)) { 41102 return 41103 } 41104 41105 const request = client[kQueue][client[kPendingIdx]] 41106 41107 if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { 41108 if (client[kRunning] > 0) { 41109 return 41110 } 41111 41112 client[kServerName] = request.servername 41113 41114 if (socket && socket.servername !== request.servername) { 41115 util.destroy(socket, new InformationalError('servername changed')) 41116 return 41117 } 41118 } 41119 41120 if (client[kConnecting]) { 41121 return 41122 } 41123 41124 if (!socket && !client[kHTTP2Session]) { 41125 connect(client) 41126 return 41127 } 41128 41129 if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { 41130 return 41131 } 41132 41133 if (client[kRunning] > 0 && !request.idempotent) { 41134 // Non-idempotent request cannot be retried. 41135 // Ensure that no other requests are inflight and 41136 // could cause failure. 41137 return 41138 } 41139 41140 if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { 41141 // Don't dispatch an upgrade until all preceding requests have completed. 41142 // A misbehaving server might upgrade the connection before all pipelined 41143 // request has completed. 41144 return 41145 } 41146 41147 if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && 41148 (util.isStream(request.body) || util.isAsyncIterable(request.body))) { 41149 // Request with stream or iterator body can error while other requests 41150 // are inflight and indirectly error those as well. 41151 // Ensure this doesn't happen by waiting for inflight 41152 // to complete before dispatching. 41153 41154 // Request with stream or iterator body cannot be retried. 41155 // Ensure that no other requests are inflight and 41156 // could cause failure. 41157 return 41158 } 41159 41160 if (!request.aborted && write(client, request)) { 41161 client[kPendingIdx]++ 41162 } else { 41163 client[kQueue].splice(client[kPendingIdx], 1) 41164 } 41165 } 41166 } 41167 41168 // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 41169 function shouldSendContentLength (method) { 41170 return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' 41171 } 41172 41173 function write (client, request) { 41174 if (client[kHTTPConnVersion] === 'h2') { 41175 writeH2(client, client[kHTTP2Session], request) 41176 return 41177 } 41178 41179 const { body, method, path, host, upgrade, headers, blocking, reset } = request 41180 41181 // https://tools.ietf.org/html/rfc7231#section-4.3.1 41182 // https://tools.ietf.org/html/rfc7231#section-4.3.2 41183 // https://tools.ietf.org/html/rfc7231#section-4.3.5 41184 41185 // Sending a payload body on a request that does not 41186 // expect it can cause undefined behavior on some 41187 // servers and corrupt connection state. Do not 41188 // re-use the connection for further requests. 41189 41190 const expectsPayload = ( 41191 method === 'PUT' || 41192 method === 'POST' || 41193 method === 'PATCH' 41194 ) 41195 41196 if (body && typeof body.read === 'function') { 41197 // Try to read EOF in order to get length. 41198 body.read(0) 41199 } 41200 41201 const bodyLength = util.bodyLength(body) 41202 41203 let contentLength = bodyLength 41204 41205 if (contentLength === null) { 41206 contentLength = request.contentLength 41207 } 41208 41209 if (contentLength === 0 && !expectsPayload) { 41210 // https://tools.ietf.org/html/rfc7230#section-3.3.2 41211 // A user agent SHOULD NOT send a Content-Length header field when 41212 // the request message does not contain a payload body and the method 41213 // semantics do not anticipate such a body. 41214 41215 contentLength = null 41216 } 41217 41218 // https://github.com/nodejs/undici/issues/2046 41219 // A user agent may send a Content-Length header with 0 value, this should be allowed. 41220 if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { 41221 if (client[kStrictContentLength]) { 41222 errorRequest(client, request, new RequestContentLengthMismatchError()) 41223 return false 41224 } 41225 41226 process.emitWarning(new RequestContentLengthMismatchError()) 41227 } 41228 41229 const socket = client[kSocket] 41230 41231 try { 41232 request.onConnect((err) => { 41233 if (request.aborted || request.completed) { 41234 return 41235 } 41236 41237 errorRequest(client, request, err || new RequestAbortedError()) 41238 41239 util.destroy(socket, new InformationalError('aborted')) 41240 }) 41241 } catch (err) { 41242 errorRequest(client, request, err) 41243 } 41244 41245 if (request.aborted) { 41246 return false 41247 } 41248 41249 if (method === 'HEAD') { 41250 // https://github.com/mcollina/undici/issues/258 41251 // Close after a HEAD request to interop with misbehaving servers 41252 // that may send a body in the response. 41253 41254 socket[kReset] = true 41255 } 41256 41257 if (upgrade || method === 'CONNECT') { 41258 // On CONNECT or upgrade, block pipeline from dispatching further 41259 // requests on this connection. 41260 41261 socket[kReset] = true 41262 } 41263 41264 if (reset != null) { 41265 socket[kReset] = reset 41266 } 41267 41268 if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { 41269 socket[kReset] = true 41270 } 41271 41272 if (blocking) { 41273 socket[kBlocking] = true 41274 } 41275 41276 let header = `${method} ${path} HTTP/1.1\r\n` 41277 41278 if (typeof host === 'string') { 41279 header += `host: ${host}\r\n` 41280 } else { 41281 header += client[kHostHeader] 41282 } 41283 41284 if (upgrade) { 41285 header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` 41286 } else if (client[kPipelining] && !socket[kReset]) { 41287 header += 'connection: keep-alive\r\n' 41288 } else { 41289 header += 'connection: close\r\n' 41290 } 41291 41292 if (headers) { 41293 header += headers 41294 } 41295 41296 if (channels.sendHeaders.hasSubscribers) { 41297 channels.sendHeaders.publish({ request, headers: header, socket }) 41298 } 41299 41300 /* istanbul ignore else: assertion */ 41301 if (!body || bodyLength === 0) { 41302 if (contentLength === 0) { 41303 socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') 41304 } else { 41305 assert(contentLength === null, 'no body must not have content length') 41306 socket.write(`${header}\r\n`, 'latin1') 41307 } 41308 request.onRequestSent() 41309 } else if (util.isBuffer(body)) { 41310 assert(contentLength === body.byteLength, 'buffer body must have content length') 41311 41312 socket.cork() 41313 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') 41314 socket.write(body) 41315 socket.uncork() 41316 request.onBodySent(body) 41317 request.onRequestSent() 41318 if (!expectsPayload) { 41319 socket[kReset] = true 41320 } 41321 } else if (util.isBlobLike(body)) { 41322 if (typeof body.stream === 'function') { 41323 writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) 41324 } else { 41325 writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) 41326 } 41327 } else if (util.isStream(body)) { 41328 writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) 41329 } else if (util.isIterable(body)) { 41330 writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) 41331 } else { 41332 assert(false) 41333 } 41334 41335 return true 41336 } 41337 41338 function writeH2 (client, session, request) { 41339 const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request 41340 41341 let headers 41342 if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) 41343 else headers = reqHeaders 41344 41345 if (upgrade) { 41346 errorRequest(client, request, new Error('Upgrade not supported for H2')) 41347 return false 41348 } 41349 41350 try { 41351 // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? 41352 request.onConnect((err) => { 41353 if (request.aborted || request.completed) { 41354 return 41355 } 41356 41357 errorRequest(client, request, err || new RequestAbortedError()) 41358 }) 41359 } catch (err) { 41360 errorRequest(client, request, err) 41361 } 41362 41363 if (request.aborted) { 41364 return false 41365 } 41366 41367 /** @type {import('node:http2').ClientHttp2Stream} */ 41368 let stream 41369 const h2State = client[kHTTP2SessionState] 41370 41371 headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] 41372 headers[HTTP2_HEADER_METHOD] = method 41373 41374 if (method === 'CONNECT') { 41375 session.ref() 41376 // we are already connected, streams are pending, first request 41377 // will create a new stream. We trigger a request to create the stream and wait until 41378 // `ready` event is triggered 41379 // We disabled endStream to allow the user to write to the stream 41380 stream = session.request(headers, { endStream: false, signal }) 41381 41382 if (stream.id && !stream.pending) { 41383 request.onUpgrade(null, null, stream) 41384 ++h2State.openStreams 41385 } else { 41386 stream.once('ready', () => { 41387 request.onUpgrade(null, null, stream) 41388 ++h2State.openStreams 41389 }) 41390 } 41391 41392 stream.once('close', () => { 41393 h2State.openStreams -= 1 41394 // TODO(HTTP/2): unref only if current streams count is 0 41395 if (h2State.openStreams === 0) session.unref() 41396 }) 41397 41398 return true 41399 } 41400 41401 // https://tools.ietf.org/html/rfc7540#section-8.3 41402 // :path and :scheme headers must be omited when sending CONNECT 41403 41404 headers[HTTP2_HEADER_PATH] = path 41405 headers[HTTP2_HEADER_SCHEME] = 'https' 41406 41407 // https://tools.ietf.org/html/rfc7231#section-4.3.1 41408 // https://tools.ietf.org/html/rfc7231#section-4.3.2 41409 // https://tools.ietf.org/html/rfc7231#section-4.3.5 41410 41411 // Sending a payload body on a request that does not 41412 // expect it can cause undefined behavior on some 41413 // servers and corrupt connection state. Do not 41414 // re-use the connection for further requests. 41415 41416 const expectsPayload = ( 41417 method === 'PUT' || 41418 method === 'POST' || 41419 method === 'PATCH' 41420 ) 41421 41422 if (body && typeof body.read === 'function') { 41423 // Try to read EOF in order to get length. 41424 body.read(0) 41425 } 41426 41427 let contentLength = util.bodyLength(body) 41428 41429 if (contentLength == null) { 41430 contentLength = request.contentLength 41431 } 41432 41433 if (contentLength === 0 || !expectsPayload) { 41434 // https://tools.ietf.org/html/rfc7230#section-3.3.2 41435 // A user agent SHOULD NOT send a Content-Length header field when 41436 // the request message does not contain a payload body and the method 41437 // semantics do not anticipate such a body. 41438 41439 contentLength = null 41440 } 41441 41442 // https://github.com/nodejs/undici/issues/2046 41443 // A user agent may send a Content-Length header with 0 value, this should be allowed. 41444 if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { 41445 if (client[kStrictContentLength]) { 41446 errorRequest(client, request, new RequestContentLengthMismatchError()) 41447 return false 41448 } 41449 41450 process.emitWarning(new RequestContentLengthMismatchError()) 41451 } 41452 41453 if (contentLength != null) { 41454 assert(body, 'no body must not have content length') 41455 headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` 41456 } 41457 41458 session.ref() 41459 41460 const shouldEndStream = method === 'GET' || method === 'HEAD' 41461 if (expectContinue) { 41462 headers[HTTP2_HEADER_EXPECT] = '100-continue' 41463 stream = session.request(headers, { endStream: shouldEndStream, signal }) 41464 41465 stream.once('continue', writeBodyH2) 41466 } else { 41467 stream = session.request(headers, { 41468 endStream: shouldEndStream, 41469 signal 41470 }) 41471 writeBodyH2() 41472 } 41473 41474 // Increment counter as we have new several streams open 41475 ++h2State.openStreams 41476 41477 stream.once('response', headers => { 41478 const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers 41479 41480 if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { 41481 stream.pause() 41482 } 41483 }) 41484 41485 stream.once('end', () => { 41486 request.onComplete([]) 41487 }) 41488 41489 stream.on('data', (chunk) => { 41490 if (request.onData(chunk) === false) { 41491 stream.pause() 41492 } 41493 }) 41494 41495 stream.once('close', () => { 41496 h2State.openStreams -= 1 41497 // TODO(HTTP/2): unref only if current streams count is 0 41498 if (h2State.openStreams === 0) { 41499 session.unref() 41500 } 41501 }) 41502 41503 stream.once('error', function (err) { 41504 if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { 41505 h2State.streams -= 1 41506 util.destroy(stream, err) 41507 } 41508 }) 41509 41510 stream.once('frameError', (type, code) => { 41511 const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) 41512 errorRequest(client, request, err) 41513 41514 if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { 41515 h2State.streams -= 1 41516 util.destroy(stream, err) 41517 } 41518 }) 41519 41520 // stream.on('aborted', () => { 41521 // // TODO(HTTP/2): Support aborted 41522 // }) 41523 41524 // stream.on('timeout', () => { 41525 // // TODO(HTTP/2): Support timeout 41526 // }) 41527 41528 // stream.on('push', headers => { 41529 // // TODO(HTTP/2): Suppor push 41530 // }) 41531 41532 // stream.on('trailers', headers => { 41533 // // TODO(HTTP/2): Support trailers 41534 // }) 41535 41536 return true 41537 41538 function writeBodyH2 () { 41539 /* istanbul ignore else: assertion */ 41540 if (!body) { 41541 request.onRequestSent() 41542 } else if (util.isBuffer(body)) { 41543 assert(contentLength === body.byteLength, 'buffer body must have content length') 41544 stream.cork() 41545 stream.write(body) 41546 stream.uncork() 41547 stream.end() 41548 request.onBodySent(body) 41549 request.onRequestSent() 41550 } else if (util.isBlobLike(body)) { 41551 if (typeof body.stream === 'function') { 41552 writeIterable({ 41553 client, 41554 request, 41555 contentLength, 41556 h2stream: stream, 41557 expectsPayload, 41558 body: body.stream(), 41559 socket: client[kSocket], 41560 header: '' 41561 }) 41562 } else { 41563 writeBlob({ 41564 body, 41565 client, 41566 request, 41567 contentLength, 41568 expectsPayload, 41569 h2stream: stream, 41570 header: '', 41571 socket: client[kSocket] 41572 }) 41573 } 41574 } else if (util.isStream(body)) { 41575 writeStream({ 41576 body, 41577 client, 41578 request, 41579 contentLength, 41580 expectsPayload, 41581 socket: client[kSocket], 41582 h2stream: stream, 41583 header: '' 41584 }) 41585 } else if (util.isIterable(body)) { 41586 writeIterable({ 41587 body, 41588 client, 41589 request, 41590 contentLength, 41591 expectsPayload, 41592 header: '', 41593 h2stream: stream, 41594 socket: client[kSocket] 41595 }) 41596 } else { 41597 assert(false) 41598 } 41599 } 41600 } 41601 41602 function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { 41603 assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') 41604 41605 if (client[kHTTPConnVersion] === 'h2') { 41606 // For HTTP/2, is enough to pipe the stream 41607 const pipe = pipeline( 41608 body, 41609 h2stream, 41610 (err) => { 41611 if (err) { 41612 util.destroy(body, err) 41613 util.destroy(h2stream, err) 41614 } else { 41615 request.onRequestSent() 41616 } 41617 } 41618 ) 41619 41620 pipe.on('data', onPipeData) 41621 pipe.once('end', () => { 41622 pipe.removeListener('data', onPipeData) 41623 util.destroy(pipe) 41624 }) 41625 41626 function onPipeData (chunk) { 41627 request.onBodySent(chunk) 41628 } 41629 41630 return 41631 } 41632 41633 let finished = false 41634 41635 const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) 41636 41637 const onData = function (chunk) { 41638 if (finished) { 41639 return 41640 } 41641 41642 try { 41643 if (!writer.write(chunk) && this.pause) { 41644 this.pause() 41645 } 41646 } catch (err) { 41647 util.destroy(this, err) 41648 } 41649 } 41650 const onDrain = function () { 41651 if (finished) { 41652 return 41653 } 41654 41655 if (body.resume) { 41656 body.resume() 41657 } 41658 } 41659 const onAbort = function () { 41660 if (finished) { 41661 return 41662 } 41663 const err = new RequestAbortedError() 41664 queueMicrotask(() => onFinished(err)) 41665 } 41666 const onFinished = function (err) { 41667 if (finished) { 41668 return 41669 } 41670 41671 finished = true 41672 41673 assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) 41674 41675 socket 41676 .off('drain', onDrain) 41677 .off('error', onFinished) 41678 41679 body 41680 .removeListener('data', onData) 41681 .removeListener('end', onFinished) 41682 .removeListener('error', onFinished) 41683 .removeListener('close', onAbort) 41684 41685 if (!err) { 41686 try { 41687 writer.end() 41688 } catch (er) { 41689 err = er 41690 } 41691 } 41692 41693 writer.destroy(err) 41694 41695 if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { 41696 util.destroy(body, err) 41697 } else { 41698 util.destroy(body) 41699 } 41700 } 41701 41702 body 41703 .on('data', onData) 41704 .on('end', onFinished) 41705 .on('error', onFinished) 41706 .on('close', onAbort) 41707 41708 if (body.resume) { 41709 body.resume() 41710 } 41711 41712 socket 41713 .on('drain', onDrain) 41714 .on('error', onFinished) 41715 } 41716 41717 async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { 41718 assert(contentLength === body.size, 'blob body must have content length') 41719 41720 const isH2 = client[kHTTPConnVersion] === 'h2' 41721 try { 41722 if (contentLength != null && contentLength !== body.size) { 41723 throw new RequestContentLengthMismatchError() 41724 } 41725 41726 const buffer = Buffer.from(await body.arrayBuffer()) 41727 41728 if (isH2) { 41729 h2stream.cork() 41730 h2stream.write(buffer) 41731 h2stream.uncork() 41732 } else { 41733 socket.cork() 41734 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') 41735 socket.write(buffer) 41736 socket.uncork() 41737 } 41738 41739 request.onBodySent(buffer) 41740 request.onRequestSent() 41741 41742 if (!expectsPayload) { 41743 socket[kReset] = true 41744 } 41745 41746 resume(client) 41747 } catch (err) { 41748 util.destroy(isH2 ? h2stream : socket, err) 41749 } 41750 } 41751 41752 async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { 41753 assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') 41754 41755 let callback = null 41756 function onDrain () { 41757 if (callback) { 41758 const cb = callback 41759 callback = null 41760 cb() 41761 } 41762 } 41763 41764 const waitForDrain = () => new Promise((resolve, reject) => { 41765 assert(callback === null) 41766 41767 if (socket[kError]) { 41768 reject(socket[kError]) 41769 } else { 41770 callback = resolve 41771 } 41772 }) 41773 41774 if (client[kHTTPConnVersion] === 'h2') { 41775 h2stream 41776 .on('close', onDrain) 41777 .on('drain', onDrain) 41778 41779 try { 41780 // It's up to the user to somehow abort the async iterable. 41781 for await (const chunk of body) { 41782 if (socket[kError]) { 41783 throw socket[kError] 41784 } 41785 41786 const res = h2stream.write(chunk) 41787 request.onBodySent(chunk) 41788 if (!res) { 41789 await waitForDrain() 41790 } 41791 } 41792 } catch (err) { 41793 h2stream.destroy(err) 41794 } finally { 41795 request.onRequestSent() 41796 h2stream.end() 41797 h2stream 41798 .off('close', onDrain) 41799 .off('drain', onDrain) 41800 } 41801 41802 return 41803 } 41804 41805 socket 41806 .on('close', onDrain) 41807 .on('drain', onDrain) 41808 41809 const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) 41810 try { 41811 // It's up to the user to somehow abort the async iterable. 41812 for await (const chunk of body) { 41813 if (socket[kError]) { 41814 throw socket[kError] 41815 } 41816 41817 if (!writer.write(chunk)) { 41818 await waitForDrain() 41819 } 41820 } 41821 41822 writer.end() 41823 } catch (err) { 41824 writer.destroy(err) 41825 } finally { 41826 socket 41827 .off('close', onDrain) 41828 .off('drain', onDrain) 41829 } 41830 } 41831 41832 class AsyncWriter { 41833 constructor ({ socket, request, contentLength, client, expectsPayload, header }) { 41834 this.socket = socket 41835 this.request = request 41836 this.contentLength = contentLength 41837 this.client = client 41838 this.bytesWritten = 0 41839 this.expectsPayload = expectsPayload 41840 this.header = header 41841 41842 socket[kWriting] = true 41843 } 41844 41845 write (chunk) { 41846 const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this 41847 41848 if (socket[kError]) { 41849 throw socket[kError] 41850 } 41851 41852 if (socket.destroyed) { 41853 return false 41854 } 41855 41856 const len = Buffer.byteLength(chunk) 41857 if (!len) { 41858 return true 41859 } 41860 41861 // We should defer writing chunks. 41862 if (contentLength !== null && bytesWritten + len > contentLength) { 41863 if (client[kStrictContentLength]) { 41864 throw new RequestContentLengthMismatchError() 41865 } 41866 41867 process.emitWarning(new RequestContentLengthMismatchError()) 41868 } 41869 41870 socket.cork() 41871 41872 if (bytesWritten === 0) { 41873 if (!expectsPayload) { 41874 socket[kReset] = true 41875 } 41876 41877 if (contentLength === null) { 41878 socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') 41879 } else { 41880 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') 41881 } 41882 } 41883 41884 if (contentLength === null) { 41885 socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') 41886 } 41887 41888 this.bytesWritten += len 41889 41890 const ret = socket.write(chunk) 41891 41892 socket.uncork() 41893 41894 request.onBodySent(chunk) 41895 41896 if (!ret) { 41897 if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { 41898 // istanbul ignore else: only for jest 41899 if (socket[kParser].timeout.refresh) { 41900 socket[kParser].timeout.refresh() 41901 } 41902 } 41903 } 41904 41905 return ret 41906 } 41907 41908 end () { 41909 const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this 41910 request.onRequestSent() 41911 41912 socket[kWriting] = false 41913 41914 if (socket[kError]) { 41915 throw socket[kError] 41916 } 41917 41918 if (socket.destroyed) { 41919 return 41920 } 41921 41922 if (bytesWritten === 0) { 41923 if (expectsPayload) { 41924 // https://tools.ietf.org/html/rfc7230#section-3.3.2 41925 // A user agent SHOULD send a Content-Length in a request message when 41926 // no Transfer-Encoding is sent and the request method defines a meaning 41927 // for an enclosed payload body. 41928 41929 socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') 41930 } else { 41931 socket.write(`${header}\r\n`, 'latin1') 41932 } 41933 } else if (contentLength === null) { 41934 socket.write('\r\n0\r\n\r\n', 'latin1') 41935 } 41936 41937 if (contentLength !== null && bytesWritten !== contentLength) { 41938 if (client[kStrictContentLength]) { 41939 throw new RequestContentLengthMismatchError() 41940 } else { 41941 process.emitWarning(new RequestContentLengthMismatchError()) 41942 } 41943 } 41944 41945 if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { 41946 // istanbul ignore else: only for jest 41947 if (socket[kParser].timeout.refresh) { 41948 socket[kParser].timeout.refresh() 41949 } 41950 } 41951 41952 resume(client) 41953 } 41954 41955 destroy (err) { 41956 const { socket, client } = this 41957 41958 socket[kWriting] = false 41959 41960 if (err) { 41961 assert(client[kRunning] <= 1, 'pipeline should only contain this request') 41962 util.destroy(socket, err) 41963 } 41964 } 41965 } 41966 41967 function errorRequest (client, request, err) { 41968 try { 41969 request.onError(err) 41970 assert(request.aborted) 41971 } catch (err) { 41972 client.emit('error', err) 41973 } 41974 } 41975 41976 module.exports = Client 41977 41978 41979 /***/ }), 41980 41981 /***/ 6436: 41982 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 41983 41984 "use strict"; 41985 41986 41987 /* istanbul ignore file: only for Node 12 */ 41988 41989 const { kConnected, kSize } = __nccwpck_require__(2785) 41990 41991 class CompatWeakRef { 41992 constructor (value) { 41993 this.value = value 41994 } 41995 41996 deref () { 41997 return this.value[kConnected] === 0 && this.value[kSize] === 0 41998 ? undefined 41999 : this.value 42000 } 42001 } 42002 42003 class CompatFinalizer { 42004 constructor (finalizer) { 42005 this.finalizer = finalizer 42006 } 42007 42008 register (dispatcher, key) { 42009 if (dispatcher.on) { 42010 dispatcher.on('disconnect', () => { 42011 if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { 42012 this.finalizer(key) 42013 } 42014 }) 42015 } 42016 } 42017 } 42018 42019 module.exports = function () { 42020 // FIXME: remove workaround when the Node bug is fixed 42021 // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 42022 if (process.env.NODE_V8_COVERAGE) { 42023 return { 42024 WeakRef: CompatWeakRef, 42025 FinalizationRegistry: CompatFinalizer 42026 } 42027 } 42028 return { 42029 WeakRef: global.WeakRef || CompatWeakRef, 42030 FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer 42031 } 42032 } 42033 42034 42035 /***/ }), 42036 42037 /***/ 663: 42038 /***/ ((module) => { 42039 42040 "use strict"; 42041 42042 42043 // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size 42044 const maxAttributeValueSize = 1024 42045 42046 // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size 42047 const maxNameValuePairSize = 4096 42048 42049 module.exports = { 42050 maxAttributeValueSize, 42051 maxNameValuePairSize 42052 } 42053 42054 42055 /***/ }), 42056 42057 /***/ 1724: 42058 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 42059 42060 "use strict"; 42061 42062 42063 const { parseSetCookie } = __nccwpck_require__(4408) 42064 const { stringify, getHeadersList } = __nccwpck_require__(3121) 42065 const { webidl } = __nccwpck_require__(1744) 42066 const { Headers } = __nccwpck_require__(554) 42067 42068 /** 42069 * @typedef {Object} Cookie 42070 * @property {string} name 42071 * @property {string} value 42072 * @property {Date|number|undefined} expires 42073 * @property {number|undefined} maxAge 42074 * @property {string|undefined} domain 42075 * @property {string|undefined} path 42076 * @property {boolean|undefined} secure 42077 * @property {boolean|undefined} httpOnly 42078 * @property {'Strict'|'Lax'|'None'} sameSite 42079 * @property {string[]} unparsed 42080 */ 42081 42082 /** 42083 * @param {Headers} headers 42084 * @returns {Record<string, string>} 42085 */ 42086 function getCookies (headers) { 42087 webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) 42088 42089 webidl.brandCheck(headers, Headers, { strict: false }) 42090 42091 const cookie = headers.get('cookie') 42092 const out = {} 42093 42094 if (!cookie) { 42095 return out 42096 } 42097 42098 for (const piece of cookie.split(';')) { 42099 const [name, ...value] = piece.split('=') 42100 42101 out[name.trim()] = value.join('=') 42102 } 42103 42104 return out 42105 } 42106 42107 /** 42108 * @param {Headers} headers 42109 * @param {string} name 42110 * @param {{ path?: string, domain?: string }|undefined} attributes 42111 * @returns {void} 42112 */ 42113 function deleteCookie (headers, name, attributes) { 42114 webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) 42115 42116 webidl.brandCheck(headers, Headers, { strict: false }) 42117 42118 name = webidl.converters.DOMString(name) 42119 attributes = webidl.converters.DeleteCookieAttributes(attributes) 42120 42121 // Matches behavior of 42122 // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 42123 setCookie(headers, { 42124 name, 42125 value: '', 42126 expires: new Date(0), 42127 ...attributes 42128 }) 42129 } 42130 42131 /** 42132 * @param {Headers} headers 42133 * @returns {Cookie[]} 42134 */ 42135 function getSetCookies (headers) { 42136 webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) 42137 42138 webidl.brandCheck(headers, Headers, { strict: false }) 42139 42140 const cookies = getHeadersList(headers).cookies 42141 42142 if (!cookies) { 42143 return [] 42144 } 42145 42146 // In older versions of undici, cookies is a list of name:value. 42147 return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) 42148 } 42149 42150 /** 42151 * @param {Headers} headers 42152 * @param {Cookie} cookie 42153 * @returns {void} 42154 */ 42155 function setCookie (headers, cookie) { 42156 webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) 42157 42158 webidl.brandCheck(headers, Headers, { strict: false }) 42159 42160 cookie = webidl.converters.Cookie(cookie) 42161 42162 const str = stringify(cookie) 42163 42164 if (str) { 42165 headers.append('Set-Cookie', stringify(cookie)) 42166 } 42167 } 42168 42169 webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ 42170 { 42171 converter: webidl.nullableConverter(webidl.converters.DOMString), 42172 key: 'path', 42173 defaultValue: null 42174 }, 42175 { 42176 converter: webidl.nullableConverter(webidl.converters.DOMString), 42177 key: 'domain', 42178 defaultValue: null 42179 } 42180 ]) 42181 42182 webidl.converters.Cookie = webidl.dictionaryConverter([ 42183 { 42184 converter: webidl.converters.DOMString, 42185 key: 'name' 42186 }, 42187 { 42188 converter: webidl.converters.DOMString, 42189 key: 'value' 42190 }, 42191 { 42192 converter: webidl.nullableConverter((value) => { 42193 if (typeof value === 'number') { 42194 return webidl.converters['unsigned long long'](value) 42195 } 42196 42197 return new Date(value) 42198 }), 42199 key: 'expires', 42200 defaultValue: null 42201 }, 42202 { 42203 converter: webidl.nullableConverter(webidl.converters['long long']), 42204 key: 'maxAge', 42205 defaultValue: null 42206 }, 42207 { 42208 converter: webidl.nullableConverter(webidl.converters.DOMString), 42209 key: 'domain', 42210 defaultValue: null 42211 }, 42212 { 42213 converter: webidl.nullableConverter(webidl.converters.DOMString), 42214 key: 'path', 42215 defaultValue: null 42216 }, 42217 { 42218 converter: webidl.nullableConverter(webidl.converters.boolean), 42219 key: 'secure', 42220 defaultValue: null 42221 }, 42222 { 42223 converter: webidl.nullableConverter(webidl.converters.boolean), 42224 key: 'httpOnly', 42225 defaultValue: null 42226 }, 42227 { 42228 converter: webidl.converters.USVString, 42229 key: 'sameSite', 42230 allowedValues: ['Strict', 'Lax', 'None'] 42231 }, 42232 { 42233 converter: webidl.sequenceConverter(webidl.converters.DOMString), 42234 key: 'unparsed', 42235 defaultValue: [] 42236 } 42237 ]) 42238 42239 module.exports = { 42240 getCookies, 42241 deleteCookie, 42242 getSetCookies, 42243 setCookie 42244 } 42245 42246 42247 /***/ }), 42248 42249 /***/ 4408: 42250 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 42251 42252 "use strict"; 42253 42254 42255 const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(663) 42256 const { isCTLExcludingHtab } = __nccwpck_require__(3121) 42257 const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) 42258 const assert = __nccwpck_require__(9491) 42259 42260 /** 42261 * @description Parses the field-value attributes of a set-cookie header string. 42262 * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 42263 * @param {string} header 42264 * @returns if the header is invalid, null will be returned 42265 */ 42266 function parseSetCookie (header) { 42267 // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F 42268 // character (CTL characters excluding HTAB): Abort these steps and 42269 // ignore the set-cookie-string entirely. 42270 if (isCTLExcludingHtab(header)) { 42271 return null 42272 } 42273 42274 let nameValuePair = '' 42275 let unparsedAttributes = '' 42276 let name = '' 42277 let value = '' 42278 42279 // 2. If the set-cookie-string contains a %x3B (";") character: 42280 if (header.includes(';')) { 42281 // 1. The name-value-pair string consists of the characters up to, 42282 // but not including, the first %x3B (";"), and the unparsed- 42283 // attributes consist of the remainder of the set-cookie-string 42284 // (including the %x3B (";") in question). 42285 const position = { position: 0 } 42286 42287 nameValuePair = collectASequenceOfCodePointsFast(';', header, position) 42288 unparsedAttributes = header.slice(position.position) 42289 } else { 42290 // Otherwise: 42291 42292 // 1. The name-value-pair string consists of all the characters 42293 // contained in the set-cookie-string, and the unparsed- 42294 // attributes is the empty string. 42295 nameValuePair = header 42296 } 42297 42298 // 3. If the name-value-pair string lacks a %x3D ("=") character, then 42299 // the name string is empty, and the value string is the value of 42300 // name-value-pair. 42301 if (!nameValuePair.includes('=')) { 42302 value = nameValuePair 42303 } else { 42304 // Otherwise, the name string consists of the characters up to, but 42305 // not including, the first %x3D ("=") character, and the (possibly 42306 // empty) value string consists of the characters after the first 42307 // %x3D ("=") character. 42308 const position = { position: 0 } 42309 name = collectASequenceOfCodePointsFast( 42310 '=', 42311 nameValuePair, 42312 position 42313 ) 42314 value = nameValuePair.slice(position.position + 1) 42315 } 42316 42317 // 4. Remove any leading or trailing WSP characters from the name 42318 // string and the value string. 42319 name = name.trim() 42320 value = value.trim() 42321 42322 // 5. If the sum of the lengths of the name string and the value string 42323 // is more than 4096 octets, abort these steps and ignore the set- 42324 // cookie-string entirely. 42325 if (name.length + value.length > maxNameValuePairSize) { 42326 return null 42327 } 42328 42329 // 6. The cookie-name is the name string, and the cookie-value is the 42330 // value string. 42331 return { 42332 name, value, ...parseUnparsedAttributes(unparsedAttributes) 42333 } 42334 } 42335 42336 /** 42337 * Parses the remaining attributes of a set-cookie header 42338 * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 42339 * @param {string} unparsedAttributes 42340 * @param {[Object.<string, unknown>]={}} cookieAttributeList 42341 */ 42342 function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { 42343 // 1. If the unparsed-attributes string is empty, skip the rest of 42344 // these steps. 42345 if (unparsedAttributes.length === 0) { 42346 return cookieAttributeList 42347 } 42348 42349 // 2. Discard the first character of the unparsed-attributes (which 42350 // will be a %x3B (";") character). 42351 assert(unparsedAttributes[0] === ';') 42352 unparsedAttributes = unparsedAttributes.slice(1) 42353 42354 let cookieAv = '' 42355 42356 // 3. If the remaining unparsed-attributes contains a %x3B (";") 42357 // character: 42358 if (unparsedAttributes.includes(';')) { 42359 // 1. Consume the characters of the unparsed-attributes up to, but 42360 // not including, the first %x3B (";") character. 42361 cookieAv = collectASequenceOfCodePointsFast( 42362 ';', 42363 unparsedAttributes, 42364 { position: 0 } 42365 ) 42366 unparsedAttributes = unparsedAttributes.slice(cookieAv.length) 42367 } else { 42368 // Otherwise: 42369 42370 // 1. Consume the remainder of the unparsed-attributes. 42371 cookieAv = unparsedAttributes 42372 unparsedAttributes = '' 42373 } 42374 42375 // Let the cookie-av string be the characters consumed in this step. 42376 42377 let attributeName = '' 42378 let attributeValue = '' 42379 42380 // 4. If the cookie-av string contains a %x3D ("=") character: 42381 if (cookieAv.includes('=')) { 42382 // 1. The (possibly empty) attribute-name string consists of the 42383 // characters up to, but not including, the first %x3D ("=") 42384 // character, and the (possibly empty) attribute-value string 42385 // consists of the characters after the first %x3D ("=") 42386 // character. 42387 const position = { position: 0 } 42388 42389 attributeName = collectASequenceOfCodePointsFast( 42390 '=', 42391 cookieAv, 42392 position 42393 ) 42394 attributeValue = cookieAv.slice(position.position + 1) 42395 } else { 42396 // Otherwise: 42397 42398 // 1. The attribute-name string consists of the entire cookie-av 42399 // string, and the attribute-value string is empty. 42400 attributeName = cookieAv 42401 } 42402 42403 // 5. Remove any leading or trailing WSP characters from the attribute- 42404 // name string and the attribute-value string. 42405 attributeName = attributeName.trim() 42406 attributeValue = attributeValue.trim() 42407 42408 // 6. If the attribute-value is longer than 1024 octets, ignore the 42409 // cookie-av string and return to Step 1 of this algorithm. 42410 if (attributeValue.length > maxAttributeValueSize) { 42411 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) 42412 } 42413 42414 // 7. Process the attribute-name and attribute-value according to the 42415 // requirements in the following subsections. (Notice that 42416 // attributes with unrecognized attribute-names are ignored.) 42417 const attributeNameLowercase = attributeName.toLowerCase() 42418 42419 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 42420 // If the attribute-name case-insensitively matches the string 42421 // "Expires", the user agent MUST process the cookie-av as follows. 42422 if (attributeNameLowercase === 'expires') { 42423 // 1. Let the expiry-time be the result of parsing the attribute-value 42424 // as cookie-date (see Section 5.1.1). 42425 const expiryTime = new Date(attributeValue) 42426 42427 // 2. If the attribute-value failed to parse as a cookie date, ignore 42428 // the cookie-av. 42429 42430 cookieAttributeList.expires = expiryTime 42431 } else if (attributeNameLowercase === 'max-age') { 42432 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 42433 // If the attribute-name case-insensitively matches the string "Max- 42434 // Age", the user agent MUST process the cookie-av as follows. 42435 42436 // 1. If the first character of the attribute-value is not a DIGIT or a 42437 // "-" character, ignore the cookie-av. 42438 const charCode = attributeValue.charCodeAt(0) 42439 42440 if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { 42441 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) 42442 } 42443 42444 // 2. If the remainder of attribute-value contains a non-DIGIT 42445 // character, ignore the cookie-av. 42446 if (!/^\d+$/.test(attributeValue)) { 42447 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) 42448 } 42449 42450 // 3. Let delta-seconds be the attribute-value converted to an integer. 42451 const deltaSeconds = Number(attributeValue) 42452 42453 // 4. Let cookie-age-limit be the maximum age of the cookie (which 42454 // SHOULD be 400 days or less, see Section 4.1.2.2). 42455 42456 // 5. Set delta-seconds to the smaller of its present value and cookie- 42457 // age-limit. 42458 // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) 42459 42460 // 6. If delta-seconds is less than or equal to zero (0), let expiry- 42461 // time be the earliest representable date and time. Otherwise, let 42462 // the expiry-time be the current date and time plus delta-seconds 42463 // seconds. 42464 // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds 42465 42466 // 7. Append an attribute to the cookie-attribute-list with an 42467 // attribute-name of Max-Age and an attribute-value of expiry-time. 42468 cookieAttributeList.maxAge = deltaSeconds 42469 } else if (attributeNameLowercase === 'domain') { 42470 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 42471 // If the attribute-name case-insensitively matches the string "Domain", 42472 // the user agent MUST process the cookie-av as follows. 42473 42474 // 1. Let cookie-domain be the attribute-value. 42475 let cookieDomain = attributeValue 42476 42477 // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be 42478 // cookie-domain without its leading %x2E ("."). 42479 if (cookieDomain[0] === '.') { 42480 cookieDomain = cookieDomain.slice(1) 42481 } 42482 42483 // 3. Convert the cookie-domain to lower case. 42484 cookieDomain = cookieDomain.toLowerCase() 42485 42486 // 4. Append an attribute to the cookie-attribute-list with an 42487 // attribute-name of Domain and an attribute-value of cookie-domain. 42488 cookieAttributeList.domain = cookieDomain 42489 } else if (attributeNameLowercase === 'path') { 42490 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 42491 // If the attribute-name case-insensitively matches the string "Path", 42492 // the user agent MUST process the cookie-av as follows. 42493 42494 // 1. If the attribute-value is empty or if the first character of the 42495 // attribute-value is not %x2F ("/"): 42496 let cookiePath = '' 42497 if (attributeValue.length === 0 || attributeValue[0] !== '/') { 42498 // 1. Let cookie-path be the default-path. 42499 cookiePath = '/' 42500 } else { 42501 // Otherwise: 42502 42503 // 1. Let cookie-path be the attribute-value. 42504 cookiePath = attributeValue 42505 } 42506 42507 // 2. Append an attribute to the cookie-attribute-list with an 42508 // attribute-name of Path and an attribute-value of cookie-path. 42509 cookieAttributeList.path = cookiePath 42510 } else if (attributeNameLowercase === 'secure') { 42511 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 42512 // If the attribute-name case-insensitively matches the string "Secure", 42513 // the user agent MUST append an attribute to the cookie-attribute-list 42514 // with an attribute-name of Secure and an empty attribute-value. 42515 42516 cookieAttributeList.secure = true 42517 } else if (attributeNameLowercase === 'httponly') { 42518 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 42519 // If the attribute-name case-insensitively matches the string 42520 // "HttpOnly", the user agent MUST append an attribute to the cookie- 42521 // attribute-list with an attribute-name of HttpOnly and an empty 42522 // attribute-value. 42523 42524 cookieAttributeList.httpOnly = true 42525 } else if (attributeNameLowercase === 'samesite') { 42526 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 42527 // If the attribute-name case-insensitively matches the string 42528 // "SameSite", the user agent MUST process the cookie-av as follows: 42529 42530 // 1. Let enforcement be "Default". 42531 let enforcement = 'Default' 42532 42533 const attributeValueLowercase = attributeValue.toLowerCase() 42534 // 2. If cookie-av's attribute-value is a case-insensitive match for 42535 // "None", set enforcement to "None". 42536 if (attributeValueLowercase.includes('none')) { 42537 enforcement = 'None' 42538 } 42539 42540 // 3. If cookie-av's attribute-value is a case-insensitive match for 42541 // "Strict", set enforcement to "Strict". 42542 if (attributeValueLowercase.includes('strict')) { 42543 enforcement = 'Strict' 42544 } 42545 42546 // 4. If cookie-av's attribute-value is a case-insensitive match for 42547 // "Lax", set enforcement to "Lax". 42548 if (attributeValueLowercase.includes('lax')) { 42549 enforcement = 'Lax' 42550 } 42551 42552 // 5. Append an attribute to the cookie-attribute-list with an 42553 // attribute-name of "SameSite" and an attribute-value of 42554 // enforcement. 42555 cookieAttributeList.sameSite = enforcement 42556 } else { 42557 cookieAttributeList.unparsed ??= [] 42558 42559 cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) 42560 } 42561 42562 // 8. Return to Step 1 of this algorithm. 42563 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) 42564 } 42565 42566 module.exports = { 42567 parseSetCookie, 42568 parseUnparsedAttributes 42569 } 42570 42571 42572 /***/ }), 42573 42574 /***/ 3121: 42575 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 42576 42577 "use strict"; 42578 42579 42580 const assert = __nccwpck_require__(9491) 42581 const { kHeadersList } = __nccwpck_require__(2785) 42582 42583 function isCTLExcludingHtab (value) { 42584 if (value.length === 0) { 42585 return false 42586 } 42587 42588 for (const char of value) { 42589 const code = char.charCodeAt(0) 42590 42591 if ( 42592 (code >= 0x00 || code <= 0x08) || 42593 (code >= 0x0A || code <= 0x1F) || 42594 code === 0x7F 42595 ) { 42596 return false 42597 } 42598 } 42599 } 42600 42601 /** 42602 CHAR = <any US-ASCII character (octets 0 - 127)> 42603 token = 1*<any CHAR except CTLs or separators> 42604 separators = "(" | ")" | "<" | ">" | "@" 42605 | "," | ";" | ":" | "\" | <"> 42606 | "/" | "[" | "]" | "?" | "=" 42607 | "{" | "}" | SP | HT 42608 * @param {string} name 42609 */ 42610 function validateCookieName (name) { 42611 for (const char of name) { 42612 const code = char.charCodeAt(0) 42613 42614 if ( 42615 (code <= 0x20 || code > 0x7F) || 42616 char === '(' || 42617 char === ')' || 42618 char === '>' || 42619 char === '<' || 42620 char === '@' || 42621 char === ',' || 42622 char === ';' || 42623 char === ':' || 42624 char === '\\' || 42625 char === '"' || 42626 char === '/' || 42627 char === '[' || 42628 char === ']' || 42629 char === '?' || 42630 char === '=' || 42631 char === '{' || 42632 char === '}' 42633 ) { 42634 throw new Error('Invalid cookie name') 42635 } 42636 } 42637 } 42638 42639 /** 42640 cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) 42641 cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E 42642 ; US-ASCII characters excluding CTLs, 42643 ; whitespace DQUOTE, comma, semicolon, 42644 ; and backslash 42645 * @param {string} value 42646 */ 42647 function validateCookieValue (value) { 42648 for (const char of value) { 42649 const code = char.charCodeAt(0) 42650 42651 if ( 42652 code < 0x21 || // exclude CTLs (0-31) 42653 code === 0x22 || 42654 code === 0x2C || 42655 code === 0x3B || 42656 code === 0x5C || 42657 code > 0x7E // non-ascii 42658 ) { 42659 throw new Error('Invalid header value') 42660 } 42661 } 42662 } 42663 42664 /** 42665 * path-value = <any CHAR except CTLs or ";"> 42666 * @param {string} path 42667 */ 42668 function validateCookiePath (path) { 42669 for (const char of path) { 42670 const code = char.charCodeAt(0) 42671 42672 if (code < 0x21 || char === ';') { 42673 throw new Error('Invalid cookie path') 42674 } 42675 } 42676 } 42677 42678 /** 42679 * I have no idea why these values aren't allowed to be honest, 42680 * but Deno tests these. - Khafra 42681 * @param {string} domain 42682 */ 42683 function validateCookieDomain (domain) { 42684 if ( 42685 domain.startsWith('-') || 42686 domain.endsWith('.') || 42687 domain.endsWith('-') 42688 ) { 42689 throw new Error('Invalid cookie domain') 42690 } 42691 } 42692 42693 /** 42694 * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 42695 * @param {number|Date} date 42696 IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT 42697 ; fixed length/zone/capitalization subset of the format 42698 ; see Section 3.3 of [RFC5322] 42699 42700 day-name = %x4D.6F.6E ; "Mon", case-sensitive 42701 / %x54.75.65 ; "Tue", case-sensitive 42702 / %x57.65.64 ; "Wed", case-sensitive 42703 / %x54.68.75 ; "Thu", case-sensitive 42704 / %x46.72.69 ; "Fri", case-sensitive 42705 / %x53.61.74 ; "Sat", case-sensitive 42706 / %x53.75.6E ; "Sun", case-sensitive 42707 date1 = day SP month SP year 42708 ; e.g., 02 Jun 1982 42709 42710 day = 2DIGIT 42711 month = %x4A.61.6E ; "Jan", case-sensitive 42712 / %x46.65.62 ; "Feb", case-sensitive 42713 / %x4D.61.72 ; "Mar", case-sensitive 42714 / %x41.70.72 ; "Apr", case-sensitive 42715 / %x4D.61.79 ; "May", case-sensitive 42716 / %x4A.75.6E ; "Jun", case-sensitive 42717 / %x4A.75.6C ; "Jul", case-sensitive 42718 / %x41.75.67 ; "Aug", case-sensitive 42719 / %x53.65.70 ; "Sep", case-sensitive 42720 / %x4F.63.74 ; "Oct", case-sensitive 42721 / %x4E.6F.76 ; "Nov", case-sensitive 42722 / %x44.65.63 ; "Dec", case-sensitive 42723 year = 4DIGIT 42724 42725 GMT = %x47.4D.54 ; "GMT", case-sensitive 42726 42727 time-of-day = hour ":" minute ":" second 42728 ; 00:00:00 - 23:59:60 (leap second) 42729 42730 hour = 2DIGIT 42731 minute = 2DIGIT 42732 second = 2DIGIT 42733 */ 42734 function toIMFDate (date) { 42735 if (typeof date === 'number') { 42736 date = new Date(date) 42737 } 42738 42739 const days = [ 42740 'Sun', 'Mon', 'Tue', 'Wed', 42741 'Thu', 'Fri', 'Sat' 42742 ] 42743 42744 const months = [ 42745 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 42746 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' 42747 ] 42748 42749 const dayName = days[date.getUTCDay()] 42750 const day = date.getUTCDate().toString().padStart(2, '0') 42751 const month = months[date.getUTCMonth()] 42752 const year = date.getUTCFullYear() 42753 const hour = date.getUTCHours().toString().padStart(2, '0') 42754 const minute = date.getUTCMinutes().toString().padStart(2, '0') 42755 const second = date.getUTCSeconds().toString().padStart(2, '0') 42756 42757 return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` 42758 } 42759 42760 /** 42761 max-age-av = "Max-Age=" non-zero-digit *DIGIT 42762 ; In practice, both expires-av and max-age-av 42763 ; are limited to dates representable by the 42764 ; user agent. 42765 * @param {number} maxAge 42766 */ 42767 function validateCookieMaxAge (maxAge) { 42768 if (maxAge < 0) { 42769 throw new Error('Invalid cookie max-age') 42770 } 42771 } 42772 42773 /** 42774 * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 42775 * @param {import('./index').Cookie} cookie 42776 */ 42777 function stringify (cookie) { 42778 if (cookie.name.length === 0) { 42779 return null 42780 } 42781 42782 validateCookieName(cookie.name) 42783 validateCookieValue(cookie.value) 42784 42785 const out = [`${cookie.name}=${cookie.value}`] 42786 42787 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 42788 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 42789 if (cookie.name.startsWith('__Secure-')) { 42790 cookie.secure = true 42791 } 42792 42793 if (cookie.name.startsWith('__Host-')) { 42794 cookie.secure = true 42795 cookie.domain = null 42796 cookie.path = '/' 42797 } 42798 42799 if (cookie.secure) { 42800 out.push('Secure') 42801 } 42802 42803 if (cookie.httpOnly) { 42804 out.push('HttpOnly') 42805 } 42806 42807 if (typeof cookie.maxAge === 'number') { 42808 validateCookieMaxAge(cookie.maxAge) 42809 out.push(`Max-Age=${cookie.maxAge}`) 42810 } 42811 42812 if (cookie.domain) { 42813 validateCookieDomain(cookie.domain) 42814 out.push(`Domain=${cookie.domain}`) 42815 } 42816 42817 if (cookie.path) { 42818 validateCookiePath(cookie.path) 42819 out.push(`Path=${cookie.path}`) 42820 } 42821 42822 if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { 42823 out.push(`Expires=${toIMFDate(cookie.expires)}`) 42824 } 42825 42826 if (cookie.sameSite) { 42827 out.push(`SameSite=${cookie.sameSite}`) 42828 } 42829 42830 for (const part of cookie.unparsed) { 42831 if (!part.includes('=')) { 42832 throw new Error('Invalid unparsed') 42833 } 42834 42835 const [key, ...value] = part.split('=') 42836 42837 out.push(`${key.trim()}=${value.join('=')}`) 42838 } 42839 42840 return out.join('; ') 42841 } 42842 42843 let kHeadersListNode 42844 42845 function getHeadersList (headers) { 42846 if (headers[kHeadersList]) { 42847 return headers[kHeadersList] 42848 } 42849 42850 if (!kHeadersListNode) { 42851 kHeadersListNode = Object.getOwnPropertySymbols(headers).find( 42852 (symbol) => symbol.description === 'headers list' 42853 ) 42854 42855 assert(kHeadersListNode, 'Headers cannot be parsed') 42856 } 42857 42858 const headersList = headers[kHeadersListNode] 42859 assert(headersList) 42860 42861 return headersList 42862 } 42863 42864 module.exports = { 42865 isCTLExcludingHtab, 42866 stringify, 42867 getHeadersList 42868 } 42869 42870 42871 /***/ }), 42872 42873 /***/ 2067: 42874 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 42875 42876 "use strict"; 42877 42878 42879 const net = __nccwpck_require__(1808) 42880 const assert = __nccwpck_require__(9491) 42881 const util = __nccwpck_require__(3983) 42882 const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8045) 42883 42884 let tls // include tls conditionally since it is not always available 42885 42886 // TODO: session re-use does not wait for the first 42887 // connection to resolve the session and might therefore 42888 // resolve the same servername multiple times even when 42889 // re-use is enabled. 42890 42891 let SessionCache 42892 // FIXME: remove workaround when the Node bug is fixed 42893 // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 42894 if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { 42895 SessionCache = class WeakSessionCache { 42896 constructor (maxCachedSessions) { 42897 this._maxCachedSessions = maxCachedSessions 42898 this._sessionCache = new Map() 42899 this._sessionRegistry = new global.FinalizationRegistry((key) => { 42900 if (this._sessionCache.size < this._maxCachedSessions) { 42901 return 42902 } 42903 42904 const ref = this._sessionCache.get(key) 42905 if (ref !== undefined && ref.deref() === undefined) { 42906 this._sessionCache.delete(key) 42907 } 42908 }) 42909 } 42910 42911 get (sessionKey) { 42912 const ref = this._sessionCache.get(sessionKey) 42913 return ref ? ref.deref() : null 42914 } 42915 42916 set (sessionKey, session) { 42917 if (this._maxCachedSessions === 0) { 42918 return 42919 } 42920 42921 this._sessionCache.set(sessionKey, new WeakRef(session)) 42922 this._sessionRegistry.register(session, sessionKey) 42923 } 42924 } 42925 } else { 42926 SessionCache = class SimpleSessionCache { 42927 constructor (maxCachedSessions) { 42928 this._maxCachedSessions = maxCachedSessions 42929 this._sessionCache = new Map() 42930 } 42931 42932 get (sessionKey) { 42933 return this._sessionCache.get(sessionKey) 42934 } 42935 42936 set (sessionKey, session) { 42937 if (this._maxCachedSessions === 0) { 42938 return 42939 } 42940 42941 if (this._sessionCache.size >= this._maxCachedSessions) { 42942 // remove the oldest session 42943 const { value: oldestKey } = this._sessionCache.keys().next() 42944 this._sessionCache.delete(oldestKey) 42945 } 42946 42947 this._sessionCache.set(sessionKey, session) 42948 } 42949 } 42950 } 42951 42952 function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { 42953 if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { 42954 throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') 42955 } 42956 42957 const options = { path: socketPath, ...opts } 42958 const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) 42959 timeout = timeout == null ? 10e3 : timeout 42960 allowH2 = allowH2 != null ? allowH2 : false 42961 return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { 42962 let socket 42963 if (protocol === 'https:') { 42964 if (!tls) { 42965 tls = __nccwpck_require__(4404) 42966 } 42967 servername = servername || options.servername || util.getServerName(host) || null 42968 42969 const sessionKey = servername || hostname 42970 const session = sessionCache.get(sessionKey) || null 42971 42972 assert(sessionKey) 42973 42974 socket = tls.connect({ 42975 highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... 42976 ...options, 42977 servername, 42978 session, 42979 localAddress, 42980 // TODO(HTTP/2): Add support for h2c 42981 ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], 42982 socket: httpSocket, // upgrade socket connection 42983 port: port || 443, 42984 host: hostname 42985 }) 42986 42987 socket 42988 .on('session', function (session) { 42989 // TODO (fix): Can a session become invalid once established? Don't think so? 42990 sessionCache.set(sessionKey, session) 42991 }) 42992 } else { 42993 assert(!httpSocket, 'httpSocket can only be sent on TLS update') 42994 socket = net.connect({ 42995 highWaterMark: 64 * 1024, // Same as nodejs fs streams. 42996 ...options, 42997 localAddress, 42998 port: port || 80, 42999 host: hostname 43000 }) 43001 } 43002 43003 // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket 43004 if (options.keepAlive == null || options.keepAlive) { 43005 const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay 43006 socket.setKeepAlive(true, keepAliveInitialDelay) 43007 } 43008 43009 const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) 43010 43011 socket 43012 .setNoDelay(true) 43013 .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { 43014 cancelTimeout() 43015 43016 if (callback) { 43017 const cb = callback 43018 callback = null 43019 cb(null, this) 43020 } 43021 }) 43022 .on('error', function (err) { 43023 cancelTimeout() 43024 43025 if (callback) { 43026 const cb = callback 43027 callback = null 43028 cb(err) 43029 } 43030 }) 43031 43032 return socket 43033 } 43034 } 43035 43036 function setupTimeout (onConnectTimeout, timeout) { 43037 if (!timeout) { 43038 return () => {} 43039 } 43040 43041 let s1 = null 43042 let s2 = null 43043 const timeoutId = setTimeout(() => { 43044 // setImmediate is added to make sure that we priotorise socket error events over timeouts 43045 s1 = setImmediate(() => { 43046 if (process.platform === 'win32') { 43047 // Windows needs an extra setImmediate probably due to implementation differences in the socket logic 43048 s2 = setImmediate(() => onConnectTimeout()) 43049 } else { 43050 onConnectTimeout() 43051 } 43052 }) 43053 }, timeout) 43054 return () => { 43055 clearTimeout(timeoutId) 43056 clearImmediate(s1) 43057 clearImmediate(s2) 43058 } 43059 } 43060 43061 function onConnectTimeout (socket) { 43062 util.destroy(socket, new ConnectTimeoutError()) 43063 } 43064 43065 module.exports = buildConnector 43066 43067 43068 /***/ }), 43069 43070 /***/ 4462: 43071 /***/ ((module) => { 43072 43073 "use strict"; 43074 43075 43076 /** @type {Record<string, string | undefined>} */ 43077 const headerNameLowerCasedRecord = {} 43078 43079 // https://developer.mozilla.org/docs/Web/HTTP/Headers 43080 const wellknownHeaderNames = [ 43081 'Accept', 43082 'Accept-Encoding', 43083 'Accept-Language', 43084 'Accept-Ranges', 43085 'Access-Control-Allow-Credentials', 43086 'Access-Control-Allow-Headers', 43087 'Access-Control-Allow-Methods', 43088 'Access-Control-Allow-Origin', 43089 'Access-Control-Expose-Headers', 43090 'Access-Control-Max-Age', 43091 'Access-Control-Request-Headers', 43092 'Access-Control-Request-Method', 43093 'Age', 43094 'Allow', 43095 'Alt-Svc', 43096 'Alt-Used', 43097 'Authorization', 43098 'Cache-Control', 43099 'Clear-Site-Data', 43100 'Connection', 43101 'Content-Disposition', 43102 'Content-Encoding', 43103 'Content-Language', 43104 'Content-Length', 43105 'Content-Location', 43106 'Content-Range', 43107 'Content-Security-Policy', 43108 'Content-Security-Policy-Report-Only', 43109 'Content-Type', 43110 'Cookie', 43111 'Cross-Origin-Embedder-Policy', 43112 'Cross-Origin-Opener-Policy', 43113 'Cross-Origin-Resource-Policy', 43114 'Date', 43115 'Device-Memory', 43116 'Downlink', 43117 'ECT', 43118 'ETag', 43119 'Expect', 43120 'Expect-CT', 43121 'Expires', 43122 'Forwarded', 43123 'From', 43124 'Host', 43125 'If-Match', 43126 'If-Modified-Since', 43127 'If-None-Match', 43128 'If-Range', 43129 'If-Unmodified-Since', 43130 'Keep-Alive', 43131 'Last-Modified', 43132 'Link', 43133 'Location', 43134 'Max-Forwards', 43135 'Origin', 43136 'Permissions-Policy', 43137 'Pragma', 43138 'Proxy-Authenticate', 43139 'Proxy-Authorization', 43140 'RTT', 43141 'Range', 43142 'Referer', 43143 'Referrer-Policy', 43144 'Refresh', 43145 'Retry-After', 43146 'Sec-WebSocket-Accept', 43147 'Sec-WebSocket-Extensions', 43148 'Sec-WebSocket-Key', 43149 'Sec-WebSocket-Protocol', 43150 'Sec-WebSocket-Version', 43151 'Server', 43152 'Server-Timing', 43153 'Service-Worker-Allowed', 43154 'Service-Worker-Navigation-Preload', 43155 'Set-Cookie', 43156 'SourceMap', 43157 'Strict-Transport-Security', 43158 'Supports-Loading-Mode', 43159 'TE', 43160 'Timing-Allow-Origin', 43161 'Trailer', 43162 'Transfer-Encoding', 43163 'Upgrade', 43164 'Upgrade-Insecure-Requests', 43165 'User-Agent', 43166 'Vary', 43167 'Via', 43168 'WWW-Authenticate', 43169 'X-Content-Type-Options', 43170 'X-DNS-Prefetch-Control', 43171 'X-Frame-Options', 43172 'X-Permitted-Cross-Domain-Policies', 43173 'X-Powered-By', 43174 'X-Requested-With', 43175 'X-XSS-Protection' 43176 ] 43177 43178 for (let i = 0; i < wellknownHeaderNames.length; ++i) { 43179 const key = wellknownHeaderNames[i] 43180 const lowerCasedKey = key.toLowerCase() 43181 headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = 43182 lowerCasedKey 43183 } 43184 43185 // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. 43186 Object.setPrototypeOf(headerNameLowerCasedRecord, null) 43187 43188 module.exports = { 43189 wellknownHeaderNames, 43190 headerNameLowerCasedRecord 43191 } 43192 43193 43194 /***/ }), 43195 43196 /***/ 8045: 43197 /***/ ((module) => { 43198 43199 "use strict"; 43200 43201 43202 class UndiciError extends Error { 43203 constructor (message) { 43204 super(message) 43205 this.name = 'UndiciError' 43206 this.code = 'UND_ERR' 43207 } 43208 } 43209 43210 class ConnectTimeoutError extends UndiciError { 43211 constructor (message) { 43212 super(message) 43213 Error.captureStackTrace(this, ConnectTimeoutError) 43214 this.name = 'ConnectTimeoutError' 43215 this.message = message || 'Connect Timeout Error' 43216 this.code = 'UND_ERR_CONNECT_TIMEOUT' 43217 } 43218 } 43219 43220 class HeadersTimeoutError extends UndiciError { 43221 constructor (message) { 43222 super(message) 43223 Error.captureStackTrace(this, HeadersTimeoutError) 43224 this.name = 'HeadersTimeoutError' 43225 this.message = message || 'Headers Timeout Error' 43226 this.code = 'UND_ERR_HEADERS_TIMEOUT' 43227 } 43228 } 43229 43230 class HeadersOverflowError extends UndiciError { 43231 constructor (message) { 43232 super(message) 43233 Error.captureStackTrace(this, HeadersOverflowError) 43234 this.name = 'HeadersOverflowError' 43235 this.message = message || 'Headers Overflow Error' 43236 this.code = 'UND_ERR_HEADERS_OVERFLOW' 43237 } 43238 } 43239 43240 class BodyTimeoutError extends UndiciError { 43241 constructor (message) { 43242 super(message) 43243 Error.captureStackTrace(this, BodyTimeoutError) 43244 this.name = 'BodyTimeoutError' 43245 this.message = message || 'Body Timeout Error' 43246 this.code = 'UND_ERR_BODY_TIMEOUT' 43247 } 43248 } 43249 43250 class ResponseStatusCodeError extends UndiciError { 43251 constructor (message, statusCode, headers, body) { 43252 super(message) 43253 Error.captureStackTrace(this, ResponseStatusCodeError) 43254 this.name = 'ResponseStatusCodeError' 43255 this.message = message || 'Response Status Code Error' 43256 this.code = 'UND_ERR_RESPONSE_STATUS_CODE' 43257 this.body = body 43258 this.status = statusCode 43259 this.statusCode = statusCode 43260 this.headers = headers 43261 } 43262 } 43263 43264 class InvalidArgumentError extends UndiciError { 43265 constructor (message) { 43266 super(message) 43267 Error.captureStackTrace(this, InvalidArgumentError) 43268 this.name = 'InvalidArgumentError' 43269 this.message = message || 'Invalid Argument Error' 43270 this.code = 'UND_ERR_INVALID_ARG' 43271 } 43272 } 43273 43274 class InvalidReturnValueError extends UndiciError { 43275 constructor (message) { 43276 super(message) 43277 Error.captureStackTrace(this, InvalidReturnValueError) 43278 this.name = 'InvalidReturnValueError' 43279 this.message = message || 'Invalid Return Value Error' 43280 this.code = 'UND_ERR_INVALID_RETURN_VALUE' 43281 } 43282 } 43283 43284 class RequestAbortedError extends UndiciError { 43285 constructor (message) { 43286 super(message) 43287 Error.captureStackTrace(this, RequestAbortedError) 43288 this.name = 'AbortError' 43289 this.message = message || 'Request aborted' 43290 this.code = 'UND_ERR_ABORTED' 43291 } 43292 } 43293 43294 class InformationalError extends UndiciError { 43295 constructor (message) { 43296 super(message) 43297 Error.captureStackTrace(this, InformationalError) 43298 this.name = 'InformationalError' 43299 this.message = message || 'Request information' 43300 this.code = 'UND_ERR_INFO' 43301 } 43302 } 43303 43304 class RequestContentLengthMismatchError extends UndiciError { 43305 constructor (message) { 43306 super(message) 43307 Error.captureStackTrace(this, RequestContentLengthMismatchError) 43308 this.name = 'RequestContentLengthMismatchError' 43309 this.message = message || 'Request body length does not match content-length header' 43310 this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' 43311 } 43312 } 43313 43314 class ResponseContentLengthMismatchError extends UndiciError { 43315 constructor (message) { 43316 super(message) 43317 Error.captureStackTrace(this, ResponseContentLengthMismatchError) 43318 this.name = 'ResponseContentLengthMismatchError' 43319 this.message = message || 'Response body length does not match content-length header' 43320 this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' 43321 } 43322 } 43323 43324 class ClientDestroyedError extends UndiciError { 43325 constructor (message) { 43326 super(message) 43327 Error.captureStackTrace(this, ClientDestroyedError) 43328 this.name = 'ClientDestroyedError' 43329 this.message = message || 'The client is destroyed' 43330 this.code = 'UND_ERR_DESTROYED' 43331 } 43332 } 43333 43334 class ClientClosedError extends UndiciError { 43335 constructor (message) { 43336 super(message) 43337 Error.captureStackTrace(this, ClientClosedError) 43338 this.name = 'ClientClosedError' 43339 this.message = message || 'The client is closed' 43340 this.code = 'UND_ERR_CLOSED' 43341 } 43342 } 43343 43344 class SocketError extends UndiciError { 43345 constructor (message, socket) { 43346 super(message) 43347 Error.captureStackTrace(this, SocketError) 43348 this.name = 'SocketError' 43349 this.message = message || 'Socket error' 43350 this.code = 'UND_ERR_SOCKET' 43351 this.socket = socket 43352 } 43353 } 43354 43355 class NotSupportedError extends UndiciError { 43356 constructor (message) { 43357 super(message) 43358 Error.captureStackTrace(this, NotSupportedError) 43359 this.name = 'NotSupportedError' 43360 this.message = message || 'Not supported error' 43361 this.code = 'UND_ERR_NOT_SUPPORTED' 43362 } 43363 } 43364 43365 class BalancedPoolMissingUpstreamError extends UndiciError { 43366 constructor (message) { 43367 super(message) 43368 Error.captureStackTrace(this, NotSupportedError) 43369 this.name = 'MissingUpstreamError' 43370 this.message = message || 'No upstream has been added to the BalancedPool' 43371 this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' 43372 } 43373 } 43374 43375 class HTTPParserError extends Error { 43376 constructor (message, code, data) { 43377 super(message) 43378 Error.captureStackTrace(this, HTTPParserError) 43379 this.name = 'HTTPParserError' 43380 this.code = code ? `HPE_${code}` : undefined 43381 this.data = data ? data.toString() : undefined 43382 } 43383 } 43384 43385 class ResponseExceededMaxSizeError extends UndiciError { 43386 constructor (message) { 43387 super(message) 43388 Error.captureStackTrace(this, ResponseExceededMaxSizeError) 43389 this.name = 'ResponseExceededMaxSizeError' 43390 this.message = message || 'Response content exceeded max size' 43391 this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' 43392 } 43393 } 43394 43395 class RequestRetryError extends UndiciError { 43396 constructor (message, code, { headers, data }) { 43397 super(message) 43398 Error.captureStackTrace(this, RequestRetryError) 43399 this.name = 'RequestRetryError' 43400 this.message = message || 'Request retry error' 43401 this.code = 'UND_ERR_REQ_RETRY' 43402 this.statusCode = code 43403 this.data = data 43404 this.headers = headers 43405 } 43406 } 43407 43408 module.exports = { 43409 HTTPParserError, 43410 UndiciError, 43411 HeadersTimeoutError, 43412 HeadersOverflowError, 43413 BodyTimeoutError, 43414 RequestContentLengthMismatchError, 43415 ConnectTimeoutError, 43416 ResponseStatusCodeError, 43417 InvalidArgumentError, 43418 InvalidReturnValueError, 43419 RequestAbortedError, 43420 ClientDestroyedError, 43421 ClientClosedError, 43422 InformationalError, 43423 SocketError, 43424 NotSupportedError, 43425 ResponseContentLengthMismatchError, 43426 BalancedPoolMissingUpstreamError, 43427 ResponseExceededMaxSizeError, 43428 RequestRetryError 43429 } 43430 43431 43432 /***/ }), 43433 43434 /***/ 2905: 43435 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 43436 43437 "use strict"; 43438 43439 43440 const { 43441 InvalidArgumentError, 43442 NotSupportedError 43443 } = __nccwpck_require__(8045) 43444 const assert = __nccwpck_require__(9491) 43445 const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(2785) 43446 const util = __nccwpck_require__(3983) 43447 43448 // tokenRegExp and headerCharRegex have been lifted from 43449 // https://github.com/nodejs/node/blob/main/lib/_http_common.js 43450 43451 /** 43452 * Verifies that the given val is a valid HTTP token 43453 * per the rules defined in RFC 7230 43454 * See https://tools.ietf.org/html/rfc7230#section-3.2.6 43455 */ 43456 const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ 43457 43458 /** 43459 * Matches if val contains an invalid field-vchar 43460 * field-value = *( field-content / obs-fold ) 43461 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] 43462 * field-vchar = VCHAR / obs-text 43463 */ 43464 const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ 43465 43466 // Verifies that a given path is valid does not contain control chars \x00 to \x20 43467 const invalidPathRegex = /[^\u0021-\u00ff]/ 43468 43469 const kHandler = Symbol('handler') 43470 43471 const channels = {} 43472 43473 let extractBody 43474 43475 try { 43476 const diagnosticsChannel = __nccwpck_require__(7643) 43477 channels.create = diagnosticsChannel.channel('undici:request:create') 43478 channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') 43479 channels.headers = diagnosticsChannel.channel('undici:request:headers') 43480 channels.trailers = diagnosticsChannel.channel('undici:request:trailers') 43481 channels.error = diagnosticsChannel.channel('undici:request:error') 43482 } catch { 43483 channels.create = { hasSubscribers: false } 43484 channels.bodySent = { hasSubscribers: false } 43485 channels.headers = { hasSubscribers: false } 43486 channels.trailers = { hasSubscribers: false } 43487 channels.error = { hasSubscribers: false } 43488 } 43489 43490 class Request { 43491 constructor (origin, { 43492 path, 43493 method, 43494 body, 43495 headers, 43496 query, 43497 idempotent, 43498 blocking, 43499 upgrade, 43500 headersTimeout, 43501 bodyTimeout, 43502 reset, 43503 throwOnError, 43504 expectContinue 43505 }, handler) { 43506 if (typeof path !== 'string') { 43507 throw new InvalidArgumentError('path must be a string') 43508 } else if ( 43509 path[0] !== '/' && 43510 !(path.startsWith('http://') || path.startsWith('https://')) && 43511 method !== 'CONNECT' 43512 ) { 43513 throw new InvalidArgumentError('path must be an absolute URL or start with a slash') 43514 } else if (invalidPathRegex.exec(path) !== null) { 43515 throw new InvalidArgumentError('invalid request path') 43516 } 43517 43518 if (typeof method !== 'string') { 43519 throw new InvalidArgumentError('method must be a string') 43520 } else if (tokenRegExp.exec(method) === null) { 43521 throw new InvalidArgumentError('invalid request method') 43522 } 43523 43524 if (upgrade && typeof upgrade !== 'string') { 43525 throw new InvalidArgumentError('upgrade must be a string') 43526 } 43527 43528 if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { 43529 throw new InvalidArgumentError('invalid headersTimeout') 43530 } 43531 43532 if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { 43533 throw new InvalidArgumentError('invalid bodyTimeout') 43534 } 43535 43536 if (reset != null && typeof reset !== 'boolean') { 43537 throw new InvalidArgumentError('invalid reset') 43538 } 43539 43540 if (expectContinue != null && typeof expectContinue !== 'boolean') { 43541 throw new InvalidArgumentError('invalid expectContinue') 43542 } 43543 43544 this.headersTimeout = headersTimeout 43545 43546 this.bodyTimeout = bodyTimeout 43547 43548 this.throwOnError = throwOnError === true 43549 43550 this.method = method 43551 43552 this.abort = null 43553 43554 if (body == null) { 43555 this.body = null 43556 } else if (util.isStream(body)) { 43557 this.body = body 43558 43559 const rState = this.body._readableState 43560 if (!rState || !rState.autoDestroy) { 43561 this.endHandler = function autoDestroy () { 43562 util.destroy(this) 43563 } 43564 this.body.on('end', this.endHandler) 43565 } 43566 43567 this.errorHandler = err => { 43568 if (this.abort) { 43569 this.abort(err) 43570 } else { 43571 this.error = err 43572 } 43573 } 43574 this.body.on('error', this.errorHandler) 43575 } else if (util.isBuffer(body)) { 43576 this.body = body.byteLength ? body : null 43577 } else if (ArrayBuffer.isView(body)) { 43578 this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null 43579 } else if (body instanceof ArrayBuffer) { 43580 this.body = body.byteLength ? Buffer.from(body) : null 43581 } else if (typeof body === 'string') { 43582 this.body = body.length ? Buffer.from(body) : null 43583 } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { 43584 this.body = body 43585 } else { 43586 throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') 43587 } 43588 43589 this.completed = false 43590 43591 this.aborted = false 43592 43593 this.upgrade = upgrade || null 43594 43595 this.path = query ? util.buildURL(path, query) : path 43596 43597 this.origin = origin 43598 43599 this.idempotent = idempotent == null 43600 ? method === 'HEAD' || method === 'GET' 43601 : idempotent 43602 43603 this.blocking = blocking == null ? false : blocking 43604 43605 this.reset = reset == null ? null : reset 43606 43607 this.host = null 43608 43609 this.contentLength = null 43610 43611 this.contentType = null 43612 43613 this.headers = '' 43614 43615 // Only for H2 43616 this.expectContinue = expectContinue != null ? expectContinue : false 43617 43618 if (Array.isArray(headers)) { 43619 if (headers.length % 2 !== 0) { 43620 throw new InvalidArgumentError('headers array must be even') 43621 } 43622 for (let i = 0; i < headers.length; i += 2) { 43623 processHeader(this, headers[i], headers[i + 1]) 43624 } 43625 } else if (headers && typeof headers === 'object') { 43626 const keys = Object.keys(headers) 43627 for (let i = 0; i < keys.length; i++) { 43628 const key = keys[i] 43629 processHeader(this, key, headers[key]) 43630 } 43631 } else if (headers != null) { 43632 throw new InvalidArgumentError('headers must be an object or an array') 43633 } 43634 43635 if (util.isFormDataLike(this.body)) { 43636 if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { 43637 throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') 43638 } 43639 43640 if (!extractBody) { 43641 extractBody = (__nccwpck_require__(1472).extractBody) 43642 } 43643 43644 const [bodyStream, contentType] = extractBody(body) 43645 if (this.contentType == null) { 43646 this.contentType = contentType 43647 this.headers += `content-type: ${contentType}\r\n` 43648 } 43649 this.body = bodyStream.stream 43650 this.contentLength = bodyStream.length 43651 } else if (util.isBlobLike(body) && this.contentType == null && body.type) { 43652 this.contentType = body.type 43653 this.headers += `content-type: ${body.type}\r\n` 43654 } 43655 43656 util.validateHandler(handler, method, upgrade) 43657 43658 this.servername = util.getServerName(this.host) 43659 43660 this[kHandler] = handler 43661 43662 if (channels.create.hasSubscribers) { 43663 channels.create.publish({ request: this }) 43664 } 43665 } 43666 43667 onBodySent (chunk) { 43668 if (this[kHandler].onBodySent) { 43669 try { 43670 return this[kHandler].onBodySent(chunk) 43671 } catch (err) { 43672 this.abort(err) 43673 } 43674 } 43675 } 43676 43677 onRequestSent () { 43678 if (channels.bodySent.hasSubscribers) { 43679 channels.bodySent.publish({ request: this }) 43680 } 43681 43682 if (this[kHandler].onRequestSent) { 43683 try { 43684 return this[kHandler].onRequestSent() 43685 } catch (err) { 43686 this.abort(err) 43687 } 43688 } 43689 } 43690 43691 onConnect (abort) { 43692 assert(!this.aborted) 43693 assert(!this.completed) 43694 43695 if (this.error) { 43696 abort(this.error) 43697 } else { 43698 this.abort = abort 43699 return this[kHandler].onConnect(abort) 43700 } 43701 } 43702 43703 onHeaders (statusCode, headers, resume, statusText) { 43704 assert(!this.aborted) 43705 assert(!this.completed) 43706 43707 if (channels.headers.hasSubscribers) { 43708 channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) 43709 } 43710 43711 try { 43712 return this[kHandler].onHeaders(statusCode, headers, resume, statusText) 43713 } catch (err) { 43714 this.abort(err) 43715 } 43716 } 43717 43718 onData (chunk) { 43719 assert(!this.aborted) 43720 assert(!this.completed) 43721 43722 try { 43723 return this[kHandler].onData(chunk) 43724 } catch (err) { 43725 this.abort(err) 43726 return false 43727 } 43728 } 43729 43730 onUpgrade (statusCode, headers, socket) { 43731 assert(!this.aborted) 43732 assert(!this.completed) 43733 43734 return this[kHandler].onUpgrade(statusCode, headers, socket) 43735 } 43736 43737 onComplete (trailers) { 43738 this.onFinally() 43739 43740 assert(!this.aborted) 43741 43742 this.completed = true 43743 if (channels.trailers.hasSubscribers) { 43744 channels.trailers.publish({ request: this, trailers }) 43745 } 43746 43747 try { 43748 return this[kHandler].onComplete(trailers) 43749 } catch (err) { 43750 // TODO (fix): This might be a bad idea? 43751 this.onError(err) 43752 } 43753 } 43754 43755 onError (error) { 43756 this.onFinally() 43757 43758 if (channels.error.hasSubscribers) { 43759 channels.error.publish({ request: this, error }) 43760 } 43761 43762 if (this.aborted) { 43763 return 43764 } 43765 this.aborted = true 43766 43767 return this[kHandler].onError(error) 43768 } 43769 43770 onFinally () { 43771 if (this.errorHandler) { 43772 this.body.off('error', this.errorHandler) 43773 this.errorHandler = null 43774 } 43775 43776 if (this.endHandler) { 43777 this.body.off('end', this.endHandler) 43778 this.endHandler = null 43779 } 43780 } 43781 43782 // TODO: adjust to support H2 43783 addHeader (key, value) { 43784 processHeader(this, key, value) 43785 return this 43786 } 43787 43788 static [kHTTP1BuildRequest] (origin, opts, handler) { 43789 // TODO: Migrate header parsing here, to make Requests 43790 // HTTP agnostic 43791 return new Request(origin, opts, handler) 43792 } 43793 43794 static [kHTTP2BuildRequest] (origin, opts, handler) { 43795 const headers = opts.headers 43796 opts = { ...opts, headers: null } 43797 43798 const request = new Request(origin, opts, handler) 43799 43800 request.headers = {} 43801 43802 if (Array.isArray(headers)) { 43803 if (headers.length % 2 !== 0) { 43804 throw new InvalidArgumentError('headers array must be even') 43805 } 43806 for (let i = 0; i < headers.length; i += 2) { 43807 processHeader(request, headers[i], headers[i + 1], true) 43808 } 43809 } else if (headers && typeof headers === 'object') { 43810 const keys = Object.keys(headers) 43811 for (let i = 0; i < keys.length; i++) { 43812 const key = keys[i] 43813 processHeader(request, key, headers[key], true) 43814 } 43815 } else if (headers != null) { 43816 throw new InvalidArgumentError('headers must be an object or an array') 43817 } 43818 43819 return request 43820 } 43821 43822 static [kHTTP2CopyHeaders] (raw) { 43823 const rawHeaders = raw.split('\r\n') 43824 const headers = {} 43825 43826 for (const header of rawHeaders) { 43827 const [key, value] = header.split(': ') 43828 43829 if (value == null || value.length === 0) continue 43830 43831 if (headers[key]) headers[key] += `,${value}` 43832 else headers[key] = value 43833 } 43834 43835 return headers 43836 } 43837 } 43838 43839 function processHeaderValue (key, val, skipAppend) { 43840 if (val && typeof val === 'object') { 43841 throw new InvalidArgumentError(`invalid ${key} header`) 43842 } 43843 43844 val = val != null ? `${val}` : '' 43845 43846 if (headerCharRegex.exec(val) !== null) { 43847 throw new InvalidArgumentError(`invalid ${key} header`) 43848 } 43849 43850 return skipAppend ? val : `${key}: ${val}\r\n` 43851 } 43852 43853 function processHeader (request, key, val, skipAppend = false) { 43854 if (val && (typeof val === 'object' && !Array.isArray(val))) { 43855 throw new InvalidArgumentError(`invalid ${key} header`) 43856 } else if (val === undefined) { 43857 return 43858 } 43859 43860 if ( 43861 request.host === null && 43862 key.length === 4 && 43863 key.toLowerCase() === 'host' 43864 ) { 43865 if (headerCharRegex.exec(val) !== null) { 43866 throw new InvalidArgumentError(`invalid ${key} header`) 43867 } 43868 // Consumed by Client 43869 request.host = val 43870 } else if ( 43871 request.contentLength === null && 43872 key.length === 14 && 43873 key.toLowerCase() === 'content-length' 43874 ) { 43875 request.contentLength = parseInt(val, 10) 43876 if (!Number.isFinite(request.contentLength)) { 43877 throw new InvalidArgumentError('invalid content-length header') 43878 } 43879 } else if ( 43880 request.contentType === null && 43881 key.length === 12 && 43882 key.toLowerCase() === 'content-type' 43883 ) { 43884 request.contentType = val 43885 if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) 43886 else request.headers += processHeaderValue(key, val) 43887 } else if ( 43888 key.length === 17 && 43889 key.toLowerCase() === 'transfer-encoding' 43890 ) { 43891 throw new InvalidArgumentError('invalid transfer-encoding header') 43892 } else if ( 43893 key.length === 10 && 43894 key.toLowerCase() === 'connection' 43895 ) { 43896 const value = typeof val === 'string' ? val.toLowerCase() : null 43897 if (value !== 'close' && value !== 'keep-alive') { 43898 throw new InvalidArgumentError('invalid connection header') 43899 } else if (value === 'close') { 43900 request.reset = true 43901 } 43902 } else if ( 43903 key.length === 10 && 43904 key.toLowerCase() === 'keep-alive' 43905 ) { 43906 throw new InvalidArgumentError('invalid keep-alive header') 43907 } else if ( 43908 key.length === 7 && 43909 key.toLowerCase() === 'upgrade' 43910 ) { 43911 throw new InvalidArgumentError('invalid upgrade header') 43912 } else if ( 43913 key.length === 6 && 43914 key.toLowerCase() === 'expect' 43915 ) { 43916 throw new NotSupportedError('expect header not supported') 43917 } else if (tokenRegExp.exec(key) === null) { 43918 throw new InvalidArgumentError('invalid header key') 43919 } else { 43920 if (Array.isArray(val)) { 43921 for (let i = 0; i < val.length; i++) { 43922 if (skipAppend) { 43923 if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` 43924 else request.headers[key] = processHeaderValue(key, val[i], skipAppend) 43925 } else { 43926 request.headers += processHeaderValue(key, val[i]) 43927 } 43928 } 43929 } else { 43930 if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) 43931 else request.headers += processHeaderValue(key, val) 43932 } 43933 } 43934 } 43935 43936 module.exports = Request 43937 43938 43939 /***/ }), 43940 43941 /***/ 2785: 43942 /***/ ((module) => { 43943 43944 module.exports = { 43945 kClose: Symbol('close'), 43946 kDestroy: Symbol('destroy'), 43947 kDispatch: Symbol('dispatch'), 43948 kUrl: Symbol('url'), 43949 kWriting: Symbol('writing'), 43950 kResuming: Symbol('resuming'), 43951 kQueue: Symbol('queue'), 43952 kConnect: Symbol('connect'), 43953 kConnecting: Symbol('connecting'), 43954 kHeadersList: Symbol('headers list'), 43955 kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), 43956 kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), 43957 kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), 43958 kKeepAliveTimeoutValue: Symbol('keep alive timeout'), 43959 kKeepAlive: Symbol('keep alive'), 43960 kHeadersTimeout: Symbol('headers timeout'), 43961 kBodyTimeout: Symbol('body timeout'), 43962 kServerName: Symbol('server name'), 43963 kLocalAddress: Symbol('local address'), 43964 kHost: Symbol('host'), 43965 kNoRef: Symbol('no ref'), 43966 kBodyUsed: Symbol('used'), 43967 kRunning: Symbol('running'), 43968 kBlocking: Symbol('blocking'), 43969 kPending: Symbol('pending'), 43970 kSize: Symbol('size'), 43971 kBusy: Symbol('busy'), 43972 kQueued: Symbol('queued'), 43973 kFree: Symbol('free'), 43974 kConnected: Symbol('connected'), 43975 kClosed: Symbol('closed'), 43976 kNeedDrain: Symbol('need drain'), 43977 kReset: Symbol('reset'), 43978 kDestroyed: Symbol.for('nodejs.stream.destroyed'), 43979 kMaxHeadersSize: Symbol('max headers size'), 43980 kRunningIdx: Symbol('running index'), 43981 kPendingIdx: Symbol('pending index'), 43982 kError: Symbol('error'), 43983 kClients: Symbol('clients'), 43984 kClient: Symbol('client'), 43985 kParser: Symbol('parser'), 43986 kOnDestroyed: Symbol('destroy callbacks'), 43987 kPipelining: Symbol('pipelining'), 43988 kSocket: Symbol('socket'), 43989 kHostHeader: Symbol('host header'), 43990 kConnector: Symbol('connector'), 43991 kStrictContentLength: Symbol('strict content length'), 43992 kMaxRedirections: Symbol('maxRedirections'), 43993 kMaxRequests: Symbol('maxRequestsPerClient'), 43994 kProxy: Symbol('proxy agent options'), 43995 kCounter: Symbol('socket request counter'), 43996 kInterceptors: Symbol('dispatch interceptors'), 43997 kMaxResponseSize: Symbol('max response size'), 43998 kHTTP2Session: Symbol('http2Session'), 43999 kHTTP2SessionState: Symbol('http2Session state'), 44000 kHTTP2BuildRequest: Symbol('http2 build request'), 44001 kHTTP1BuildRequest: Symbol('http1 build request'), 44002 kHTTP2CopyHeaders: Symbol('http2 copy headers'), 44003 kHTTPConnVersion: Symbol('http connection version'), 44004 kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), 44005 kConstruct: Symbol('constructable') 44006 } 44007 44008 44009 /***/ }), 44010 44011 /***/ 3983: 44012 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 44013 44014 "use strict"; 44015 44016 44017 const assert = __nccwpck_require__(9491) 44018 const { kDestroyed, kBodyUsed } = __nccwpck_require__(2785) 44019 const { IncomingMessage } = __nccwpck_require__(3685) 44020 const stream = __nccwpck_require__(2781) 44021 const net = __nccwpck_require__(1808) 44022 const { InvalidArgumentError } = __nccwpck_require__(8045) 44023 const { Blob } = __nccwpck_require__(4300) 44024 const nodeUtil = __nccwpck_require__(3837) 44025 const { stringify } = __nccwpck_require__(3477) 44026 const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) 44027 44028 const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) 44029 44030 function nop () {} 44031 44032 function isStream (obj) { 44033 return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' 44034 } 44035 44036 // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) 44037 function isBlobLike (object) { 44038 return (Blob && object instanceof Blob) || ( 44039 object && 44040 typeof object === 'object' && 44041 (typeof object.stream === 'function' || 44042 typeof object.arrayBuffer === 'function') && 44043 /^(Blob|File)$/.test(object[Symbol.toStringTag]) 44044 ) 44045 } 44046 44047 function buildURL (url, queryParams) { 44048 if (url.includes('?') || url.includes('#')) { 44049 throw new Error('Query params cannot be passed when url already contains "?" or "#".') 44050 } 44051 44052 const stringified = stringify(queryParams) 44053 44054 if (stringified) { 44055 url += '?' + stringified 44056 } 44057 44058 return url 44059 } 44060 44061 function parseURL (url) { 44062 if (typeof url === 'string') { 44063 url = new URL(url) 44064 44065 if (!/^https?:/.test(url.origin || url.protocol)) { 44066 throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') 44067 } 44068 44069 return url 44070 } 44071 44072 if (!url || typeof url !== 'object') { 44073 throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') 44074 } 44075 44076 if (!/^https?:/.test(url.origin || url.protocol)) { 44077 throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') 44078 } 44079 44080 if (!(url instanceof URL)) { 44081 if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { 44082 throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') 44083 } 44084 44085 if (url.path != null && typeof url.path !== 'string') { 44086 throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') 44087 } 44088 44089 if (url.pathname != null && typeof url.pathname !== 'string') { 44090 throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') 44091 } 44092 44093 if (url.hostname != null && typeof url.hostname !== 'string') { 44094 throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') 44095 } 44096 44097 if (url.origin != null && typeof url.origin !== 'string') { 44098 throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') 44099 } 44100 44101 const port = url.port != null 44102 ? url.port 44103 : (url.protocol === 'https:' ? 443 : 80) 44104 let origin = url.origin != null 44105 ? url.origin 44106 : `${url.protocol}//${url.hostname}:${port}` 44107 let path = url.path != null 44108 ? url.path 44109 : `${url.pathname || ''}${url.search || ''}` 44110 44111 if (origin.endsWith('/')) { 44112 origin = origin.substring(0, origin.length - 1) 44113 } 44114 44115 if (path && !path.startsWith('/')) { 44116 path = `/${path}` 44117 } 44118 // new URL(path, origin) is unsafe when `path` contains an absolute URL 44119 // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: 44120 // If first parameter is a relative URL, second param is required, and will be used as the base URL. 44121 // If first parameter is an absolute URL, a given second param will be ignored. 44122 url = new URL(origin + path) 44123 } 44124 44125 return url 44126 } 44127 44128 function parseOrigin (url) { 44129 url = parseURL(url) 44130 44131 if (url.pathname !== '/' || url.search || url.hash) { 44132 throw new InvalidArgumentError('invalid url') 44133 } 44134 44135 return url 44136 } 44137 44138 function getHostname (host) { 44139 if (host[0] === '[') { 44140 const idx = host.indexOf(']') 44141 44142 assert(idx !== -1) 44143 return host.substring(1, idx) 44144 } 44145 44146 const idx = host.indexOf(':') 44147 if (idx === -1) return host 44148 44149 return host.substring(0, idx) 44150 } 44151 44152 // IP addresses are not valid server names per RFC6066 44153 // > Currently, the only server names supported are DNS hostnames 44154 function getServerName (host) { 44155 if (!host) { 44156 return null 44157 } 44158 44159 assert.strictEqual(typeof host, 'string') 44160 44161 const servername = getHostname(host) 44162 if (net.isIP(servername)) { 44163 return '' 44164 } 44165 44166 return servername 44167 } 44168 44169 function deepClone (obj) { 44170 return JSON.parse(JSON.stringify(obj)) 44171 } 44172 44173 function isAsyncIterable (obj) { 44174 return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') 44175 } 44176 44177 function isIterable (obj) { 44178 return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) 44179 } 44180 44181 function bodyLength (body) { 44182 if (body == null) { 44183 return 0 44184 } else if (isStream(body)) { 44185 const state = body._readableState 44186 return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) 44187 ? state.length 44188 : null 44189 } else if (isBlobLike(body)) { 44190 return body.size != null ? body.size : null 44191 } else if (isBuffer(body)) { 44192 return body.byteLength 44193 } 44194 44195 return null 44196 } 44197 44198 function isDestroyed (stream) { 44199 return !stream || !!(stream.destroyed || stream[kDestroyed]) 44200 } 44201 44202 function isReadableAborted (stream) { 44203 const state = stream && stream._readableState 44204 return isDestroyed(stream) && state && !state.endEmitted 44205 } 44206 44207 function destroy (stream, err) { 44208 if (stream == null || !isStream(stream) || isDestroyed(stream)) { 44209 return 44210 } 44211 44212 if (typeof stream.destroy === 'function') { 44213 if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { 44214 // See: https://github.com/nodejs/node/pull/38505/files 44215 stream.socket = null 44216 } 44217 44218 stream.destroy(err) 44219 } else if (err) { 44220 process.nextTick((stream, err) => { 44221 stream.emit('error', err) 44222 }, stream, err) 44223 } 44224 44225 if (stream.destroyed !== true) { 44226 stream[kDestroyed] = true 44227 } 44228 } 44229 44230 const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ 44231 function parseKeepAliveTimeout (val) { 44232 const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) 44233 return m ? parseInt(m[1], 10) * 1000 : null 44234 } 44235 44236 /** 44237 * Retrieves a header name and returns its lowercase value. 44238 * @param {string | Buffer} value Header name 44239 * @returns {string} 44240 */ 44241 function headerNameToString (value) { 44242 return headerNameLowerCasedRecord[value] || value.toLowerCase() 44243 } 44244 44245 function parseHeaders (headers, obj = {}) { 44246 // For H2 support 44247 if (!Array.isArray(headers)) return headers 44248 44249 for (let i = 0; i < headers.length; i += 2) { 44250 const key = headers[i].toString().toLowerCase() 44251 let val = obj[key] 44252 44253 if (!val) { 44254 if (Array.isArray(headers[i + 1])) { 44255 obj[key] = headers[i + 1].map(x => x.toString('utf8')) 44256 } else { 44257 obj[key] = headers[i + 1].toString('utf8') 44258 } 44259 } else { 44260 if (!Array.isArray(val)) { 44261 val = [val] 44262 obj[key] = val 44263 } 44264 val.push(headers[i + 1].toString('utf8')) 44265 } 44266 } 44267 44268 // See https://github.com/nodejs/node/pull/46528 44269 if ('content-length' in obj && 'content-disposition' in obj) { 44270 obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') 44271 } 44272 44273 return obj 44274 } 44275 44276 function parseRawHeaders (headers) { 44277 const ret = [] 44278 let hasContentLength = false 44279 let contentDispositionIdx = -1 44280 44281 for (let n = 0; n < headers.length; n += 2) { 44282 const key = headers[n + 0].toString() 44283 const val = headers[n + 1].toString('utf8') 44284 44285 if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { 44286 ret.push(key, val) 44287 hasContentLength = true 44288 } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { 44289 contentDispositionIdx = ret.push(key, val) - 1 44290 } else { 44291 ret.push(key, val) 44292 } 44293 } 44294 44295 // See https://github.com/nodejs/node/pull/46528 44296 if (hasContentLength && contentDispositionIdx !== -1) { 44297 ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') 44298 } 44299 44300 return ret 44301 } 44302 44303 function isBuffer (buffer) { 44304 // See, https://github.com/mcollina/undici/pull/319 44305 return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) 44306 } 44307 44308 function validateHandler (handler, method, upgrade) { 44309 if (!handler || typeof handler !== 'object') { 44310 throw new InvalidArgumentError('handler must be an object') 44311 } 44312 44313 if (typeof handler.onConnect !== 'function') { 44314 throw new InvalidArgumentError('invalid onConnect method') 44315 } 44316 44317 if (typeof handler.onError !== 'function') { 44318 throw new InvalidArgumentError('invalid onError method') 44319 } 44320 44321 if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { 44322 throw new InvalidArgumentError('invalid onBodySent method') 44323 } 44324 44325 if (upgrade || method === 'CONNECT') { 44326 if (typeof handler.onUpgrade !== 'function') { 44327 throw new InvalidArgumentError('invalid onUpgrade method') 44328 } 44329 } else { 44330 if (typeof handler.onHeaders !== 'function') { 44331 throw new InvalidArgumentError('invalid onHeaders method') 44332 } 44333 44334 if (typeof handler.onData !== 'function') { 44335 throw new InvalidArgumentError('invalid onData method') 44336 } 44337 44338 if (typeof handler.onComplete !== 'function') { 44339 throw new InvalidArgumentError('invalid onComplete method') 44340 } 44341 } 44342 } 44343 44344 // A body is disturbed if it has been read from and it cannot 44345 // be re-used without losing state or data. 44346 function isDisturbed (body) { 44347 return !!(body && ( 44348 stream.isDisturbed 44349 ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? 44350 : body[kBodyUsed] || 44351 body.readableDidRead || 44352 (body._readableState && body._readableState.dataEmitted) || 44353 isReadableAborted(body) 44354 )) 44355 } 44356 44357 function isErrored (body) { 44358 return !!(body && ( 44359 stream.isErrored 44360 ? stream.isErrored(body) 44361 : /state: 'errored'/.test(nodeUtil.inspect(body) 44362 ))) 44363 } 44364 44365 function isReadable (body) { 44366 return !!(body && ( 44367 stream.isReadable 44368 ? stream.isReadable(body) 44369 : /state: 'readable'/.test(nodeUtil.inspect(body) 44370 ))) 44371 } 44372 44373 function getSocketInfo (socket) { 44374 return { 44375 localAddress: socket.localAddress, 44376 localPort: socket.localPort, 44377 remoteAddress: socket.remoteAddress, 44378 remotePort: socket.remotePort, 44379 remoteFamily: socket.remoteFamily, 44380 timeout: socket.timeout, 44381 bytesWritten: socket.bytesWritten, 44382 bytesRead: socket.bytesRead 44383 } 44384 } 44385 44386 async function * convertIterableToBuffer (iterable) { 44387 for await (const chunk of iterable) { 44388 yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) 44389 } 44390 } 44391 44392 let ReadableStream 44393 function ReadableStreamFrom (iterable) { 44394 if (!ReadableStream) { 44395 ReadableStream = (__nccwpck_require__(5356).ReadableStream) 44396 } 44397 44398 if (ReadableStream.from) { 44399 return ReadableStream.from(convertIterableToBuffer(iterable)) 44400 } 44401 44402 let iterator 44403 return new ReadableStream( 44404 { 44405 async start () { 44406 iterator = iterable[Symbol.asyncIterator]() 44407 }, 44408 async pull (controller) { 44409 const { done, value } = await iterator.next() 44410 if (done) { 44411 queueMicrotask(() => { 44412 controller.close() 44413 }) 44414 } else { 44415 const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) 44416 controller.enqueue(new Uint8Array(buf)) 44417 } 44418 return controller.desiredSize > 0 44419 }, 44420 async cancel (reason) { 44421 await iterator.return() 44422 } 44423 }, 44424 0 44425 ) 44426 } 44427 44428 // The chunk should be a FormData instance and contains 44429 // all the required methods. 44430 function isFormDataLike (object) { 44431 return ( 44432 object && 44433 typeof object === 'object' && 44434 typeof object.append === 'function' && 44435 typeof object.delete === 'function' && 44436 typeof object.get === 'function' && 44437 typeof object.getAll === 'function' && 44438 typeof object.has === 'function' && 44439 typeof object.set === 'function' && 44440 object[Symbol.toStringTag] === 'FormData' 44441 ) 44442 } 44443 44444 function throwIfAborted (signal) { 44445 if (!signal) { return } 44446 if (typeof signal.throwIfAborted === 'function') { 44447 signal.throwIfAborted() 44448 } else { 44449 if (signal.aborted) { 44450 // DOMException not available < v17.0.0 44451 const err = new Error('The operation was aborted') 44452 err.name = 'AbortError' 44453 throw err 44454 } 44455 } 44456 } 44457 44458 function addAbortListener (signal, listener) { 44459 if ('addEventListener' in signal) { 44460 signal.addEventListener('abort', listener, { once: true }) 44461 return () => signal.removeEventListener('abort', listener) 44462 } 44463 signal.addListener('abort', listener) 44464 return () => signal.removeListener('abort', listener) 44465 } 44466 44467 const hasToWellFormed = !!String.prototype.toWellFormed 44468 44469 /** 44470 * @param {string} val 44471 */ 44472 function toUSVString (val) { 44473 if (hasToWellFormed) { 44474 return `${val}`.toWellFormed() 44475 } else if (nodeUtil.toUSVString) { 44476 return nodeUtil.toUSVString(val) 44477 } 44478 44479 return `${val}` 44480 } 44481 44482 // Parsed accordingly to RFC 9110 44483 // https://www.rfc-editor.org/rfc/rfc9110#field.content-range 44484 function parseRangeHeader (range) { 44485 if (range == null || range === '') return { start: 0, end: null, size: null } 44486 44487 const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null 44488 return m 44489 ? { 44490 start: parseInt(m[1]), 44491 end: m[2] ? parseInt(m[2]) : null, 44492 size: m[3] ? parseInt(m[3]) : null 44493 } 44494 : null 44495 } 44496 44497 const kEnumerableProperty = Object.create(null) 44498 kEnumerableProperty.enumerable = true 44499 44500 module.exports = { 44501 kEnumerableProperty, 44502 nop, 44503 isDisturbed, 44504 isErrored, 44505 isReadable, 44506 toUSVString, 44507 isReadableAborted, 44508 isBlobLike, 44509 parseOrigin, 44510 parseURL, 44511 getServerName, 44512 isStream, 44513 isIterable, 44514 isAsyncIterable, 44515 isDestroyed, 44516 headerNameToString, 44517 parseRawHeaders, 44518 parseHeaders, 44519 parseKeepAliveTimeout, 44520 destroy, 44521 bodyLength, 44522 deepClone, 44523 ReadableStreamFrom, 44524 isBuffer, 44525 validateHandler, 44526 getSocketInfo, 44527 isFormDataLike, 44528 buildURL, 44529 throwIfAborted, 44530 addAbortListener, 44531 parseRangeHeader, 44532 nodeMajor, 44533 nodeMinor, 44534 nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), 44535 safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] 44536 } 44537 44538 44539 /***/ }), 44540 44541 /***/ 4839: 44542 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 44543 44544 "use strict"; 44545 44546 44547 const Dispatcher = __nccwpck_require__(412) 44548 const { 44549 ClientDestroyedError, 44550 ClientClosedError, 44551 InvalidArgumentError 44552 } = __nccwpck_require__(8045) 44553 const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(2785) 44554 44555 const kDestroyed = Symbol('destroyed') 44556 const kClosed = Symbol('closed') 44557 const kOnDestroyed = Symbol('onDestroyed') 44558 const kOnClosed = Symbol('onClosed') 44559 const kInterceptedDispatch = Symbol('Intercepted Dispatch') 44560 44561 class DispatcherBase extends Dispatcher { 44562 constructor () { 44563 super() 44564 44565 this[kDestroyed] = false 44566 this[kOnDestroyed] = null 44567 this[kClosed] = false 44568 this[kOnClosed] = [] 44569 } 44570 44571 get destroyed () { 44572 return this[kDestroyed] 44573 } 44574 44575 get closed () { 44576 return this[kClosed] 44577 } 44578 44579 get interceptors () { 44580 return this[kInterceptors] 44581 } 44582 44583 set interceptors (newInterceptors) { 44584 if (newInterceptors) { 44585 for (let i = newInterceptors.length - 1; i >= 0; i--) { 44586 const interceptor = this[kInterceptors][i] 44587 if (typeof interceptor !== 'function') { 44588 throw new InvalidArgumentError('interceptor must be an function') 44589 } 44590 } 44591 } 44592 44593 this[kInterceptors] = newInterceptors 44594 } 44595 44596 close (callback) { 44597 if (callback === undefined) { 44598 return new Promise((resolve, reject) => { 44599 this.close((err, data) => { 44600 return err ? reject(err) : resolve(data) 44601 }) 44602 }) 44603 } 44604 44605 if (typeof callback !== 'function') { 44606 throw new InvalidArgumentError('invalid callback') 44607 } 44608 44609 if (this[kDestroyed]) { 44610 queueMicrotask(() => callback(new ClientDestroyedError(), null)) 44611 return 44612 } 44613 44614 if (this[kClosed]) { 44615 if (this[kOnClosed]) { 44616 this[kOnClosed].push(callback) 44617 } else { 44618 queueMicrotask(() => callback(null, null)) 44619 } 44620 return 44621 } 44622 44623 this[kClosed] = true 44624 this[kOnClosed].push(callback) 44625 44626 const onClosed = () => { 44627 const callbacks = this[kOnClosed] 44628 this[kOnClosed] = null 44629 for (let i = 0; i < callbacks.length; i++) { 44630 callbacks[i](null, null) 44631 } 44632 } 44633 44634 // Should not error. 44635 this[kClose]() 44636 .then(() => this.destroy()) 44637 .then(() => { 44638 queueMicrotask(onClosed) 44639 }) 44640 } 44641 44642 destroy (err, callback) { 44643 if (typeof err === 'function') { 44644 callback = err 44645 err = null 44646 } 44647 44648 if (callback === undefined) { 44649 return new Promise((resolve, reject) => { 44650 this.destroy(err, (err, data) => { 44651 return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) 44652 }) 44653 }) 44654 } 44655 44656 if (typeof callback !== 'function') { 44657 throw new InvalidArgumentError('invalid callback') 44658 } 44659 44660 if (this[kDestroyed]) { 44661 if (this[kOnDestroyed]) { 44662 this[kOnDestroyed].push(callback) 44663 } else { 44664 queueMicrotask(() => callback(null, null)) 44665 } 44666 return 44667 } 44668 44669 if (!err) { 44670 err = new ClientDestroyedError() 44671 } 44672 44673 this[kDestroyed] = true 44674 this[kOnDestroyed] = this[kOnDestroyed] || [] 44675 this[kOnDestroyed].push(callback) 44676 44677 const onDestroyed = () => { 44678 const callbacks = this[kOnDestroyed] 44679 this[kOnDestroyed] = null 44680 for (let i = 0; i < callbacks.length; i++) { 44681 callbacks[i](null, null) 44682 } 44683 } 44684 44685 // Should not error. 44686 this[kDestroy](err).then(() => { 44687 queueMicrotask(onDestroyed) 44688 }) 44689 } 44690 44691 [kInterceptedDispatch] (opts, handler) { 44692 if (!this[kInterceptors] || this[kInterceptors].length === 0) { 44693 this[kInterceptedDispatch] = this[kDispatch] 44694 return this[kDispatch](opts, handler) 44695 } 44696 44697 let dispatch = this[kDispatch].bind(this) 44698 for (let i = this[kInterceptors].length - 1; i >= 0; i--) { 44699 dispatch = this[kInterceptors][i](dispatch) 44700 } 44701 this[kInterceptedDispatch] = dispatch 44702 return dispatch(opts, handler) 44703 } 44704 44705 dispatch (opts, handler) { 44706 if (!handler || typeof handler !== 'object') { 44707 throw new InvalidArgumentError('handler must be an object') 44708 } 44709 44710 try { 44711 if (!opts || typeof opts !== 'object') { 44712 throw new InvalidArgumentError('opts must be an object.') 44713 } 44714 44715 if (this[kDestroyed] || this[kOnDestroyed]) { 44716 throw new ClientDestroyedError() 44717 } 44718 44719 if (this[kClosed]) { 44720 throw new ClientClosedError() 44721 } 44722 44723 return this[kInterceptedDispatch](opts, handler) 44724 } catch (err) { 44725 if (typeof handler.onError !== 'function') { 44726 throw new InvalidArgumentError('invalid onError method') 44727 } 44728 44729 handler.onError(err) 44730 44731 return false 44732 } 44733 } 44734 } 44735 44736 module.exports = DispatcherBase 44737 44738 44739 /***/ }), 44740 44741 /***/ 412: 44742 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 44743 44744 "use strict"; 44745 44746 44747 const EventEmitter = __nccwpck_require__(2361) 44748 44749 class Dispatcher extends EventEmitter { 44750 dispatch () { 44751 throw new Error('not implemented') 44752 } 44753 44754 close () { 44755 throw new Error('not implemented') 44756 } 44757 44758 destroy () { 44759 throw new Error('not implemented') 44760 } 44761 } 44762 44763 module.exports = Dispatcher 44764 44765 44766 /***/ }), 44767 44768 /***/ 1472: 44769 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 44770 44771 "use strict"; 44772 44773 44774 const Busboy = __nccwpck_require__(727) 44775 const util = __nccwpck_require__(3983) 44776 const { 44777 ReadableStreamFrom, 44778 isBlobLike, 44779 isReadableStreamLike, 44780 readableStreamClose, 44781 createDeferredPromise, 44782 fullyReadBody 44783 } = __nccwpck_require__(2538) 44784 const { FormData } = __nccwpck_require__(2015) 44785 const { kState } = __nccwpck_require__(5861) 44786 const { webidl } = __nccwpck_require__(1744) 44787 const { DOMException, structuredClone } = __nccwpck_require__(1037) 44788 const { Blob, File: NativeFile } = __nccwpck_require__(4300) 44789 const { kBodyUsed } = __nccwpck_require__(2785) 44790 const assert = __nccwpck_require__(9491) 44791 const { isErrored } = __nccwpck_require__(3983) 44792 const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) 44793 const { File: UndiciFile } = __nccwpck_require__(8511) 44794 const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) 44795 44796 let ReadableStream = globalThis.ReadableStream 44797 44798 /** @type {globalThis['File']} */ 44799 const File = NativeFile ?? UndiciFile 44800 const textEncoder = new TextEncoder() 44801 const textDecoder = new TextDecoder() 44802 44803 // https://fetch.spec.whatwg.org/#concept-bodyinit-extract 44804 function extractBody (object, keepalive = false) { 44805 if (!ReadableStream) { 44806 ReadableStream = (__nccwpck_require__(5356).ReadableStream) 44807 } 44808 44809 // 1. Let stream be null. 44810 let stream = null 44811 44812 // 2. If object is a ReadableStream object, then set stream to object. 44813 if (object instanceof ReadableStream) { 44814 stream = object 44815 } else if (isBlobLike(object)) { 44816 // 3. Otherwise, if object is a Blob object, set stream to the 44817 // result of running object’s get stream. 44818 stream = object.stream() 44819 } else { 44820 // 4. Otherwise, set stream to a new ReadableStream object, and set 44821 // up stream. 44822 stream = new ReadableStream({ 44823 async pull (controller) { 44824 controller.enqueue( 44825 typeof source === 'string' ? textEncoder.encode(source) : source 44826 ) 44827 queueMicrotask(() => readableStreamClose(controller)) 44828 }, 44829 start () {}, 44830 type: undefined 44831 }) 44832 } 44833 44834 // 5. Assert: stream is a ReadableStream object. 44835 assert(isReadableStreamLike(stream)) 44836 44837 // 6. Let action be null. 44838 let action = null 44839 44840 // 7. Let source be null. 44841 let source = null 44842 44843 // 8. Let length be null. 44844 let length = null 44845 44846 // 9. Let type be null. 44847 let type = null 44848 44849 // 10. Switch on object: 44850 if (typeof object === 'string') { 44851 // Set source to the UTF-8 encoding of object. 44852 // Note: setting source to a Uint8Array here breaks some mocking assumptions. 44853 source = object 44854 44855 // Set type to `text/plain;charset=UTF-8`. 44856 type = 'text/plain;charset=UTF-8' 44857 } else if (object instanceof URLSearchParams) { 44858 // URLSearchParams 44859 44860 // spec says to run application/x-www-form-urlencoded on body.list 44861 // this is implemented in Node.js as apart of an URLSearchParams instance toString method 44862 // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 44863 // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 44864 44865 // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. 44866 source = object.toString() 44867 44868 // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. 44869 type = 'application/x-www-form-urlencoded;charset=UTF-8' 44870 } else if (isArrayBuffer(object)) { 44871 // BufferSource/ArrayBuffer 44872 44873 // Set source to a copy of the bytes held by object. 44874 source = new Uint8Array(object.slice()) 44875 } else if (ArrayBuffer.isView(object)) { 44876 // BufferSource/ArrayBufferView 44877 44878 // Set source to a copy of the bytes held by object. 44879 source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) 44880 } else if (util.isFormDataLike(object)) { 44881 const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` 44882 const prefix = `--${boundary}\r\nContent-Disposition: form-data` 44883 44884 /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */ 44885 const escape = (str) => 44886 str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') 44887 const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') 44888 44889 // Set action to this step: run the multipart/form-data 44890 // encoding algorithm, with object’s entry list and UTF-8. 44891 // - This ensures that the body is immutable and can't be changed afterwords 44892 // - That the content-length is calculated in advance. 44893 // - And that all parts are pre-encoded and ready to be sent. 44894 44895 const blobParts = [] 44896 const rn = new Uint8Array([13, 10]) // '\r\n' 44897 length = 0 44898 let hasUnknownSizeValue = false 44899 44900 for (const [name, value] of object) { 44901 if (typeof value === 'string') { 44902 const chunk = textEncoder.encode(prefix + 44903 `; name="${escape(normalizeLinefeeds(name))}"` + 44904 `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) 44905 blobParts.push(chunk) 44906 length += chunk.byteLength 44907 } else { 44908 const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + 44909 (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + 44910 `Content-Type: ${ 44911 value.type || 'application/octet-stream' 44912 }\r\n\r\n`) 44913 blobParts.push(chunk, value, rn) 44914 if (typeof value.size === 'number') { 44915 length += chunk.byteLength + value.size + rn.byteLength 44916 } else { 44917 hasUnknownSizeValue = true 44918 } 44919 } 44920 } 44921 44922 const chunk = textEncoder.encode(`--${boundary}--`) 44923 blobParts.push(chunk) 44924 length += chunk.byteLength 44925 if (hasUnknownSizeValue) { 44926 length = null 44927 } 44928 44929 // Set source to object. 44930 source = object 44931 44932 action = async function * () { 44933 for (const part of blobParts) { 44934 if (part.stream) { 44935 yield * part.stream() 44936 } else { 44937 yield part 44938 } 44939 } 44940 } 44941 44942 // Set type to `multipart/form-data; boundary=`, 44943 // followed by the multipart/form-data boundary string generated 44944 // by the multipart/form-data encoding algorithm. 44945 type = 'multipart/form-data; boundary=' + boundary 44946 } else if (isBlobLike(object)) { 44947 // Blob 44948 44949 // Set source to object. 44950 source = object 44951 44952 // Set length to object’s size. 44953 length = object.size 44954 44955 // If object’s type attribute is not the empty byte sequence, set 44956 // type to its value. 44957 if (object.type) { 44958 type = object.type 44959 } 44960 } else if (typeof object[Symbol.asyncIterator] === 'function') { 44961 // If keepalive is true, then throw a TypeError. 44962 if (keepalive) { 44963 throw new TypeError('keepalive') 44964 } 44965 44966 // If object is disturbed or locked, then throw a TypeError. 44967 if (util.isDisturbed(object) || object.locked) { 44968 throw new TypeError( 44969 'Response body object should not be disturbed or locked' 44970 ) 44971 } 44972 44973 stream = 44974 object instanceof ReadableStream ? object : ReadableStreamFrom(object) 44975 } 44976 44977 // 11. If source is a byte sequence, then set action to a 44978 // step that returns source and length to source’s length. 44979 if (typeof source === 'string' || util.isBuffer(source)) { 44980 length = Buffer.byteLength(source) 44981 } 44982 44983 // 12. If action is non-null, then run these steps in in parallel: 44984 if (action != null) { 44985 // Run action. 44986 let iterator 44987 stream = new ReadableStream({ 44988 async start () { 44989 iterator = action(object)[Symbol.asyncIterator]() 44990 }, 44991 async pull (controller) { 44992 const { value, done } = await iterator.next() 44993 if (done) { 44994 // When running action is done, close stream. 44995 queueMicrotask(() => { 44996 controller.close() 44997 }) 44998 } else { 44999 // Whenever one or more bytes are available and stream is not errored, 45000 // enqueue a Uint8Array wrapping an ArrayBuffer containing the available 45001 // bytes into stream. 45002 if (!isErrored(stream)) { 45003 controller.enqueue(new Uint8Array(value)) 45004 } 45005 } 45006 return controller.desiredSize > 0 45007 }, 45008 async cancel (reason) { 45009 await iterator.return() 45010 }, 45011 type: undefined 45012 }) 45013 } 45014 45015 // 13. Let body be a body whose stream is stream, source is source, 45016 // and length is length. 45017 const body = { stream, source, length } 45018 45019 // 14. Return (body, type). 45020 return [body, type] 45021 } 45022 45023 // https://fetch.spec.whatwg.org/#bodyinit-safely-extract 45024 function safelyExtractBody (object, keepalive = false) { 45025 if (!ReadableStream) { 45026 // istanbul ignore next 45027 ReadableStream = (__nccwpck_require__(5356).ReadableStream) 45028 } 45029 45030 // To safely extract a body and a `Content-Type` value from 45031 // a byte sequence or BodyInit object object, run these steps: 45032 45033 // 1. If object is a ReadableStream object, then: 45034 if (object instanceof ReadableStream) { 45035 // Assert: object is neither disturbed nor locked. 45036 // istanbul ignore next 45037 assert(!util.isDisturbed(object), 'The body has already been consumed.') 45038 // istanbul ignore next 45039 assert(!object.locked, 'The stream is locked.') 45040 } 45041 45042 // 2. Return the results of extracting object. 45043 return extractBody(object, keepalive) 45044 } 45045 45046 function cloneBody (body) { 45047 // To clone a body body, run these steps: 45048 45049 // https://fetch.spec.whatwg.org/#concept-body-clone 45050 45051 // 1. Let « out1, out2 » be the result of teeing body’s stream. 45052 const [out1, out2] = body.stream.tee() 45053 const out2Clone = structuredClone(out2, { transfer: [out2] }) 45054 // This, for whatever reasons, unrefs out2Clone which allows 45055 // the process to exit by itself. 45056 const [, finalClone] = out2Clone.tee() 45057 45058 // 2. Set body’s stream to out1. 45059 body.stream = out1 45060 45061 // 3. Return a body whose stream is out2 and other members are copied from body. 45062 return { 45063 stream: finalClone, 45064 length: body.length, 45065 source: body.source 45066 } 45067 } 45068 45069 async function * consumeBody (body) { 45070 if (body) { 45071 if (isUint8Array(body)) { 45072 yield body 45073 } else { 45074 const stream = body.stream 45075 45076 if (util.isDisturbed(stream)) { 45077 throw new TypeError('The body has already been consumed.') 45078 } 45079 45080 if (stream.locked) { 45081 throw new TypeError('The stream is locked.') 45082 } 45083 45084 // Compat. 45085 stream[kBodyUsed] = true 45086 45087 yield * stream 45088 } 45089 } 45090 } 45091 45092 function throwIfAborted (state) { 45093 if (state.aborted) { 45094 throw new DOMException('The operation was aborted.', 'AbortError') 45095 } 45096 } 45097 45098 function bodyMixinMethods (instance) { 45099 const methods = { 45100 blob () { 45101 // The blob() method steps are to return the result of 45102 // running consume body with this and the following step 45103 // given a byte sequence bytes: return a Blob whose 45104 // contents are bytes and whose type attribute is this’s 45105 // MIME type. 45106 return specConsumeBody(this, (bytes) => { 45107 let mimeType = bodyMimeType(this) 45108 45109 if (mimeType === 'failure') { 45110 mimeType = '' 45111 } else if (mimeType) { 45112 mimeType = serializeAMimeType(mimeType) 45113 } 45114 45115 // Return a Blob whose contents are bytes and type attribute 45116 // is mimeType. 45117 return new Blob([bytes], { type: mimeType }) 45118 }, instance) 45119 }, 45120 45121 arrayBuffer () { 45122 // The arrayBuffer() method steps are to return the result 45123 // of running consume body with this and the following step 45124 // given a byte sequence bytes: return a new ArrayBuffer 45125 // whose contents are bytes. 45126 return specConsumeBody(this, (bytes) => { 45127 return new Uint8Array(bytes).buffer 45128 }, instance) 45129 }, 45130 45131 text () { 45132 // The text() method steps are to return the result of running 45133 // consume body with this and UTF-8 decode. 45134 return specConsumeBody(this, utf8DecodeBytes, instance) 45135 }, 45136 45137 json () { 45138 // The json() method steps are to return the result of running 45139 // consume body with this and parse JSON from bytes. 45140 return specConsumeBody(this, parseJSONFromBytes, instance) 45141 }, 45142 45143 async formData () { 45144 webidl.brandCheck(this, instance) 45145 45146 throwIfAborted(this[kState]) 45147 45148 const contentType = this.headers.get('Content-Type') 45149 45150 // If mimeType’s essence is "multipart/form-data", then: 45151 if (/multipart\/form-data/.test(contentType)) { 45152 const headers = {} 45153 for (const [key, value] of this.headers) headers[key.toLowerCase()] = value 45154 45155 const responseFormData = new FormData() 45156 45157 let busboy 45158 45159 try { 45160 busboy = new Busboy({ 45161 headers, 45162 preservePath: true 45163 }) 45164 } catch (err) { 45165 throw new DOMException(`${err}`, 'AbortError') 45166 } 45167 45168 busboy.on('field', (name, value) => { 45169 responseFormData.append(name, value) 45170 }) 45171 busboy.on('file', (name, value, filename, encoding, mimeType) => { 45172 const chunks = [] 45173 45174 if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { 45175 let base64chunk = '' 45176 45177 value.on('data', (chunk) => { 45178 base64chunk += chunk.toString().replace(/[\r\n]/gm, '') 45179 45180 const end = base64chunk.length - base64chunk.length % 4 45181 chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) 45182 45183 base64chunk = base64chunk.slice(end) 45184 }) 45185 value.on('end', () => { 45186 chunks.push(Buffer.from(base64chunk, 'base64')) 45187 responseFormData.append(name, new File(chunks, filename, { type: mimeType })) 45188 }) 45189 } else { 45190 value.on('data', (chunk) => { 45191 chunks.push(chunk) 45192 }) 45193 value.on('end', () => { 45194 responseFormData.append(name, new File(chunks, filename, { type: mimeType })) 45195 }) 45196 } 45197 }) 45198 45199 const busboyResolve = new Promise((resolve, reject) => { 45200 busboy.on('finish', resolve) 45201 busboy.on('error', (err) => reject(new TypeError(err))) 45202 }) 45203 45204 if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) 45205 busboy.end() 45206 await busboyResolve 45207 45208 return responseFormData 45209 } else if (/application\/x-www-form-urlencoded/.test(contentType)) { 45210 // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: 45211 45212 // 1. Let entries be the result of parsing bytes. 45213 let entries 45214 try { 45215 let text = '' 45216 // application/x-www-form-urlencoded parser will keep the BOM. 45217 // https://url.spec.whatwg.org/#concept-urlencoded-parser 45218 // Note that streaming decoder is stateful and cannot be reused 45219 const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) 45220 45221 for await (const chunk of consumeBody(this[kState].body)) { 45222 if (!isUint8Array(chunk)) { 45223 throw new TypeError('Expected Uint8Array chunk') 45224 } 45225 text += streamingDecoder.decode(chunk, { stream: true }) 45226 } 45227 text += streamingDecoder.decode() 45228 entries = new URLSearchParams(text) 45229 } catch (err) { 45230 // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. 45231 // 2. If entries is failure, then throw a TypeError. 45232 throw Object.assign(new TypeError(), { cause: err }) 45233 } 45234 45235 // 3. Return a new FormData object whose entries are entries. 45236 const formData = new FormData() 45237 for (const [name, value] of entries) { 45238 formData.append(name, value) 45239 } 45240 return formData 45241 } else { 45242 // Wait a tick before checking if the request has been aborted. 45243 // Otherwise, a TypeError can be thrown when an AbortError should. 45244 await Promise.resolve() 45245 45246 throwIfAborted(this[kState]) 45247 45248 // Otherwise, throw a TypeError. 45249 throw webidl.errors.exception({ 45250 header: `${instance.name}.formData`, 45251 message: 'Could not parse content as FormData.' 45252 }) 45253 } 45254 } 45255 } 45256 45257 return methods 45258 } 45259 45260 function mixinBody (prototype) { 45261 Object.assign(prototype.prototype, bodyMixinMethods(prototype)) 45262 } 45263 45264 /** 45265 * @see https://fetch.spec.whatwg.org/#concept-body-consume-body 45266 * @param {Response|Request} object 45267 * @param {(value: unknown) => unknown} convertBytesToJSValue 45268 * @param {Response|Request} instance 45269 */ 45270 async function specConsumeBody (object, convertBytesToJSValue, instance) { 45271 webidl.brandCheck(object, instance) 45272 45273 throwIfAborted(object[kState]) 45274 45275 // 1. If object is unusable, then return a promise rejected 45276 // with a TypeError. 45277 if (bodyUnusable(object[kState].body)) { 45278 throw new TypeError('Body is unusable') 45279 } 45280 45281 // 2. Let promise be a new promise. 45282 const promise = createDeferredPromise() 45283 45284 // 3. Let errorSteps given error be to reject promise with error. 45285 const errorSteps = (error) => promise.reject(error) 45286 45287 // 4. Let successSteps given a byte sequence data be to resolve 45288 // promise with the result of running convertBytesToJSValue 45289 // with data. If that threw an exception, then run errorSteps 45290 // with that exception. 45291 const successSteps = (data) => { 45292 try { 45293 promise.resolve(convertBytesToJSValue(data)) 45294 } catch (e) { 45295 errorSteps(e) 45296 } 45297 } 45298 45299 // 5. If object’s body is null, then run successSteps with an 45300 // empty byte sequence. 45301 if (object[kState].body == null) { 45302 successSteps(new Uint8Array()) 45303 return promise.promise 45304 } 45305 45306 // 6. Otherwise, fully read object’s body given successSteps, 45307 // errorSteps, and object’s relevant global object. 45308 await fullyReadBody(object[kState].body, successSteps, errorSteps) 45309 45310 // 7. Return promise. 45311 return promise.promise 45312 } 45313 45314 // https://fetch.spec.whatwg.org/#body-unusable 45315 function bodyUnusable (body) { 45316 // An object including the Body interface mixin is 45317 // said to be unusable if its body is non-null and 45318 // its body’s stream is disturbed or locked. 45319 return body != null && (body.stream.locked || util.isDisturbed(body.stream)) 45320 } 45321 45322 /** 45323 * @see https://encoding.spec.whatwg.org/#utf-8-decode 45324 * @param {Buffer} buffer 45325 */ 45326 function utf8DecodeBytes (buffer) { 45327 if (buffer.length === 0) { 45328 return '' 45329 } 45330 45331 // 1. Let buffer be the result of peeking three bytes from 45332 // ioQueue, converted to a byte sequence. 45333 45334 // 2. If buffer is 0xEF 0xBB 0xBF, then read three 45335 // bytes from ioQueue. (Do nothing with those bytes.) 45336 if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { 45337 buffer = buffer.subarray(3) 45338 } 45339 45340 // 3. Process a queue with an instance of UTF-8’s 45341 // decoder, ioQueue, output, and "replacement". 45342 const output = textDecoder.decode(buffer) 45343 45344 // 4. Return output. 45345 return output 45346 } 45347 45348 /** 45349 * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value 45350 * @param {Uint8Array} bytes 45351 */ 45352 function parseJSONFromBytes (bytes) { 45353 return JSON.parse(utf8DecodeBytes(bytes)) 45354 } 45355 45356 /** 45357 * @see https://fetch.spec.whatwg.org/#concept-body-mime-type 45358 * @param {import('./response').Response|import('./request').Request} object 45359 */ 45360 function bodyMimeType (object) { 45361 const { headersList } = object[kState] 45362 const contentType = headersList.get('content-type') 45363 45364 if (contentType === null) { 45365 return 'failure' 45366 } 45367 45368 return parseMIMEType(contentType) 45369 } 45370 45371 module.exports = { 45372 extractBody, 45373 safelyExtractBody, 45374 cloneBody, 45375 mixinBody 45376 } 45377 45378 45379 /***/ }), 45380 45381 /***/ 1037: 45382 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 45383 45384 "use strict"; 45385 45386 45387 const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) 45388 45389 const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] 45390 const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) 45391 45392 const nullBodyStatus = [101, 204, 205, 304] 45393 45394 const redirectStatus = [301, 302, 303, 307, 308] 45395 const redirectStatusSet = new Set(redirectStatus) 45396 45397 // https://fetch.spec.whatwg.org/#block-bad-port 45398 const badPorts = [ 45399 '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', 45400 '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', 45401 '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', 45402 '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', 45403 '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', 45404 '10080' 45405 ] 45406 45407 const badPortsSet = new Set(badPorts) 45408 45409 // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies 45410 const referrerPolicy = [ 45411 '', 45412 'no-referrer', 45413 'no-referrer-when-downgrade', 45414 'same-origin', 45415 'origin', 45416 'strict-origin', 45417 'origin-when-cross-origin', 45418 'strict-origin-when-cross-origin', 45419 'unsafe-url' 45420 ] 45421 const referrerPolicySet = new Set(referrerPolicy) 45422 45423 const requestRedirect = ['follow', 'manual', 'error'] 45424 45425 const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] 45426 const safeMethodsSet = new Set(safeMethods) 45427 45428 const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] 45429 45430 const requestCredentials = ['omit', 'same-origin', 'include'] 45431 45432 const requestCache = [ 45433 'default', 45434 'no-store', 45435 'reload', 45436 'no-cache', 45437 'force-cache', 45438 'only-if-cached' 45439 ] 45440 45441 // https://fetch.spec.whatwg.org/#request-body-header-name 45442 const requestBodyHeader = [ 45443 'content-encoding', 45444 'content-language', 45445 'content-location', 45446 'content-type', 45447 // See https://github.com/nodejs/undici/issues/2021 45448 // 'Content-Length' is a forbidden header name, which is typically 45449 // removed in the Headers implementation. However, undici doesn't 45450 // filter out headers, so we add it here. 45451 'content-length' 45452 ] 45453 45454 // https://fetch.spec.whatwg.org/#enumdef-requestduplex 45455 const requestDuplex = [ 45456 'half' 45457 ] 45458 45459 // http://fetch.spec.whatwg.org/#forbidden-method 45460 const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] 45461 const forbiddenMethodsSet = new Set(forbiddenMethods) 45462 45463 const subresource = [ 45464 'audio', 45465 'audioworklet', 45466 'font', 45467 'image', 45468 'manifest', 45469 'paintworklet', 45470 'script', 45471 'style', 45472 'track', 45473 'video', 45474 'xslt', 45475 '' 45476 ] 45477 const subresourceSet = new Set(subresource) 45478 45479 /** @type {globalThis['DOMException']} */ 45480 const DOMException = globalThis.DOMException ?? (() => { 45481 // DOMException was only made a global in Node v17.0.0, 45482 // but fetch supports >= v16.8. 45483 try { 45484 atob('~') 45485 } catch (err) { 45486 return Object.getPrototypeOf(err).constructor 45487 } 45488 })() 45489 45490 let channel 45491 45492 /** @type {globalThis['structuredClone']} */ 45493 const structuredClone = 45494 globalThis.structuredClone ?? 45495 // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js 45496 // structuredClone was added in v17.0.0, but fetch supports v16.8 45497 function structuredClone (value, options = undefined) { 45498 if (arguments.length === 0) { 45499 throw new TypeError('missing argument') 45500 } 45501 45502 if (!channel) { 45503 channel = new MessageChannel() 45504 } 45505 channel.port1.unref() 45506 channel.port2.unref() 45507 channel.port1.postMessage(value, options?.transfer) 45508 return receiveMessageOnPort(channel.port2).message 45509 } 45510 45511 module.exports = { 45512 DOMException, 45513 structuredClone, 45514 subresource, 45515 forbiddenMethods, 45516 requestBodyHeader, 45517 referrerPolicy, 45518 requestRedirect, 45519 requestMode, 45520 requestCredentials, 45521 requestCache, 45522 redirectStatus, 45523 corsSafeListedMethods, 45524 nullBodyStatus, 45525 safeMethods, 45526 badPorts, 45527 requestDuplex, 45528 subresourceSet, 45529 badPortsSet, 45530 redirectStatusSet, 45531 corsSafeListedMethodsSet, 45532 safeMethodsSet, 45533 forbiddenMethodsSet, 45534 referrerPolicySet 45535 } 45536 45537 45538 /***/ }), 45539 45540 /***/ 685: 45541 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 45542 45543 const assert = __nccwpck_require__(9491) 45544 const { atob } = __nccwpck_require__(4300) 45545 const { isomorphicDecode } = __nccwpck_require__(2538) 45546 45547 const encoder = new TextEncoder() 45548 45549 /** 45550 * @see https://mimesniff.spec.whatwg.org/#http-token-code-point 45551 */ 45552 const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ 45553 const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line 45554 /** 45555 * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point 45556 */ 45557 const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line 45558 45559 // https://fetch.spec.whatwg.org/#data-url-processor 45560 /** @param {URL} dataURL */ 45561 function dataURLProcessor (dataURL) { 45562 // 1. Assert: dataURL’s scheme is "data". 45563 assert(dataURL.protocol === 'data:') 45564 45565 // 2. Let input be the result of running the URL 45566 // serializer on dataURL with exclude fragment 45567 // set to true. 45568 let input = URLSerializer(dataURL, true) 45569 45570 // 3. Remove the leading "data:" string from input. 45571 input = input.slice(5) 45572 45573 // 4. Let position point at the start of input. 45574 const position = { position: 0 } 45575 45576 // 5. Let mimeType be the result of collecting a 45577 // sequence of code points that are not equal 45578 // to U+002C (,), given position. 45579 let mimeType = collectASequenceOfCodePointsFast( 45580 ',', 45581 input, 45582 position 45583 ) 45584 45585 // 6. Strip leading and trailing ASCII whitespace 45586 // from mimeType. 45587 // Undici implementation note: we need to store the 45588 // length because if the mimetype has spaces removed, 45589 // the wrong amount will be sliced from the input in 45590 // step #9 45591 const mimeTypeLength = mimeType.length 45592 mimeType = removeASCIIWhitespace(mimeType, true, true) 45593 45594 // 7. If position is past the end of input, then 45595 // return failure 45596 if (position.position >= input.length) { 45597 return 'failure' 45598 } 45599 45600 // 8. Advance position by 1. 45601 position.position++ 45602 45603 // 9. Let encodedBody be the remainder of input. 45604 const encodedBody = input.slice(mimeTypeLength + 1) 45605 45606 // 10. Let body be the percent-decoding of encodedBody. 45607 let body = stringPercentDecode(encodedBody) 45608 45609 // 11. If mimeType ends with U+003B (;), followed by 45610 // zero or more U+0020 SPACE, followed by an ASCII 45611 // case-insensitive match for "base64", then: 45612 if (/;(\u0020){0,}base64$/i.test(mimeType)) { 45613 // 1. Let stringBody be the isomorphic decode of body. 45614 const stringBody = isomorphicDecode(body) 45615 45616 // 2. Set body to the forgiving-base64 decode of 45617 // stringBody. 45618 body = forgivingBase64(stringBody) 45619 45620 // 3. If body is failure, then return failure. 45621 if (body === 'failure') { 45622 return 'failure' 45623 } 45624 45625 // 4. Remove the last 6 code points from mimeType. 45626 mimeType = mimeType.slice(0, -6) 45627 45628 // 5. Remove trailing U+0020 SPACE code points from mimeType, 45629 // if any. 45630 mimeType = mimeType.replace(/(\u0020)+$/, '') 45631 45632 // 6. Remove the last U+003B (;) code point from mimeType. 45633 mimeType = mimeType.slice(0, -1) 45634 } 45635 45636 // 12. If mimeType starts with U+003B (;), then prepend 45637 // "text/plain" to mimeType. 45638 if (mimeType.startsWith(';')) { 45639 mimeType = 'text/plain' + mimeType 45640 } 45641 45642 // 13. Let mimeTypeRecord be the result of parsing 45643 // mimeType. 45644 let mimeTypeRecord = parseMIMEType(mimeType) 45645 45646 // 14. If mimeTypeRecord is failure, then set 45647 // mimeTypeRecord to text/plain;charset=US-ASCII. 45648 if (mimeTypeRecord === 'failure') { 45649 mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') 45650 } 45651 45652 // 15. Return a new data: URL struct whose MIME 45653 // type is mimeTypeRecord and body is body. 45654 // https://fetch.spec.whatwg.org/#data-url-struct 45655 return { mimeType: mimeTypeRecord, body } 45656 } 45657 45658 // https://url.spec.whatwg.org/#concept-url-serializer 45659 /** 45660 * @param {URL} url 45661 * @param {boolean} excludeFragment 45662 */ 45663 function URLSerializer (url, excludeFragment = false) { 45664 if (!excludeFragment) { 45665 return url.href 45666 } 45667 45668 const href = url.href 45669 const hashLength = url.hash.length 45670 45671 return hashLength === 0 ? href : href.substring(0, href.length - hashLength) 45672 } 45673 45674 // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points 45675 /** 45676 * @param {(char: string) => boolean} condition 45677 * @param {string} input 45678 * @param {{ position: number }} position 45679 */ 45680 function collectASequenceOfCodePoints (condition, input, position) { 45681 // 1. Let result be the empty string. 45682 let result = '' 45683 45684 // 2. While position doesn’t point past the end of input and the 45685 // code point at position within input meets the condition condition: 45686 while (position.position < input.length && condition(input[position.position])) { 45687 // 1. Append that code point to the end of result. 45688 result += input[position.position] 45689 45690 // 2. Advance position by 1. 45691 position.position++ 45692 } 45693 45694 // 3. Return result. 45695 return result 45696 } 45697 45698 /** 45699 * A faster collectASequenceOfCodePoints that only works when comparing a single character. 45700 * @param {string} char 45701 * @param {string} input 45702 * @param {{ position: number }} position 45703 */ 45704 function collectASequenceOfCodePointsFast (char, input, position) { 45705 const idx = input.indexOf(char, position.position) 45706 const start = position.position 45707 45708 if (idx === -1) { 45709 position.position = input.length 45710 return input.slice(start) 45711 } 45712 45713 position.position = idx 45714 return input.slice(start, position.position) 45715 } 45716 45717 // https://url.spec.whatwg.org/#string-percent-decode 45718 /** @param {string} input */ 45719 function stringPercentDecode (input) { 45720 // 1. Let bytes be the UTF-8 encoding of input. 45721 const bytes = encoder.encode(input) 45722 45723 // 2. Return the percent-decoding of bytes. 45724 return percentDecode(bytes) 45725 } 45726 45727 // https://url.spec.whatwg.org/#percent-decode 45728 /** @param {Uint8Array} input */ 45729 function percentDecode (input) { 45730 // 1. Let output be an empty byte sequence. 45731 /** @type {number[]} */ 45732 const output = [] 45733 45734 // 2. For each byte byte in input: 45735 for (let i = 0; i < input.length; i++) { 45736 const byte = input[i] 45737 45738 // 1. If byte is not 0x25 (%), then append byte to output. 45739 if (byte !== 0x25) { 45740 output.push(byte) 45741 45742 // 2. Otherwise, if byte is 0x25 (%) and the next two bytes 45743 // after byte in input are not in the ranges 45744 // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), 45745 // and 0x61 (a) to 0x66 (f), all inclusive, append byte 45746 // to output. 45747 } else if ( 45748 byte === 0x25 && 45749 !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) 45750 ) { 45751 output.push(0x25) 45752 45753 // 3. Otherwise: 45754 } else { 45755 // 1. Let bytePoint be the two bytes after byte in input, 45756 // decoded, and then interpreted as hexadecimal number. 45757 const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) 45758 const bytePoint = Number.parseInt(nextTwoBytes, 16) 45759 45760 // 2. Append a byte whose value is bytePoint to output. 45761 output.push(bytePoint) 45762 45763 // 3. Skip the next two bytes in input. 45764 i += 2 45765 } 45766 } 45767 45768 // 3. Return output. 45769 return Uint8Array.from(output) 45770 } 45771 45772 // https://mimesniff.spec.whatwg.org/#parse-a-mime-type 45773 /** @param {string} input */ 45774 function parseMIMEType (input) { 45775 // 1. Remove any leading and trailing HTTP whitespace 45776 // from input. 45777 input = removeHTTPWhitespace(input, true, true) 45778 45779 // 2. Let position be a position variable for input, 45780 // initially pointing at the start of input. 45781 const position = { position: 0 } 45782 45783 // 3. Let type be the result of collecting a sequence 45784 // of code points that are not U+002F (/) from 45785 // input, given position. 45786 const type = collectASequenceOfCodePointsFast( 45787 '/', 45788 input, 45789 position 45790 ) 45791 45792 // 4. If type is the empty string or does not solely 45793 // contain HTTP token code points, then return failure. 45794 // https://mimesniff.spec.whatwg.org/#http-token-code-point 45795 if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { 45796 return 'failure' 45797 } 45798 45799 // 5. If position is past the end of input, then return 45800 // failure 45801 if (position.position > input.length) { 45802 return 'failure' 45803 } 45804 45805 // 6. Advance position by 1. (This skips past U+002F (/).) 45806 position.position++ 45807 45808 // 7. Let subtype be the result of collecting a sequence of 45809 // code points that are not U+003B (;) from input, given 45810 // position. 45811 let subtype = collectASequenceOfCodePointsFast( 45812 ';', 45813 input, 45814 position 45815 ) 45816 45817 // 8. Remove any trailing HTTP whitespace from subtype. 45818 subtype = removeHTTPWhitespace(subtype, false, true) 45819 45820 // 9. If subtype is the empty string or does not solely 45821 // contain HTTP token code points, then return failure. 45822 if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { 45823 return 'failure' 45824 } 45825 45826 const typeLowercase = type.toLowerCase() 45827 const subtypeLowercase = subtype.toLowerCase() 45828 45829 // 10. Let mimeType be a new MIME type record whose type 45830 // is type, in ASCII lowercase, and subtype is subtype, 45831 // in ASCII lowercase. 45832 // https://mimesniff.spec.whatwg.org/#mime-type 45833 const mimeType = { 45834 type: typeLowercase, 45835 subtype: subtypeLowercase, 45836 /** @type {Map<string, string>} */ 45837 parameters: new Map(), 45838 // https://mimesniff.spec.whatwg.org/#mime-type-essence 45839 essence: `${typeLowercase}/${subtypeLowercase}` 45840 } 45841 45842 // 11. While position is not past the end of input: 45843 while (position.position < input.length) { 45844 // 1. Advance position by 1. (This skips past U+003B (;).) 45845 position.position++ 45846 45847 // 2. Collect a sequence of code points that are HTTP 45848 // whitespace from input given position. 45849 collectASequenceOfCodePoints( 45850 // https://fetch.spec.whatwg.org/#http-whitespace 45851 char => HTTP_WHITESPACE_REGEX.test(char), 45852 input, 45853 position 45854 ) 45855 45856 // 3. Let parameterName be the result of collecting a 45857 // sequence of code points that are not U+003B (;) 45858 // or U+003D (=) from input, given position. 45859 let parameterName = collectASequenceOfCodePoints( 45860 (char) => char !== ';' && char !== '=', 45861 input, 45862 position 45863 ) 45864 45865 // 4. Set parameterName to parameterName, in ASCII 45866 // lowercase. 45867 parameterName = parameterName.toLowerCase() 45868 45869 // 5. If position is not past the end of input, then: 45870 if (position.position < input.length) { 45871 // 1. If the code point at position within input is 45872 // U+003B (;), then continue. 45873 if (input[position.position] === ';') { 45874 continue 45875 } 45876 45877 // 2. Advance position by 1. (This skips past U+003D (=).) 45878 position.position++ 45879 } 45880 45881 // 6. If position is past the end of input, then break. 45882 if (position.position > input.length) { 45883 break 45884 } 45885 45886 // 7. Let parameterValue be null. 45887 let parameterValue = null 45888 45889 // 8. If the code point at position within input is 45890 // U+0022 ("), then: 45891 if (input[position.position] === '"') { 45892 // 1. Set parameterValue to the result of collecting 45893 // an HTTP quoted string from input, given position 45894 // and the extract-value flag. 45895 parameterValue = collectAnHTTPQuotedString(input, position, true) 45896 45897 // 2. Collect a sequence of code points that are not 45898 // U+003B (;) from input, given position. 45899 collectASequenceOfCodePointsFast( 45900 ';', 45901 input, 45902 position 45903 ) 45904 45905 // 9. Otherwise: 45906 } else { 45907 // 1. Set parameterValue to the result of collecting 45908 // a sequence of code points that are not U+003B (;) 45909 // from input, given position. 45910 parameterValue = collectASequenceOfCodePointsFast( 45911 ';', 45912 input, 45913 position 45914 ) 45915 45916 // 2. Remove any trailing HTTP whitespace from parameterValue. 45917 parameterValue = removeHTTPWhitespace(parameterValue, false, true) 45918 45919 // 3. If parameterValue is the empty string, then continue. 45920 if (parameterValue.length === 0) { 45921 continue 45922 } 45923 } 45924 45925 // 10. If all of the following are true 45926 // - parameterName is not the empty string 45927 // - parameterName solely contains HTTP token code points 45928 // - parameterValue solely contains HTTP quoted-string token code points 45929 // - mimeType’s parameters[parameterName] does not exist 45930 // then set mimeType’s parameters[parameterName] to parameterValue. 45931 if ( 45932 parameterName.length !== 0 && 45933 HTTP_TOKEN_CODEPOINTS.test(parameterName) && 45934 (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && 45935 !mimeType.parameters.has(parameterName) 45936 ) { 45937 mimeType.parameters.set(parameterName, parameterValue) 45938 } 45939 } 45940 45941 // 12. Return mimeType. 45942 return mimeType 45943 } 45944 45945 // https://infra.spec.whatwg.org/#forgiving-base64-decode 45946 /** @param {string} data */ 45947 function forgivingBase64 (data) { 45948 // 1. Remove all ASCII whitespace from data. 45949 data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line 45950 45951 // 2. If data’s code point length divides by 4 leaving 45952 // no remainder, then: 45953 if (data.length % 4 === 0) { 45954 // 1. If data ends with one or two U+003D (=) code points, 45955 // then remove them from data. 45956 data = data.replace(/=?=$/, '') 45957 } 45958 45959 // 3. If data’s code point length divides by 4 leaving 45960 // a remainder of 1, then return failure. 45961 if (data.length % 4 === 1) { 45962 return 'failure' 45963 } 45964 45965 // 4. If data contains a code point that is not one of 45966 // U+002B (+) 45967 // U+002F (/) 45968 // ASCII alphanumeric 45969 // then return failure. 45970 if (/[^+/0-9A-Za-z]/.test(data)) { 45971 return 'failure' 45972 } 45973 45974 const binary = atob(data) 45975 const bytes = new Uint8Array(binary.length) 45976 45977 for (let byte = 0; byte < binary.length; byte++) { 45978 bytes[byte] = binary.charCodeAt(byte) 45979 } 45980 45981 return bytes 45982 } 45983 45984 // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string 45985 // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string 45986 /** 45987 * @param {string} input 45988 * @param {{ position: number }} position 45989 * @param {boolean?} extractValue 45990 */ 45991 function collectAnHTTPQuotedString (input, position, extractValue) { 45992 // 1. Let positionStart be position. 45993 const positionStart = position.position 45994 45995 // 2. Let value be the empty string. 45996 let value = '' 45997 45998 // 3. Assert: the code point at position within input 45999 // is U+0022 ("). 46000 assert(input[position.position] === '"') 46001 46002 // 4. Advance position by 1. 46003 position.position++ 46004 46005 // 5. While true: 46006 while (true) { 46007 // 1. Append the result of collecting a sequence of code points 46008 // that are not U+0022 (") or U+005C (\) from input, given 46009 // position, to value. 46010 value += collectASequenceOfCodePoints( 46011 (char) => char !== '"' && char !== '\\', 46012 input, 46013 position 46014 ) 46015 46016 // 2. If position is past the end of input, then break. 46017 if (position.position >= input.length) { 46018 break 46019 } 46020 46021 // 3. Let quoteOrBackslash be the code point at position within 46022 // input. 46023 const quoteOrBackslash = input[position.position] 46024 46025 // 4. Advance position by 1. 46026 position.position++ 46027 46028 // 5. If quoteOrBackslash is U+005C (\), then: 46029 if (quoteOrBackslash === '\\') { 46030 // 1. If position is past the end of input, then append 46031 // U+005C (\) to value and break. 46032 if (position.position >= input.length) { 46033 value += '\\' 46034 break 46035 } 46036 46037 // 2. Append the code point at position within input to value. 46038 value += input[position.position] 46039 46040 // 3. Advance position by 1. 46041 position.position++ 46042 46043 // 6. Otherwise: 46044 } else { 46045 // 1. Assert: quoteOrBackslash is U+0022 ("). 46046 assert(quoteOrBackslash === '"') 46047 46048 // 2. Break. 46049 break 46050 } 46051 } 46052 46053 // 6. If the extract-value flag is set, then return value. 46054 if (extractValue) { 46055 return value 46056 } 46057 46058 // 7. Return the code points from positionStart to position, 46059 // inclusive, within input. 46060 return input.slice(positionStart, position.position) 46061 } 46062 46063 /** 46064 * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type 46065 */ 46066 function serializeAMimeType (mimeType) { 46067 assert(mimeType !== 'failure') 46068 const { parameters, essence } = mimeType 46069 46070 // 1. Let serialization be the concatenation of mimeType’s 46071 // type, U+002F (/), and mimeType’s subtype. 46072 let serialization = essence 46073 46074 // 2. For each name → value of mimeType’s parameters: 46075 for (let [name, value] of parameters.entries()) { 46076 // 1. Append U+003B (;) to serialization. 46077 serialization += ';' 46078 46079 // 2. Append name to serialization. 46080 serialization += name 46081 46082 // 3. Append U+003D (=) to serialization. 46083 serialization += '=' 46084 46085 // 4. If value does not solely contain HTTP token code 46086 // points or value is the empty string, then: 46087 if (!HTTP_TOKEN_CODEPOINTS.test(value)) { 46088 // 1. Precede each occurence of U+0022 (") or 46089 // U+005C (\) in value with U+005C (\). 46090 value = value.replace(/(\\|")/g, '\\$1') 46091 46092 // 2. Prepend U+0022 (") to value. 46093 value = '"' + value 46094 46095 // 3. Append U+0022 (") to value. 46096 value += '"' 46097 } 46098 46099 // 5. Append value to serialization. 46100 serialization += value 46101 } 46102 46103 // 3. Return serialization. 46104 return serialization 46105 } 46106 46107 /** 46108 * @see https://fetch.spec.whatwg.org/#http-whitespace 46109 * @param {string} char 46110 */ 46111 function isHTTPWhiteSpace (char) { 46112 return char === '\r' || char === '\n' || char === '\t' || char === ' ' 46113 } 46114 46115 /** 46116 * @see https://fetch.spec.whatwg.org/#http-whitespace 46117 * @param {string} str 46118 */ 46119 function removeHTTPWhitespace (str, leading = true, trailing = true) { 46120 let lead = 0 46121 let trail = str.length - 1 46122 46123 if (leading) { 46124 for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); 46125 } 46126 46127 if (trailing) { 46128 for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); 46129 } 46130 46131 return str.slice(lead, trail + 1) 46132 } 46133 46134 /** 46135 * @see https://infra.spec.whatwg.org/#ascii-whitespace 46136 * @param {string} char 46137 */ 46138 function isASCIIWhitespace (char) { 46139 return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' 46140 } 46141 46142 /** 46143 * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace 46144 */ 46145 function removeASCIIWhitespace (str, leading = true, trailing = true) { 46146 let lead = 0 46147 let trail = str.length - 1 46148 46149 if (leading) { 46150 for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); 46151 } 46152 46153 if (trailing) { 46154 for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); 46155 } 46156 46157 return str.slice(lead, trail + 1) 46158 } 46159 46160 module.exports = { 46161 dataURLProcessor, 46162 URLSerializer, 46163 collectASequenceOfCodePoints, 46164 collectASequenceOfCodePointsFast, 46165 stringPercentDecode, 46166 parseMIMEType, 46167 collectAnHTTPQuotedString, 46168 serializeAMimeType 46169 } 46170 46171 46172 /***/ }), 46173 46174 /***/ 8511: 46175 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 46176 46177 "use strict"; 46178 46179 46180 const { Blob, File: NativeFile } = __nccwpck_require__(4300) 46181 const { types } = __nccwpck_require__(3837) 46182 const { kState } = __nccwpck_require__(5861) 46183 const { isBlobLike } = __nccwpck_require__(2538) 46184 const { webidl } = __nccwpck_require__(1744) 46185 const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) 46186 const { kEnumerableProperty } = __nccwpck_require__(3983) 46187 const encoder = new TextEncoder() 46188 46189 class File extends Blob { 46190 constructor (fileBits, fileName, options = {}) { 46191 // The File constructor is invoked with two or three parameters, depending 46192 // on whether the optional dictionary parameter is used. When the File() 46193 // constructor is invoked, user agents must run the following steps: 46194 webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) 46195 46196 fileBits = webidl.converters['sequence<BlobPart>'](fileBits) 46197 fileName = webidl.converters.USVString(fileName) 46198 options = webidl.converters.FilePropertyBag(options) 46199 46200 // 1. Let bytes be the result of processing blob parts given fileBits and 46201 // options. 46202 // Note: Blob handles this for us 46203 46204 // 2. Let n be the fileName argument to the constructor. 46205 const n = fileName 46206 46207 // 3. Process FilePropertyBag dictionary argument by running the following 46208 // substeps: 46209 46210 // 1. If the type member is provided and is not the empty string, let t 46211 // be set to the type dictionary member. If t contains any characters 46212 // outside the range U+0020 to U+007E, then set t to the empty string 46213 // and return from these substeps. 46214 // 2. Convert every character in t to ASCII lowercase. 46215 let t = options.type 46216 let d 46217 46218 // eslint-disable-next-line no-labels 46219 substep: { 46220 if (t) { 46221 t = parseMIMEType(t) 46222 46223 if (t === 'failure') { 46224 t = '' 46225 // eslint-disable-next-line no-labels 46226 break substep 46227 } 46228 46229 t = serializeAMimeType(t).toLowerCase() 46230 } 46231 46232 // 3. If the lastModified member is provided, let d be set to the 46233 // lastModified dictionary member. If it is not provided, set d to the 46234 // current date and time represented as the number of milliseconds since 46235 // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). 46236 d = options.lastModified 46237 } 46238 46239 // 4. Return a new File object F such that: 46240 // F refers to the bytes byte sequence. 46241 // F.size is set to the number of total bytes in bytes. 46242 // F.name is set to n. 46243 // F.type is set to t. 46244 // F.lastModified is set to d. 46245 46246 super(processBlobParts(fileBits, options), { type: t }) 46247 this[kState] = { 46248 name: n, 46249 lastModified: d, 46250 type: t 46251 } 46252 } 46253 46254 get name () { 46255 webidl.brandCheck(this, File) 46256 46257 return this[kState].name 46258 } 46259 46260 get lastModified () { 46261 webidl.brandCheck(this, File) 46262 46263 return this[kState].lastModified 46264 } 46265 46266 get type () { 46267 webidl.brandCheck(this, File) 46268 46269 return this[kState].type 46270 } 46271 } 46272 46273 class FileLike { 46274 constructor (blobLike, fileName, options = {}) { 46275 // TODO: argument idl type check 46276 46277 // The File constructor is invoked with two or three parameters, depending 46278 // on whether the optional dictionary parameter is used. When the File() 46279 // constructor is invoked, user agents must run the following steps: 46280 46281 // 1. Let bytes be the result of processing blob parts given fileBits and 46282 // options. 46283 46284 // 2. Let n be the fileName argument to the constructor. 46285 const n = fileName 46286 46287 // 3. Process FilePropertyBag dictionary argument by running the following 46288 // substeps: 46289 46290 // 1. If the type member is provided and is not the empty string, let t 46291 // be set to the type dictionary member. If t contains any characters 46292 // outside the range U+0020 to U+007E, then set t to the empty string 46293 // and return from these substeps. 46294 // TODO 46295 const t = options.type 46296 46297 // 2. Convert every character in t to ASCII lowercase. 46298 // TODO 46299 46300 // 3. If the lastModified member is provided, let d be set to the 46301 // lastModified dictionary member. If it is not provided, set d to the 46302 // current date and time represented as the number of milliseconds since 46303 // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). 46304 const d = options.lastModified ?? Date.now() 46305 46306 // 4. Return a new File object F such that: 46307 // F refers to the bytes byte sequence. 46308 // F.size is set to the number of total bytes in bytes. 46309 // F.name is set to n. 46310 // F.type is set to t. 46311 // F.lastModified is set to d. 46312 46313 this[kState] = { 46314 blobLike, 46315 name: n, 46316 type: t, 46317 lastModified: d 46318 } 46319 } 46320 46321 stream (...args) { 46322 webidl.brandCheck(this, FileLike) 46323 46324 return this[kState].blobLike.stream(...args) 46325 } 46326 46327 arrayBuffer (...args) { 46328 webidl.brandCheck(this, FileLike) 46329 46330 return this[kState].blobLike.arrayBuffer(...args) 46331 } 46332 46333 slice (...args) { 46334 webidl.brandCheck(this, FileLike) 46335 46336 return this[kState].blobLike.slice(...args) 46337 } 46338 46339 text (...args) { 46340 webidl.brandCheck(this, FileLike) 46341 46342 return this[kState].blobLike.text(...args) 46343 } 46344 46345 get size () { 46346 webidl.brandCheck(this, FileLike) 46347 46348 return this[kState].blobLike.size 46349 } 46350 46351 get type () { 46352 webidl.brandCheck(this, FileLike) 46353 46354 return this[kState].blobLike.type 46355 } 46356 46357 get name () { 46358 webidl.brandCheck(this, FileLike) 46359 46360 return this[kState].name 46361 } 46362 46363 get lastModified () { 46364 webidl.brandCheck(this, FileLike) 46365 46366 return this[kState].lastModified 46367 } 46368 46369 get [Symbol.toStringTag] () { 46370 return 'File' 46371 } 46372 } 46373 46374 Object.defineProperties(File.prototype, { 46375 [Symbol.toStringTag]: { 46376 value: 'File', 46377 configurable: true 46378 }, 46379 name: kEnumerableProperty, 46380 lastModified: kEnumerableProperty 46381 }) 46382 46383 webidl.converters.Blob = webidl.interfaceConverter(Blob) 46384 46385 webidl.converters.BlobPart = function (V, opts) { 46386 if (webidl.util.Type(V) === 'Object') { 46387 if (isBlobLike(V)) { 46388 return webidl.converters.Blob(V, { strict: false }) 46389 } 46390 46391 if ( 46392 ArrayBuffer.isView(V) || 46393 types.isAnyArrayBuffer(V) 46394 ) { 46395 return webidl.converters.BufferSource(V, opts) 46396 } 46397 } 46398 46399 return webidl.converters.USVString(V, opts) 46400 } 46401 46402 webidl.converters['sequence<BlobPart>'] = webidl.sequenceConverter( 46403 webidl.converters.BlobPart 46404 ) 46405 46406 // https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag 46407 webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ 46408 { 46409 key: 'lastModified', 46410 converter: webidl.converters['long long'], 46411 get defaultValue () { 46412 return Date.now() 46413 } 46414 }, 46415 { 46416 key: 'type', 46417 converter: webidl.converters.DOMString, 46418 defaultValue: '' 46419 }, 46420 { 46421 key: 'endings', 46422 converter: (value) => { 46423 value = webidl.converters.DOMString(value) 46424 value = value.toLowerCase() 46425 46426 if (value !== 'native') { 46427 value = 'transparent' 46428 } 46429 46430 return value 46431 }, 46432 defaultValue: 'transparent' 46433 } 46434 ]) 46435 46436 /** 46437 * @see https://www.w3.org/TR/FileAPI/#process-blob-parts 46438 * @param {(NodeJS.TypedArray|Blob|string)[]} parts 46439 * @param {{ type: string, endings: string }} options 46440 */ 46441 function processBlobParts (parts, options) { 46442 // 1. Let bytes be an empty sequence of bytes. 46443 /** @type {NodeJS.TypedArray[]} */ 46444 const bytes = [] 46445 46446 // 2. For each element in parts: 46447 for (const element of parts) { 46448 // 1. If element is a USVString, run the following substeps: 46449 if (typeof element === 'string') { 46450 // 1. Let s be element. 46451 let s = element 46452 46453 // 2. If the endings member of options is "native", set s 46454 // to the result of converting line endings to native 46455 // of element. 46456 if (options.endings === 'native') { 46457 s = convertLineEndingsNative(s) 46458 } 46459 46460 // 3. Append the result of UTF-8 encoding s to bytes. 46461 bytes.push(encoder.encode(s)) 46462 } else if ( 46463 types.isAnyArrayBuffer(element) || 46464 types.isTypedArray(element) 46465 ) { 46466 // 2. If element is a BufferSource, get a copy of the 46467 // bytes held by the buffer source, and append those 46468 // bytes to bytes. 46469 if (!element.buffer) { // ArrayBuffer 46470 bytes.push(new Uint8Array(element)) 46471 } else { 46472 bytes.push( 46473 new Uint8Array(element.buffer, element.byteOffset, element.byteLength) 46474 ) 46475 } 46476 } else if (isBlobLike(element)) { 46477 // 3. If element is a Blob, append the bytes it represents 46478 // to bytes. 46479 bytes.push(element) 46480 } 46481 } 46482 46483 // 3. Return bytes. 46484 return bytes 46485 } 46486 46487 /** 46488 * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native 46489 * @param {string} s 46490 */ 46491 function convertLineEndingsNative (s) { 46492 // 1. Let native line ending be be the code point U+000A LF. 46493 let nativeLineEnding = '\n' 46494 46495 // 2. If the underlying platform’s conventions are to 46496 // represent newlines as a carriage return and line feed 46497 // sequence, set native line ending to the code point 46498 // U+000D CR followed by the code point U+000A LF. 46499 if (process.platform === 'win32') { 46500 nativeLineEnding = '\r\n' 46501 } 46502 46503 return s.replace(/\r?\n/g, nativeLineEnding) 46504 } 46505 46506 // If this function is moved to ./util.js, some tools (such as 46507 // rollup) will warn about circular dependencies. See: 46508 // https://github.com/nodejs/undici/issues/1629 46509 function isFileLike (object) { 46510 return ( 46511 (NativeFile && object instanceof NativeFile) || 46512 object instanceof File || ( 46513 object && 46514 (typeof object.stream === 'function' || 46515 typeof object.arrayBuffer === 'function') && 46516 object[Symbol.toStringTag] === 'File' 46517 ) 46518 ) 46519 } 46520 46521 module.exports = { File, FileLike, isFileLike } 46522 46523 46524 /***/ }), 46525 46526 /***/ 2015: 46527 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 46528 46529 "use strict"; 46530 46531 46532 const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(2538) 46533 const { kState } = __nccwpck_require__(5861) 46534 const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(8511) 46535 const { webidl } = __nccwpck_require__(1744) 46536 const { Blob, File: NativeFile } = __nccwpck_require__(4300) 46537 46538 /** @type {globalThis['File']} */ 46539 const File = NativeFile ?? UndiciFile 46540 46541 // https://xhr.spec.whatwg.org/#formdata 46542 class FormData { 46543 constructor (form) { 46544 if (form !== undefined) { 46545 throw webidl.errors.conversionFailed({ 46546 prefix: 'FormData constructor', 46547 argument: 'Argument 1', 46548 types: ['undefined'] 46549 }) 46550 } 46551 46552 this[kState] = [] 46553 } 46554 46555 append (name, value, filename = undefined) { 46556 webidl.brandCheck(this, FormData) 46557 46558 webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) 46559 46560 if (arguments.length === 3 && !isBlobLike(value)) { 46561 throw new TypeError( 46562 "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" 46563 ) 46564 } 46565 46566 // 1. Let value be value if given; otherwise blobValue. 46567 46568 name = webidl.converters.USVString(name) 46569 value = isBlobLike(value) 46570 ? webidl.converters.Blob(value, { strict: false }) 46571 : webidl.converters.USVString(value) 46572 filename = arguments.length === 3 46573 ? webidl.converters.USVString(filename) 46574 : undefined 46575 46576 // 2. Let entry be the result of creating an entry with 46577 // name, value, and filename if given. 46578 const entry = makeEntry(name, value, filename) 46579 46580 // 3. Append entry to this’s entry list. 46581 this[kState].push(entry) 46582 } 46583 46584 delete (name) { 46585 webidl.brandCheck(this, FormData) 46586 46587 webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) 46588 46589 name = webidl.converters.USVString(name) 46590 46591 // The delete(name) method steps are to remove all entries whose name 46592 // is name from this’s entry list. 46593 this[kState] = this[kState].filter(entry => entry.name !== name) 46594 } 46595 46596 get (name) { 46597 webidl.brandCheck(this, FormData) 46598 46599 webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) 46600 46601 name = webidl.converters.USVString(name) 46602 46603 // 1. If there is no entry whose name is name in this’s entry list, 46604 // then return null. 46605 const idx = this[kState].findIndex((entry) => entry.name === name) 46606 if (idx === -1) { 46607 return null 46608 } 46609 46610 // 2. Return the value of the first entry whose name is name from 46611 // this’s entry list. 46612 return this[kState][idx].value 46613 } 46614 46615 getAll (name) { 46616 webidl.brandCheck(this, FormData) 46617 46618 webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) 46619 46620 name = webidl.converters.USVString(name) 46621 46622 // 1. If there is no entry whose name is name in this’s entry list, 46623 // then return the empty list. 46624 // 2. Return the values of all entries whose name is name, in order, 46625 // from this’s entry list. 46626 return this[kState] 46627 .filter((entry) => entry.name === name) 46628 .map((entry) => entry.value) 46629 } 46630 46631 has (name) { 46632 webidl.brandCheck(this, FormData) 46633 46634 webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) 46635 46636 name = webidl.converters.USVString(name) 46637 46638 // The has(name) method steps are to return true if there is an entry 46639 // whose name is name in this’s entry list; otherwise false. 46640 return this[kState].findIndex((entry) => entry.name === name) !== -1 46641 } 46642 46643 set (name, value, filename = undefined) { 46644 webidl.brandCheck(this, FormData) 46645 46646 webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) 46647 46648 if (arguments.length === 3 && !isBlobLike(value)) { 46649 throw new TypeError( 46650 "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" 46651 ) 46652 } 46653 46654 // The set(name, value) and set(name, blobValue, filename) method steps 46655 // are: 46656 46657 // 1. Let value be value if given; otherwise blobValue. 46658 46659 name = webidl.converters.USVString(name) 46660 value = isBlobLike(value) 46661 ? webidl.converters.Blob(value, { strict: false }) 46662 : webidl.converters.USVString(value) 46663 filename = arguments.length === 3 46664 ? toUSVString(filename) 46665 : undefined 46666 46667 // 2. Let entry be the result of creating an entry with name, value, and 46668 // filename if given. 46669 const entry = makeEntry(name, value, filename) 46670 46671 // 3. If there are entries in this’s entry list whose name is name, then 46672 // replace the first such entry with entry and remove the others. 46673 const idx = this[kState].findIndex((entry) => entry.name === name) 46674 if (idx !== -1) { 46675 this[kState] = [ 46676 ...this[kState].slice(0, idx), 46677 entry, 46678 ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) 46679 ] 46680 } else { 46681 // 4. Otherwise, append entry to this’s entry list. 46682 this[kState].push(entry) 46683 } 46684 } 46685 46686 entries () { 46687 webidl.brandCheck(this, FormData) 46688 46689 return makeIterator( 46690 () => this[kState].map(pair => [pair.name, pair.value]), 46691 'FormData', 46692 'key+value' 46693 ) 46694 } 46695 46696 keys () { 46697 webidl.brandCheck(this, FormData) 46698 46699 return makeIterator( 46700 () => this[kState].map(pair => [pair.name, pair.value]), 46701 'FormData', 46702 'key' 46703 ) 46704 } 46705 46706 values () { 46707 webidl.brandCheck(this, FormData) 46708 46709 return makeIterator( 46710 () => this[kState].map(pair => [pair.name, pair.value]), 46711 'FormData', 46712 'value' 46713 ) 46714 } 46715 46716 /** 46717 * @param {(value: string, key: string, self: FormData) => void} callbackFn 46718 * @param {unknown} thisArg 46719 */ 46720 forEach (callbackFn, thisArg = globalThis) { 46721 webidl.brandCheck(this, FormData) 46722 46723 webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) 46724 46725 if (typeof callbackFn !== 'function') { 46726 throw new TypeError( 46727 "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." 46728 ) 46729 } 46730 46731 for (const [key, value] of this) { 46732 callbackFn.apply(thisArg, [value, key, this]) 46733 } 46734 } 46735 } 46736 46737 FormData.prototype[Symbol.iterator] = FormData.prototype.entries 46738 46739 Object.defineProperties(FormData.prototype, { 46740 [Symbol.toStringTag]: { 46741 value: 'FormData', 46742 configurable: true 46743 } 46744 }) 46745 46746 /** 46747 * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry 46748 * @param {string} name 46749 * @param {string|Blob} value 46750 * @param {?string} filename 46751 * @returns 46752 */ 46753 function makeEntry (name, value, filename) { 46754 // 1. Set name to the result of converting name into a scalar value string. 46755 // "To convert a string into a scalar value string, replace any surrogates 46756 // with U+FFFD." 46757 // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end 46758 name = Buffer.from(name).toString('utf8') 46759 46760 // 2. If value is a string, then set value to the result of converting 46761 // value into a scalar value string. 46762 if (typeof value === 'string') { 46763 value = Buffer.from(value).toString('utf8') 46764 } else { 46765 // 3. Otherwise: 46766 46767 // 1. If value is not a File object, then set value to a new File object, 46768 // representing the same bytes, whose name attribute value is "blob" 46769 if (!isFileLike(value)) { 46770 value = value instanceof Blob 46771 ? new File([value], 'blob', { type: value.type }) 46772 : new FileLike(value, 'blob', { type: value.type }) 46773 } 46774 46775 // 2. If filename is given, then set value to a new File object, 46776 // representing the same bytes, whose name attribute is filename. 46777 if (filename !== undefined) { 46778 /** @type {FilePropertyBag} */ 46779 const options = { 46780 type: value.type, 46781 lastModified: value.lastModified 46782 } 46783 46784 value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile 46785 ? new File([value], filename, options) 46786 : new FileLike(value, filename, options) 46787 } 46788 } 46789 46790 // 4. Return an entry whose name is name and whose value is value. 46791 return { name, value } 46792 } 46793 46794 module.exports = { FormData } 46795 46796 46797 /***/ }), 46798 46799 /***/ 1246: 46800 /***/ ((module) => { 46801 46802 "use strict"; 46803 46804 46805 // In case of breaking changes, increase the version 46806 // number to avoid conflicts. 46807 const globalOrigin = Symbol.for('undici.globalOrigin.1') 46808 46809 function getGlobalOrigin () { 46810 return globalThis[globalOrigin] 46811 } 46812 46813 function setGlobalOrigin (newOrigin) { 46814 if (newOrigin === undefined) { 46815 Object.defineProperty(globalThis, globalOrigin, { 46816 value: undefined, 46817 writable: true, 46818 enumerable: false, 46819 configurable: false 46820 }) 46821 46822 return 46823 } 46824 46825 const parsedURL = new URL(newOrigin) 46826 46827 if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { 46828 throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) 46829 } 46830 46831 Object.defineProperty(globalThis, globalOrigin, { 46832 value: parsedURL, 46833 writable: true, 46834 enumerable: false, 46835 configurable: false 46836 }) 46837 } 46838 46839 module.exports = { 46840 getGlobalOrigin, 46841 setGlobalOrigin 46842 } 46843 46844 46845 /***/ }), 46846 46847 /***/ 554: 46848 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 46849 46850 "use strict"; 46851 // https://github.com/Ethan-Arrowood/undici-fetch 46852 46853 46854 46855 const { kHeadersList, kConstruct } = __nccwpck_require__(2785) 46856 const { kGuard } = __nccwpck_require__(5861) 46857 const { kEnumerableProperty } = __nccwpck_require__(3983) 46858 const { 46859 makeIterator, 46860 isValidHeaderName, 46861 isValidHeaderValue 46862 } = __nccwpck_require__(2538) 46863 const { webidl } = __nccwpck_require__(1744) 46864 const assert = __nccwpck_require__(9491) 46865 46866 const kHeadersMap = Symbol('headers map') 46867 const kHeadersSortedMap = Symbol('headers map sorted') 46868 46869 /** 46870 * @param {number} code 46871 */ 46872 function isHTTPWhiteSpaceCharCode (code) { 46873 return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 46874 } 46875 46876 /** 46877 * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize 46878 * @param {string} potentialValue 46879 */ 46880 function headerValueNormalize (potentialValue) { 46881 // To normalize a byte sequence potentialValue, remove 46882 // any leading and trailing HTTP whitespace bytes from 46883 // potentialValue. 46884 let i = 0; let j = potentialValue.length 46885 46886 while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j 46887 while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i 46888 46889 return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) 46890 } 46891 46892 function fill (headers, object) { 46893 // To fill a Headers object headers with a given object object, run these steps: 46894 46895 // 1. If object is a sequence, then for each header in object: 46896 // Note: webidl conversion to array has already been done. 46897 if (Array.isArray(object)) { 46898 for (let i = 0; i < object.length; ++i) { 46899 const header = object[i] 46900 // 1. If header does not contain exactly two items, then throw a TypeError. 46901 if (header.length !== 2) { 46902 throw webidl.errors.exception({ 46903 header: 'Headers constructor', 46904 message: `expected name/value pair to be length 2, found ${header.length}.` 46905 }) 46906 } 46907 46908 // 2. Append (header’s first item, header’s second item) to headers. 46909 appendHeader(headers, header[0], header[1]) 46910 } 46911 } else if (typeof object === 'object' && object !== null) { 46912 // Note: null should throw 46913 46914 // 2. Otherwise, object is a record, then for each key → value in object, 46915 // append (key, value) to headers 46916 const keys = Object.keys(object) 46917 for (let i = 0; i < keys.length; ++i) { 46918 appendHeader(headers, keys[i], object[keys[i]]) 46919 } 46920 } else { 46921 throw webidl.errors.conversionFailed({ 46922 prefix: 'Headers constructor', 46923 argument: 'Argument 1', 46924 types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>'] 46925 }) 46926 } 46927 } 46928 46929 /** 46930 * @see https://fetch.spec.whatwg.org/#concept-headers-append 46931 */ 46932 function appendHeader (headers, name, value) { 46933 // 1. Normalize value. 46934 value = headerValueNormalize(value) 46935 46936 // 2. If name is not a header name or value is not a 46937 // header value, then throw a TypeError. 46938 if (!isValidHeaderName(name)) { 46939 throw webidl.errors.invalidArgument({ 46940 prefix: 'Headers.append', 46941 value: name, 46942 type: 'header name' 46943 }) 46944 } else if (!isValidHeaderValue(value)) { 46945 throw webidl.errors.invalidArgument({ 46946 prefix: 'Headers.append', 46947 value, 46948 type: 'header value' 46949 }) 46950 } 46951 46952 // 3. If headers’s guard is "immutable", then throw a TypeError. 46953 // 4. Otherwise, if headers’s guard is "request" and name is a 46954 // forbidden header name, return. 46955 // Note: undici does not implement forbidden header names 46956 if (headers[kGuard] === 'immutable') { 46957 throw new TypeError('immutable') 46958 } else if (headers[kGuard] === 'request-no-cors') { 46959 // 5. Otherwise, if headers’s guard is "request-no-cors": 46960 // TODO 46961 } 46962 46963 // 6. Otherwise, if headers’s guard is "response" and name is a 46964 // forbidden response-header name, return. 46965 46966 // 7. Append (name, value) to headers’s header list. 46967 return headers[kHeadersList].append(name, value) 46968 46969 // 8. If headers’s guard is "request-no-cors", then remove 46970 // privileged no-CORS request headers from headers 46971 } 46972 46973 class HeadersList { 46974 /** @type {[string, string][]|null} */ 46975 cookies = null 46976 46977 constructor (init) { 46978 if (init instanceof HeadersList) { 46979 this[kHeadersMap] = new Map(init[kHeadersMap]) 46980 this[kHeadersSortedMap] = init[kHeadersSortedMap] 46981 this.cookies = init.cookies === null ? null : [...init.cookies] 46982 } else { 46983 this[kHeadersMap] = new Map(init) 46984 this[kHeadersSortedMap] = null 46985 } 46986 } 46987 46988 // https://fetch.spec.whatwg.org/#header-list-contains 46989 contains (name) { 46990 // A header list list contains a header name name if list 46991 // contains a header whose name is a byte-case-insensitive 46992 // match for name. 46993 name = name.toLowerCase() 46994 46995 return this[kHeadersMap].has(name) 46996 } 46997 46998 clear () { 46999 this[kHeadersMap].clear() 47000 this[kHeadersSortedMap] = null 47001 this.cookies = null 47002 } 47003 47004 // https://fetch.spec.whatwg.org/#concept-header-list-append 47005 append (name, value) { 47006 this[kHeadersSortedMap] = null 47007 47008 // 1. If list contains name, then set name to the first such 47009 // header’s name. 47010 const lowercaseName = name.toLowerCase() 47011 const exists = this[kHeadersMap].get(lowercaseName) 47012 47013 // 2. Append (name, value) to list. 47014 if (exists) { 47015 const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' 47016 this[kHeadersMap].set(lowercaseName, { 47017 name: exists.name, 47018 value: `${exists.value}${delimiter}${value}` 47019 }) 47020 } else { 47021 this[kHeadersMap].set(lowercaseName, { name, value }) 47022 } 47023 47024 if (lowercaseName === 'set-cookie') { 47025 this.cookies ??= [] 47026 this.cookies.push(value) 47027 } 47028 } 47029 47030 // https://fetch.spec.whatwg.org/#concept-header-list-set 47031 set (name, value) { 47032 this[kHeadersSortedMap] = null 47033 const lowercaseName = name.toLowerCase() 47034 47035 if (lowercaseName === 'set-cookie') { 47036 this.cookies = [value] 47037 } 47038 47039 // 1. If list contains name, then set the value of 47040 // the first such header to value and remove the 47041 // others. 47042 // 2. Otherwise, append header (name, value) to list. 47043 this[kHeadersMap].set(lowercaseName, { name, value }) 47044 } 47045 47046 // https://fetch.spec.whatwg.org/#concept-header-list-delete 47047 delete (name) { 47048 this[kHeadersSortedMap] = null 47049 47050 name = name.toLowerCase() 47051 47052 if (name === 'set-cookie') { 47053 this.cookies = null 47054 } 47055 47056 this[kHeadersMap].delete(name) 47057 } 47058 47059 // https://fetch.spec.whatwg.org/#concept-header-list-get 47060 get (name) { 47061 const value = this[kHeadersMap].get(name.toLowerCase()) 47062 47063 // 1. If list does not contain name, then return null. 47064 // 2. Return the values of all headers in list whose name 47065 // is a byte-case-insensitive match for name, 47066 // separated from each other by 0x2C 0x20, in order. 47067 return value === undefined ? null : value.value 47068 } 47069 47070 * [Symbol.iterator] () { 47071 // use the lowercased name 47072 for (const [name, { value }] of this[kHeadersMap]) { 47073 yield [name, value] 47074 } 47075 } 47076 47077 get entries () { 47078 const headers = {} 47079 47080 if (this[kHeadersMap].size) { 47081 for (const { name, value } of this[kHeadersMap].values()) { 47082 headers[name] = value 47083 } 47084 } 47085 47086 return headers 47087 } 47088 } 47089 47090 // https://fetch.spec.whatwg.org/#headers-class 47091 class Headers { 47092 constructor (init = undefined) { 47093 if (init === kConstruct) { 47094 return 47095 } 47096 this[kHeadersList] = new HeadersList() 47097 47098 // The new Headers(init) constructor steps are: 47099 47100 // 1. Set this’s guard to "none". 47101 this[kGuard] = 'none' 47102 47103 // 2. If init is given, then fill this with init. 47104 if (init !== undefined) { 47105 init = webidl.converters.HeadersInit(init) 47106 fill(this, init) 47107 } 47108 } 47109 47110 // https://fetch.spec.whatwg.org/#dom-headers-append 47111 append (name, value) { 47112 webidl.brandCheck(this, Headers) 47113 47114 webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) 47115 47116 name = webidl.converters.ByteString(name) 47117 value = webidl.converters.ByteString(value) 47118 47119 return appendHeader(this, name, value) 47120 } 47121 47122 // https://fetch.spec.whatwg.org/#dom-headers-delete 47123 delete (name) { 47124 webidl.brandCheck(this, Headers) 47125 47126 webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) 47127 47128 name = webidl.converters.ByteString(name) 47129 47130 // 1. If name is not a header name, then throw a TypeError. 47131 if (!isValidHeaderName(name)) { 47132 throw webidl.errors.invalidArgument({ 47133 prefix: 'Headers.delete', 47134 value: name, 47135 type: 'header name' 47136 }) 47137 } 47138 47139 // 2. If this’s guard is "immutable", then throw a TypeError. 47140 // 3. Otherwise, if this’s guard is "request" and name is a 47141 // forbidden header name, return. 47142 // 4. Otherwise, if this’s guard is "request-no-cors", name 47143 // is not a no-CORS-safelisted request-header name, and 47144 // name is not a privileged no-CORS request-header name, 47145 // return. 47146 // 5. Otherwise, if this’s guard is "response" and name is 47147 // a forbidden response-header name, return. 47148 // Note: undici does not implement forbidden header names 47149 if (this[kGuard] === 'immutable') { 47150 throw new TypeError('immutable') 47151 } else if (this[kGuard] === 'request-no-cors') { 47152 // TODO 47153 } 47154 47155 // 6. If this’s header list does not contain name, then 47156 // return. 47157 if (!this[kHeadersList].contains(name)) { 47158 return 47159 } 47160 47161 // 7. Delete name from this’s header list. 47162 // 8. If this’s guard is "request-no-cors", then remove 47163 // privileged no-CORS request headers from this. 47164 this[kHeadersList].delete(name) 47165 } 47166 47167 // https://fetch.spec.whatwg.org/#dom-headers-get 47168 get (name) { 47169 webidl.brandCheck(this, Headers) 47170 47171 webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) 47172 47173 name = webidl.converters.ByteString(name) 47174 47175 // 1. If name is not a header name, then throw a TypeError. 47176 if (!isValidHeaderName(name)) { 47177 throw webidl.errors.invalidArgument({ 47178 prefix: 'Headers.get', 47179 value: name, 47180 type: 'header name' 47181 }) 47182 } 47183 47184 // 2. Return the result of getting name from this’s header 47185 // list. 47186 return this[kHeadersList].get(name) 47187 } 47188 47189 // https://fetch.spec.whatwg.org/#dom-headers-has 47190 has (name) { 47191 webidl.brandCheck(this, Headers) 47192 47193 webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) 47194 47195 name = webidl.converters.ByteString(name) 47196 47197 // 1. If name is not a header name, then throw a TypeError. 47198 if (!isValidHeaderName(name)) { 47199 throw webidl.errors.invalidArgument({ 47200 prefix: 'Headers.has', 47201 value: name, 47202 type: 'header name' 47203 }) 47204 } 47205 47206 // 2. Return true if this’s header list contains name; 47207 // otherwise false. 47208 return this[kHeadersList].contains(name) 47209 } 47210 47211 // https://fetch.spec.whatwg.org/#dom-headers-set 47212 set (name, value) { 47213 webidl.brandCheck(this, Headers) 47214 47215 webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) 47216 47217 name = webidl.converters.ByteString(name) 47218 value = webidl.converters.ByteString(value) 47219 47220 // 1. Normalize value. 47221 value = headerValueNormalize(value) 47222 47223 // 2. If name is not a header name or value is not a 47224 // header value, then throw a TypeError. 47225 if (!isValidHeaderName(name)) { 47226 throw webidl.errors.invalidArgument({ 47227 prefix: 'Headers.set', 47228 value: name, 47229 type: 'header name' 47230 }) 47231 } else if (!isValidHeaderValue(value)) { 47232 throw webidl.errors.invalidArgument({ 47233 prefix: 'Headers.set', 47234 value, 47235 type: 'header value' 47236 }) 47237 } 47238 47239 // 3. If this’s guard is "immutable", then throw a TypeError. 47240 // 4. Otherwise, if this’s guard is "request" and name is a 47241 // forbidden header name, return. 47242 // 5. Otherwise, if this’s guard is "request-no-cors" and 47243 // name/value is not a no-CORS-safelisted request-header, 47244 // return. 47245 // 6. Otherwise, if this’s guard is "response" and name is a 47246 // forbidden response-header name, return. 47247 // Note: undici does not implement forbidden header names 47248 if (this[kGuard] === 'immutable') { 47249 throw new TypeError('immutable') 47250 } else if (this[kGuard] === 'request-no-cors') { 47251 // TODO 47252 } 47253 47254 // 7. Set (name, value) in this’s header list. 47255 // 8. If this’s guard is "request-no-cors", then remove 47256 // privileged no-CORS request headers from this 47257 this[kHeadersList].set(name, value) 47258 } 47259 47260 // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie 47261 getSetCookie () { 47262 webidl.brandCheck(this, Headers) 47263 47264 // 1. If this’s header list does not contain `Set-Cookie`, then return « ». 47265 // 2. Return the values of all headers in this’s header list whose name is 47266 // a byte-case-insensitive match for `Set-Cookie`, in order. 47267 47268 const list = this[kHeadersList].cookies 47269 47270 if (list) { 47271 return [...list] 47272 } 47273 47274 return [] 47275 } 47276 47277 // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine 47278 get [kHeadersSortedMap] () { 47279 if (this[kHeadersList][kHeadersSortedMap]) { 47280 return this[kHeadersList][kHeadersSortedMap] 47281 } 47282 47283 // 1. Let headers be an empty list of headers with the key being the name 47284 // and value the value. 47285 const headers = [] 47286 47287 // 2. Let names be the result of convert header names to a sorted-lowercase 47288 // set with all the names of the headers in list. 47289 const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) 47290 const cookies = this[kHeadersList].cookies 47291 47292 // 3. For each name of names: 47293 for (let i = 0; i < names.length; ++i) { 47294 const [name, value] = names[i] 47295 // 1. If name is `set-cookie`, then: 47296 if (name === 'set-cookie') { 47297 // 1. Let values be a list of all values of headers in list whose name 47298 // is a byte-case-insensitive match for name, in order. 47299 47300 // 2. For each value of values: 47301 // 1. Append (name, value) to headers. 47302 for (let j = 0; j < cookies.length; ++j) { 47303 headers.push([name, cookies[j]]) 47304 } 47305 } else { 47306 // 2. Otherwise: 47307 47308 // 1. Let value be the result of getting name from list. 47309 47310 // 2. Assert: value is non-null. 47311 assert(value !== null) 47312 47313 // 3. Append (name, value) to headers. 47314 headers.push([name, value]) 47315 } 47316 } 47317 47318 this[kHeadersList][kHeadersSortedMap] = headers 47319 47320 // 4. Return headers. 47321 return headers 47322 } 47323 47324 keys () { 47325 webidl.brandCheck(this, Headers) 47326 47327 if (this[kGuard] === 'immutable') { 47328 const value = this[kHeadersSortedMap] 47329 return makeIterator(() => value, 'Headers', 47330 'key') 47331 } 47332 47333 return makeIterator( 47334 () => [...this[kHeadersSortedMap].values()], 47335 'Headers', 47336 'key' 47337 ) 47338 } 47339 47340 values () { 47341 webidl.brandCheck(this, Headers) 47342 47343 if (this[kGuard] === 'immutable') { 47344 const value = this[kHeadersSortedMap] 47345 return makeIterator(() => value, 'Headers', 47346 'value') 47347 } 47348 47349 return makeIterator( 47350 () => [...this[kHeadersSortedMap].values()], 47351 'Headers', 47352 'value' 47353 ) 47354 } 47355 47356 entries () { 47357 webidl.brandCheck(this, Headers) 47358 47359 if (this[kGuard] === 'immutable') { 47360 const value = this[kHeadersSortedMap] 47361 return makeIterator(() => value, 'Headers', 47362 'key+value') 47363 } 47364 47365 return makeIterator( 47366 () => [...this[kHeadersSortedMap].values()], 47367 'Headers', 47368 'key+value' 47369 ) 47370 } 47371 47372 /** 47373 * @param {(value: string, key: string, self: Headers) => void} callbackFn 47374 * @param {unknown} thisArg 47375 */ 47376 forEach (callbackFn, thisArg = globalThis) { 47377 webidl.brandCheck(this, Headers) 47378 47379 webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) 47380 47381 if (typeof callbackFn !== 'function') { 47382 throw new TypeError( 47383 "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." 47384 ) 47385 } 47386 47387 for (const [key, value] of this) { 47388 callbackFn.apply(thisArg, [value, key, this]) 47389 } 47390 } 47391 47392 [Symbol.for('nodejs.util.inspect.custom')] () { 47393 webidl.brandCheck(this, Headers) 47394 47395 return this[kHeadersList] 47396 } 47397 } 47398 47399 Headers.prototype[Symbol.iterator] = Headers.prototype.entries 47400 47401 Object.defineProperties(Headers.prototype, { 47402 append: kEnumerableProperty, 47403 delete: kEnumerableProperty, 47404 get: kEnumerableProperty, 47405 has: kEnumerableProperty, 47406 set: kEnumerableProperty, 47407 getSetCookie: kEnumerableProperty, 47408 keys: kEnumerableProperty, 47409 values: kEnumerableProperty, 47410 entries: kEnumerableProperty, 47411 forEach: kEnumerableProperty, 47412 [Symbol.iterator]: { enumerable: false }, 47413 [Symbol.toStringTag]: { 47414 value: 'Headers', 47415 configurable: true 47416 } 47417 }) 47418 47419 webidl.converters.HeadersInit = function (V) { 47420 if (webidl.util.Type(V) === 'Object') { 47421 if (V[Symbol.iterator]) { 47422 return webidl.converters['sequence<sequence<ByteString>>'](V) 47423 } 47424 47425 return webidl.converters['record<ByteString, ByteString>'](V) 47426 } 47427 47428 throw webidl.errors.conversionFailed({ 47429 prefix: 'Headers constructor', 47430 argument: 'Argument 1', 47431 types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>'] 47432 }) 47433 } 47434 47435 module.exports = { 47436 fill, 47437 Headers, 47438 HeadersList 47439 } 47440 47441 47442 /***/ }), 47443 47444 /***/ 4881: 47445 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 47446 47447 "use strict"; 47448 // https://github.com/Ethan-Arrowood/undici-fetch 47449 47450 47451 47452 const { 47453 Response, 47454 makeNetworkError, 47455 makeAppropriateNetworkError, 47456 filterResponse, 47457 makeResponse 47458 } = __nccwpck_require__(7823) 47459 const { Headers } = __nccwpck_require__(554) 47460 const { Request, makeRequest } = __nccwpck_require__(8359) 47461 const zlib = __nccwpck_require__(9796) 47462 const { 47463 bytesMatch, 47464 makePolicyContainer, 47465 clonePolicyContainer, 47466 requestBadPort, 47467 TAOCheck, 47468 appendRequestOriginHeader, 47469 responseLocationURL, 47470 requestCurrentURL, 47471 setRequestReferrerPolicyOnRedirect, 47472 tryUpgradeRequestToAPotentiallyTrustworthyURL, 47473 createOpaqueTimingInfo, 47474 appendFetchMetadata, 47475 corsCheck, 47476 crossOriginResourcePolicyCheck, 47477 determineRequestsReferrer, 47478 coarsenedSharedCurrentTime, 47479 createDeferredPromise, 47480 isBlobLike, 47481 sameOrigin, 47482 isCancelled, 47483 isAborted, 47484 isErrorLike, 47485 fullyReadBody, 47486 readableStreamClose, 47487 isomorphicEncode, 47488 urlIsLocal, 47489 urlIsHttpHttpsScheme, 47490 urlHasHttpsScheme 47491 } = __nccwpck_require__(2538) 47492 const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) 47493 const assert = __nccwpck_require__(9491) 47494 const { safelyExtractBody } = __nccwpck_require__(1472) 47495 const { 47496 redirectStatusSet, 47497 nullBodyStatus, 47498 safeMethodsSet, 47499 requestBodyHeader, 47500 subresourceSet, 47501 DOMException 47502 } = __nccwpck_require__(1037) 47503 const { kHeadersList } = __nccwpck_require__(2785) 47504 const EE = __nccwpck_require__(2361) 47505 const { Readable, pipeline } = __nccwpck_require__(2781) 47506 const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3983) 47507 const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) 47508 const { TransformStream } = __nccwpck_require__(5356) 47509 const { getGlobalDispatcher } = __nccwpck_require__(1892) 47510 const { webidl } = __nccwpck_require__(1744) 47511 const { STATUS_CODES } = __nccwpck_require__(3685) 47512 const GET_OR_HEAD = ['GET', 'HEAD'] 47513 47514 /** @type {import('buffer').resolveObjectURL} */ 47515 let resolveObjectURL 47516 let ReadableStream = globalThis.ReadableStream 47517 47518 class Fetch extends EE { 47519 constructor (dispatcher) { 47520 super() 47521 47522 this.dispatcher = dispatcher 47523 this.connection = null 47524 this.dump = false 47525 this.state = 'ongoing' 47526 // 2 terminated listeners get added per request, 47527 // but only 1 gets removed. If there are 20 redirects, 47528 // 21 listeners will be added. 47529 // See https://github.com/nodejs/undici/issues/1711 47530 // TODO (fix): Find and fix root cause for leaked listener. 47531 this.setMaxListeners(21) 47532 } 47533 47534 terminate (reason) { 47535 if (this.state !== 'ongoing') { 47536 return 47537 } 47538 47539 this.state = 'terminated' 47540 this.connection?.destroy(reason) 47541 this.emit('terminated', reason) 47542 } 47543 47544 // https://fetch.spec.whatwg.org/#fetch-controller-abort 47545 abort (error) { 47546 if (this.state !== 'ongoing') { 47547 return 47548 } 47549 47550 // 1. Set controller’s state to "aborted". 47551 this.state = 'aborted' 47552 47553 // 2. Let fallbackError be an "AbortError" DOMException. 47554 // 3. Set error to fallbackError if it is not given. 47555 if (!error) { 47556 error = new DOMException('The operation was aborted.', 'AbortError') 47557 } 47558 47559 // 4. Let serializedError be StructuredSerialize(error). 47560 // If that threw an exception, catch it, and let 47561 // serializedError be StructuredSerialize(fallbackError). 47562 47563 // 5. Set controller’s serialized abort reason to serializedError. 47564 this.serializedAbortReason = error 47565 47566 this.connection?.destroy(error) 47567 this.emit('terminated', error) 47568 } 47569 } 47570 47571 // https://fetch.spec.whatwg.org/#fetch-method 47572 function fetch (input, init = {}) { 47573 webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) 47574 47575 // 1. Let p be a new promise. 47576 const p = createDeferredPromise() 47577 47578 // 2. Let requestObject be the result of invoking the initial value of 47579 // Request as constructor with input and init as arguments. If this throws 47580 // an exception, reject p with it and return p. 47581 let requestObject 47582 47583 try { 47584 requestObject = new Request(input, init) 47585 } catch (e) { 47586 p.reject(e) 47587 return p.promise 47588 } 47589 47590 // 3. Let request be requestObject’s request. 47591 const request = requestObject[kState] 47592 47593 // 4. If requestObject’s signal’s aborted flag is set, then: 47594 if (requestObject.signal.aborted) { 47595 // 1. Abort the fetch() call with p, request, null, and 47596 // requestObject’s signal’s abort reason. 47597 abortFetch(p, request, null, requestObject.signal.reason) 47598 47599 // 2. Return p. 47600 return p.promise 47601 } 47602 47603 // 5. Let globalObject be request’s client’s global object. 47604 const globalObject = request.client.globalObject 47605 47606 // 6. If globalObject is a ServiceWorkerGlobalScope object, then set 47607 // request’s service-workers mode to "none". 47608 if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { 47609 request.serviceWorkers = 'none' 47610 } 47611 47612 // 7. Let responseObject be null. 47613 let responseObject = null 47614 47615 // 8. Let relevantRealm be this’s relevant Realm. 47616 const relevantRealm = null 47617 47618 // 9. Let locallyAborted be false. 47619 let locallyAborted = false 47620 47621 // 10. Let controller be null. 47622 let controller = null 47623 47624 // 11. Add the following abort steps to requestObject’s signal: 47625 addAbortListener( 47626 requestObject.signal, 47627 () => { 47628 // 1. Set locallyAborted to true. 47629 locallyAborted = true 47630 47631 // 2. Assert: controller is non-null. 47632 assert(controller != null) 47633 47634 // 3. Abort controller with requestObject’s signal’s abort reason. 47635 controller.abort(requestObject.signal.reason) 47636 47637 // 4. Abort the fetch() call with p, request, responseObject, 47638 // and requestObject’s signal’s abort reason. 47639 abortFetch(p, request, responseObject, requestObject.signal.reason) 47640 } 47641 ) 47642 47643 // 12. Let handleFetchDone given response response be to finalize and 47644 // report timing with response, globalObject, and "fetch". 47645 const handleFetchDone = (response) => 47646 finalizeAndReportTiming(response, 'fetch') 47647 47648 // 13. Set controller to the result of calling fetch given request, 47649 // with processResponseEndOfBody set to handleFetchDone, and processResponse 47650 // given response being these substeps: 47651 47652 const processResponse = (response) => { 47653 // 1. If locallyAborted is true, terminate these substeps. 47654 if (locallyAborted) { 47655 return Promise.resolve() 47656 } 47657 47658 // 2. If response’s aborted flag is set, then: 47659 if (response.aborted) { 47660 // 1. Let deserializedError be the result of deserialize a serialized 47661 // abort reason given controller’s serialized abort reason and 47662 // relevantRealm. 47663 47664 // 2. Abort the fetch() call with p, request, responseObject, and 47665 // deserializedError. 47666 47667 abortFetch(p, request, responseObject, controller.serializedAbortReason) 47668 return Promise.resolve() 47669 } 47670 47671 // 3. If response is a network error, then reject p with a TypeError 47672 // and terminate these substeps. 47673 if (response.type === 'error') { 47674 p.reject( 47675 Object.assign(new TypeError('fetch failed'), { cause: response.error }) 47676 ) 47677 return Promise.resolve() 47678 } 47679 47680 // 4. Set responseObject to the result of creating a Response object, 47681 // given response, "immutable", and relevantRealm. 47682 responseObject = new Response() 47683 responseObject[kState] = response 47684 responseObject[kRealm] = relevantRealm 47685 responseObject[kHeaders][kHeadersList] = response.headersList 47686 responseObject[kHeaders][kGuard] = 'immutable' 47687 responseObject[kHeaders][kRealm] = relevantRealm 47688 47689 // 5. Resolve p with responseObject. 47690 p.resolve(responseObject) 47691 } 47692 47693 controller = fetching({ 47694 request, 47695 processResponseEndOfBody: handleFetchDone, 47696 processResponse, 47697 dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici 47698 }) 47699 47700 // 14. Return p. 47701 return p.promise 47702 } 47703 47704 // https://fetch.spec.whatwg.org/#finalize-and-report-timing 47705 function finalizeAndReportTiming (response, initiatorType = 'other') { 47706 // 1. If response is an aborted network error, then return. 47707 if (response.type === 'error' && response.aborted) { 47708 return 47709 } 47710 47711 // 2. If response’s URL list is null or empty, then return. 47712 if (!response.urlList?.length) { 47713 return 47714 } 47715 47716 // 3. Let originalURL be response’s URL list[0]. 47717 const originalURL = response.urlList[0] 47718 47719 // 4. Let timingInfo be response’s timing info. 47720 let timingInfo = response.timingInfo 47721 47722 // 5. Let cacheState be response’s cache state. 47723 let cacheState = response.cacheState 47724 47725 // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. 47726 if (!urlIsHttpHttpsScheme(originalURL)) { 47727 return 47728 } 47729 47730 // 7. If timingInfo is null, then return. 47731 if (timingInfo === null) { 47732 return 47733 } 47734 47735 // 8. If response’s timing allow passed flag is not set, then: 47736 if (!response.timingAllowPassed) { 47737 // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. 47738 timingInfo = createOpaqueTimingInfo({ 47739 startTime: timingInfo.startTime 47740 }) 47741 47742 // 2. Set cacheState to the empty string. 47743 cacheState = '' 47744 } 47745 47746 // 9. Set timingInfo’s end time to the coarsened shared current time 47747 // given global’s relevant settings object’s cross-origin isolated 47748 // capability. 47749 // TODO: given global’s relevant settings object’s cross-origin isolated 47750 // capability? 47751 timingInfo.endTime = coarsenedSharedCurrentTime() 47752 47753 // 10. Set response’s timing info to timingInfo. 47754 response.timingInfo = timingInfo 47755 47756 // 11. Mark resource timing for timingInfo, originalURL, initiatorType, 47757 // global, and cacheState. 47758 markResourceTiming( 47759 timingInfo, 47760 originalURL, 47761 initiatorType, 47762 globalThis, 47763 cacheState 47764 ) 47765 } 47766 47767 // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing 47768 function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { 47769 if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { 47770 performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) 47771 } 47772 } 47773 47774 // https://fetch.spec.whatwg.org/#abort-fetch 47775 function abortFetch (p, request, responseObject, error) { 47776 // Note: AbortSignal.reason was added in node v17.2.0 47777 // which would give us an undefined error to reject with. 47778 // Remove this once node v16 is no longer supported. 47779 if (!error) { 47780 error = new DOMException('The operation was aborted.', 'AbortError') 47781 } 47782 47783 // 1. Reject promise with error. 47784 p.reject(error) 47785 47786 // 2. If request’s body is not null and is readable, then cancel request’s 47787 // body with error. 47788 if (request.body != null && isReadable(request.body?.stream)) { 47789 request.body.stream.cancel(error).catch((err) => { 47790 if (err.code === 'ERR_INVALID_STATE') { 47791 // Node bug? 47792 return 47793 } 47794 throw err 47795 }) 47796 } 47797 47798 // 3. If responseObject is null, then return. 47799 if (responseObject == null) { 47800 return 47801 } 47802 47803 // 4. Let response be responseObject’s response. 47804 const response = responseObject[kState] 47805 47806 // 5. If response’s body is not null and is readable, then error response’s 47807 // body with error. 47808 if (response.body != null && isReadable(response.body?.stream)) { 47809 response.body.stream.cancel(error).catch((err) => { 47810 if (err.code === 'ERR_INVALID_STATE') { 47811 // Node bug? 47812 return 47813 } 47814 throw err 47815 }) 47816 } 47817 } 47818 47819 // https://fetch.spec.whatwg.org/#fetching 47820 function fetching ({ 47821 request, 47822 processRequestBodyChunkLength, 47823 processRequestEndOfBody, 47824 processResponse, 47825 processResponseEndOfBody, 47826 processResponseConsumeBody, 47827 useParallelQueue = false, 47828 dispatcher // undici 47829 }) { 47830 // 1. Let taskDestination be null. 47831 let taskDestination = null 47832 47833 // 2. Let crossOriginIsolatedCapability be false. 47834 let crossOriginIsolatedCapability = false 47835 47836 // 3. If request’s client is non-null, then: 47837 if (request.client != null) { 47838 // 1. Set taskDestination to request’s client’s global object. 47839 taskDestination = request.client.globalObject 47840 47841 // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin 47842 // isolated capability. 47843 crossOriginIsolatedCapability = 47844 request.client.crossOriginIsolatedCapability 47845 } 47846 47847 // 4. If useParallelQueue is true, then set taskDestination to the result of 47848 // starting a new parallel queue. 47849 // TODO 47850 47851 // 5. Let timingInfo be a new fetch timing info whose start time and 47852 // post-redirect start time are the coarsened shared current time given 47853 // crossOriginIsolatedCapability. 47854 const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) 47855 const timingInfo = createOpaqueTimingInfo({ 47856 startTime: currenTime 47857 }) 47858 47859 // 6. Let fetchParams be a new fetch params whose 47860 // request is request, 47861 // timing info is timingInfo, 47862 // process request body chunk length is processRequestBodyChunkLength, 47863 // process request end-of-body is processRequestEndOfBody, 47864 // process response is processResponse, 47865 // process response consume body is processResponseConsumeBody, 47866 // process response end-of-body is processResponseEndOfBody, 47867 // task destination is taskDestination, 47868 // and cross-origin isolated capability is crossOriginIsolatedCapability. 47869 const fetchParams = { 47870 controller: new Fetch(dispatcher), 47871 request, 47872 timingInfo, 47873 processRequestBodyChunkLength, 47874 processRequestEndOfBody, 47875 processResponse, 47876 processResponseConsumeBody, 47877 processResponseEndOfBody, 47878 taskDestination, 47879 crossOriginIsolatedCapability 47880 } 47881 47882 // 7. If request’s body is a byte sequence, then set request’s body to 47883 // request’s body as a body. 47884 // NOTE: Since fetching is only called from fetch, body should already be 47885 // extracted. 47886 assert(!request.body || request.body.stream) 47887 47888 // 8. If request’s window is "client", then set request’s window to request’s 47889 // client, if request’s client’s global object is a Window object; otherwise 47890 // "no-window". 47891 if (request.window === 'client') { 47892 // TODO: What if request.client is null? 47893 request.window = 47894 request.client?.globalObject?.constructor?.name === 'Window' 47895 ? request.client 47896 : 'no-window' 47897 } 47898 47899 // 9. If request’s origin is "client", then set request’s origin to request’s 47900 // client’s origin. 47901 if (request.origin === 'client') { 47902 // TODO: What if request.client is null? 47903 request.origin = request.client?.origin 47904 } 47905 47906 // 10. If all of the following conditions are true: 47907 // TODO 47908 47909 // 11. If request’s policy container is "client", then: 47910 if (request.policyContainer === 'client') { 47911 // 1. If request’s client is non-null, then set request’s policy 47912 // container to a clone of request’s client’s policy container. [HTML] 47913 if (request.client != null) { 47914 request.policyContainer = clonePolicyContainer( 47915 request.client.policyContainer 47916 ) 47917 } else { 47918 // 2. Otherwise, set request’s policy container to a new policy 47919 // container. 47920 request.policyContainer = makePolicyContainer() 47921 } 47922 } 47923 47924 // 12. If request’s header list does not contain `Accept`, then: 47925 if (!request.headersList.contains('accept')) { 47926 // 1. Let value be `*/*`. 47927 const value = '*/*' 47928 47929 // 2. A user agent should set value to the first matching statement, if 47930 // any, switching on request’s destination: 47931 // "document" 47932 // "frame" 47933 // "iframe" 47934 // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` 47935 // "image" 47936 // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` 47937 // "style" 47938 // `text/css,*/*;q=0.1` 47939 // TODO 47940 47941 // 3. Append `Accept`/value to request’s header list. 47942 request.headersList.append('accept', value) 47943 } 47944 47945 // 13. If request’s header list does not contain `Accept-Language`, then 47946 // user agents should append `Accept-Language`/an appropriate value to 47947 // request’s header list. 47948 if (!request.headersList.contains('accept-language')) { 47949 request.headersList.append('accept-language', '*') 47950 } 47951 47952 // 14. If request’s priority is null, then use request’s initiator and 47953 // destination appropriately in setting request’s priority to a 47954 // user-agent-defined object. 47955 if (request.priority === null) { 47956 // TODO 47957 } 47958 47959 // 15. If request is a subresource request, then: 47960 if (subresourceSet.has(request.destination)) { 47961 // TODO 47962 } 47963 47964 // 16. Run main fetch given fetchParams. 47965 mainFetch(fetchParams) 47966 .catch(err => { 47967 fetchParams.controller.terminate(err) 47968 }) 47969 47970 // 17. Return fetchParam's controller 47971 return fetchParams.controller 47972 } 47973 47974 // https://fetch.spec.whatwg.org/#concept-main-fetch 47975 async function mainFetch (fetchParams, recursive = false) { 47976 // 1. Let request be fetchParams’s request. 47977 const request = fetchParams.request 47978 47979 // 2. Let response be null. 47980 let response = null 47981 47982 // 3. If request’s local-URLs-only flag is set and request’s current URL is 47983 // not local, then set response to a network error. 47984 if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { 47985 response = makeNetworkError('local URLs only') 47986 } 47987 47988 // 4. Run report Content Security Policy violations for request. 47989 // TODO 47990 47991 // 5. Upgrade request to a potentially trustworthy URL, if appropriate. 47992 tryUpgradeRequestToAPotentiallyTrustworthyURL(request) 47993 47994 // 6. If should request be blocked due to a bad port, should fetching request 47995 // be blocked as mixed content, or should request be blocked by Content 47996 // Security Policy returns blocked, then set response to a network error. 47997 if (requestBadPort(request) === 'blocked') { 47998 response = makeNetworkError('bad port') 47999 } 48000 // TODO: should fetching request be blocked as mixed content? 48001 // TODO: should request be blocked by Content Security Policy? 48002 48003 // 7. If request’s referrer policy is the empty string, then set request’s 48004 // referrer policy to request’s policy container’s referrer policy. 48005 if (request.referrerPolicy === '') { 48006 request.referrerPolicy = request.policyContainer.referrerPolicy 48007 } 48008 48009 // 8. If request’s referrer is not "no-referrer", then set request’s 48010 // referrer to the result of invoking determine request’s referrer. 48011 if (request.referrer !== 'no-referrer') { 48012 request.referrer = determineRequestsReferrer(request) 48013 } 48014 48015 // 9. Set request’s current URL’s scheme to "https" if all of the following 48016 // conditions are true: 48017 // - request’s current URL’s scheme is "http" 48018 // - request’s current URL’s host is a domain 48019 // - Matching request’s current URL’s host per Known HSTS Host Domain Name 48020 // Matching results in either a superdomain match with an asserted 48021 // includeSubDomains directive or a congruent match (with or without an 48022 // asserted includeSubDomains directive). [HSTS] 48023 // TODO 48024 48025 // 10. If recursive is false, then run the remaining steps in parallel. 48026 // TODO 48027 48028 // 11. If response is null, then set response to the result of running 48029 // the steps corresponding to the first matching statement: 48030 if (response === null) { 48031 response = await (async () => { 48032 const currentURL = requestCurrentURL(request) 48033 48034 if ( 48035 // - request’s current URL’s origin is same origin with request’s origin, 48036 // and request’s response tainting is "basic" 48037 (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || 48038 // request’s current URL’s scheme is "data" 48039 (currentURL.protocol === 'data:') || 48040 // - request’s mode is "navigate" or "websocket" 48041 (request.mode === 'navigate' || request.mode === 'websocket') 48042 ) { 48043 // 1. Set request’s response tainting to "basic". 48044 request.responseTainting = 'basic' 48045 48046 // 2. Return the result of running scheme fetch given fetchParams. 48047 return await schemeFetch(fetchParams) 48048 } 48049 48050 // request’s mode is "same-origin" 48051 if (request.mode === 'same-origin') { 48052 // 1. Return a network error. 48053 return makeNetworkError('request mode cannot be "same-origin"') 48054 } 48055 48056 // request’s mode is "no-cors" 48057 if (request.mode === 'no-cors') { 48058 // 1. If request’s redirect mode is not "follow", then return a network 48059 // error. 48060 if (request.redirect !== 'follow') { 48061 return makeNetworkError( 48062 'redirect mode cannot be "follow" for "no-cors" request' 48063 ) 48064 } 48065 48066 // 2. Set request’s response tainting to "opaque". 48067 request.responseTainting = 'opaque' 48068 48069 // 3. Return the result of running scheme fetch given fetchParams. 48070 return await schemeFetch(fetchParams) 48071 } 48072 48073 // request’s current URL’s scheme is not an HTTP(S) scheme 48074 if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { 48075 // Return a network error. 48076 return makeNetworkError('URL scheme must be a HTTP(S) scheme') 48077 } 48078 48079 // - request’s use-CORS-preflight flag is set 48080 // - request’s unsafe-request flag is set and either request’s method is 48081 // not a CORS-safelisted method or CORS-unsafe request-header names with 48082 // request’s header list is not empty 48083 // 1. Set request’s response tainting to "cors". 48084 // 2. Let corsWithPreflightResponse be the result of running HTTP fetch 48085 // given fetchParams and true. 48086 // 3. If corsWithPreflightResponse is a network error, then clear cache 48087 // entries using request. 48088 // 4. Return corsWithPreflightResponse. 48089 // TODO 48090 48091 // Otherwise 48092 // 1. Set request’s response tainting to "cors". 48093 request.responseTainting = 'cors' 48094 48095 // 2. Return the result of running HTTP fetch given fetchParams. 48096 return await httpFetch(fetchParams) 48097 })() 48098 } 48099 48100 // 12. If recursive is true, then return response. 48101 if (recursive) { 48102 return response 48103 } 48104 48105 // 13. If response is not a network error and response is not a filtered 48106 // response, then: 48107 if (response.status !== 0 && !response.internalResponse) { 48108 // If request’s response tainting is "cors", then: 48109 if (request.responseTainting === 'cors') { 48110 // 1. Let headerNames be the result of extracting header list values 48111 // given `Access-Control-Expose-Headers` and response’s header list. 48112 // TODO 48113 // 2. If request’s credentials mode is not "include" and headerNames 48114 // contains `*`, then set response’s CORS-exposed header-name list to 48115 // all unique header names in response’s header list. 48116 // TODO 48117 // 3. Otherwise, if headerNames is not null or failure, then set 48118 // response’s CORS-exposed header-name list to headerNames. 48119 // TODO 48120 } 48121 48122 // Set response to the following filtered response with response as its 48123 // internal response, depending on request’s response tainting: 48124 if (request.responseTainting === 'basic') { 48125 response = filterResponse(response, 'basic') 48126 } else if (request.responseTainting === 'cors') { 48127 response = filterResponse(response, 'cors') 48128 } else if (request.responseTainting === 'opaque') { 48129 response = filterResponse(response, 'opaque') 48130 } else { 48131 assert(false) 48132 } 48133 } 48134 48135 // 14. Let internalResponse be response, if response is a network error, 48136 // and response’s internal response otherwise. 48137 let internalResponse = 48138 response.status === 0 ? response : response.internalResponse 48139 48140 // 15. If internalResponse’s URL list is empty, then set it to a clone of 48141 // request’s URL list. 48142 if (internalResponse.urlList.length === 0) { 48143 internalResponse.urlList.push(...request.urlList) 48144 } 48145 48146 // 16. If request’s timing allow failed flag is unset, then set 48147 // internalResponse’s timing allow passed flag. 48148 if (!request.timingAllowFailed) { 48149 response.timingAllowPassed = true 48150 } 48151 48152 // 17. If response is not a network error and any of the following returns 48153 // blocked 48154 // - should internalResponse to request be blocked as mixed content 48155 // - should internalResponse to request be blocked by Content Security Policy 48156 // - should internalResponse to request be blocked due to its MIME type 48157 // - should internalResponse to request be blocked due to nosniff 48158 // TODO 48159 48160 // 18. If response’s type is "opaque", internalResponse’s status is 206, 48161 // internalResponse’s range-requested flag is set, and request’s header 48162 // list does not contain `Range`, then set response and internalResponse 48163 // to a network error. 48164 if ( 48165 response.type === 'opaque' && 48166 internalResponse.status === 206 && 48167 internalResponse.rangeRequested && 48168 !request.headers.contains('range') 48169 ) { 48170 response = internalResponse = makeNetworkError() 48171 } 48172 48173 // 19. If response is not a network error and either request’s method is 48174 // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, 48175 // set internalResponse’s body to null and disregard any enqueuing toward 48176 // it (if any). 48177 if ( 48178 response.status !== 0 && 48179 (request.method === 'HEAD' || 48180 request.method === 'CONNECT' || 48181 nullBodyStatus.includes(internalResponse.status)) 48182 ) { 48183 internalResponse.body = null 48184 fetchParams.controller.dump = true 48185 } 48186 48187 // 20. If request’s integrity metadata is not the empty string, then: 48188 if (request.integrity) { 48189 // 1. Let processBodyError be this step: run fetch finale given fetchParams 48190 // and a network error. 48191 const processBodyError = (reason) => 48192 fetchFinale(fetchParams, makeNetworkError(reason)) 48193 48194 // 2. If request’s response tainting is "opaque", or response’s body is null, 48195 // then run processBodyError and abort these steps. 48196 if (request.responseTainting === 'opaque' || response.body == null) { 48197 processBodyError(response.error) 48198 return 48199 } 48200 48201 // 3. Let processBody given bytes be these steps: 48202 const processBody = (bytes) => { 48203 // 1. If bytes do not match request’s integrity metadata, 48204 // then run processBodyError and abort these steps. [SRI] 48205 if (!bytesMatch(bytes, request.integrity)) { 48206 processBodyError('integrity mismatch') 48207 return 48208 } 48209 48210 // 2. Set response’s body to bytes as a body. 48211 response.body = safelyExtractBody(bytes)[0] 48212 48213 // 3. Run fetch finale given fetchParams and response. 48214 fetchFinale(fetchParams, response) 48215 } 48216 48217 // 4. Fully read response’s body given processBody and processBodyError. 48218 await fullyReadBody(response.body, processBody, processBodyError) 48219 } else { 48220 // 21. Otherwise, run fetch finale given fetchParams and response. 48221 fetchFinale(fetchParams, response) 48222 } 48223 } 48224 48225 // https://fetch.spec.whatwg.org/#concept-scheme-fetch 48226 // given a fetch params fetchParams 48227 function schemeFetch (fetchParams) { 48228 // Note: since the connection is destroyed on redirect, which sets fetchParams to a 48229 // cancelled state, we do not want this condition to trigger *unless* there have been 48230 // no redirects. See https://github.com/nodejs/undici/issues/1776 48231 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. 48232 if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { 48233 return Promise.resolve(makeAppropriateNetworkError(fetchParams)) 48234 } 48235 48236 // 2. Let request be fetchParams’s request. 48237 const { request } = fetchParams 48238 48239 const { protocol: scheme } = requestCurrentURL(request) 48240 48241 // 3. Switch on request’s current URL’s scheme and run the associated steps: 48242 switch (scheme) { 48243 case 'about:': { 48244 // If request’s current URL’s path is the string "blank", then return a new response 48245 // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », 48246 // and body is the empty byte sequence as a body. 48247 48248 // Otherwise, return a network error. 48249 return Promise.resolve(makeNetworkError('about scheme is not supported')) 48250 } 48251 case 'blob:': { 48252 if (!resolveObjectURL) { 48253 resolveObjectURL = (__nccwpck_require__(4300).resolveObjectURL) 48254 } 48255 48256 // 1. Let blobURLEntry be request’s current URL’s blob URL entry. 48257 const blobURLEntry = requestCurrentURL(request) 48258 48259 // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 48260 // Buffer.resolveObjectURL does not ignore URL queries. 48261 if (blobURLEntry.search.length !== 0) { 48262 return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) 48263 } 48264 48265 const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) 48266 48267 // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s 48268 // object is not a Blob object, then return a network error. 48269 if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { 48270 return Promise.resolve(makeNetworkError('invalid method')) 48271 } 48272 48273 // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. 48274 const bodyWithType = safelyExtractBody(blobURLEntryObject) 48275 48276 // 4. Let body be bodyWithType’s body. 48277 const body = bodyWithType[0] 48278 48279 // 5. Let length be body’s length, serialized and isomorphic encoded. 48280 const length = isomorphicEncode(`${body.length}`) 48281 48282 // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. 48283 const type = bodyWithType[1] ?? '' 48284 48285 // 7. Return a new response whose status message is `OK`, header list is 48286 // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. 48287 const response = makeResponse({ 48288 statusText: 'OK', 48289 headersList: [ 48290 ['content-length', { name: 'Content-Length', value: length }], 48291 ['content-type', { name: 'Content-Type', value: type }] 48292 ] 48293 }) 48294 48295 response.body = body 48296 48297 return Promise.resolve(response) 48298 } 48299 case 'data:': { 48300 // 1. Let dataURLStruct be the result of running the 48301 // data: URL processor on request’s current URL. 48302 const currentURL = requestCurrentURL(request) 48303 const dataURLStruct = dataURLProcessor(currentURL) 48304 48305 // 2. If dataURLStruct is failure, then return a 48306 // network error. 48307 if (dataURLStruct === 'failure') { 48308 return Promise.resolve(makeNetworkError('failed to fetch the data URL')) 48309 } 48310 48311 // 3. Let mimeType be dataURLStruct’s MIME type, serialized. 48312 const mimeType = serializeAMimeType(dataURLStruct.mimeType) 48313 48314 // 4. Return a response whose status message is `OK`, 48315 // header list is « (`Content-Type`, mimeType) », 48316 // and body is dataURLStruct’s body as a body. 48317 return Promise.resolve(makeResponse({ 48318 statusText: 'OK', 48319 headersList: [ 48320 ['content-type', { name: 'Content-Type', value: mimeType }] 48321 ], 48322 body: safelyExtractBody(dataURLStruct.body)[0] 48323 })) 48324 } 48325 case 'file:': { 48326 // For now, unfortunate as it is, file URLs are left as an exercise for the reader. 48327 // When in doubt, return a network error. 48328 return Promise.resolve(makeNetworkError('not implemented... yet...')) 48329 } 48330 case 'http:': 48331 case 'https:': { 48332 // Return the result of running HTTP fetch given fetchParams. 48333 48334 return httpFetch(fetchParams) 48335 .catch((err) => makeNetworkError(err)) 48336 } 48337 default: { 48338 return Promise.resolve(makeNetworkError('unknown scheme')) 48339 } 48340 } 48341 } 48342 48343 // https://fetch.spec.whatwg.org/#finalize-response 48344 function finalizeResponse (fetchParams, response) { 48345 // 1. Set fetchParams’s request’s done flag. 48346 fetchParams.request.done = true 48347 48348 // 2, If fetchParams’s process response done is not null, then queue a fetch 48349 // task to run fetchParams’s process response done given response, with 48350 // fetchParams’s task destination. 48351 if (fetchParams.processResponseDone != null) { 48352 queueMicrotask(() => fetchParams.processResponseDone(response)) 48353 } 48354 } 48355 48356 // https://fetch.spec.whatwg.org/#fetch-finale 48357 function fetchFinale (fetchParams, response) { 48358 // 1. If response is a network error, then: 48359 if (response.type === 'error') { 48360 // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». 48361 response.urlList = [fetchParams.request.urlList[0]] 48362 48363 // 2. Set response’s timing info to the result of creating an opaque timing 48364 // info for fetchParams’s timing info. 48365 response.timingInfo = createOpaqueTimingInfo({ 48366 startTime: fetchParams.timingInfo.startTime 48367 }) 48368 } 48369 48370 // 2. Let processResponseEndOfBody be the following steps: 48371 const processResponseEndOfBody = () => { 48372 // 1. Set fetchParams’s request’s done flag. 48373 fetchParams.request.done = true 48374 48375 // If fetchParams’s process response end-of-body is not null, 48376 // then queue a fetch task to run fetchParams’s process response 48377 // end-of-body given response with fetchParams’s task destination. 48378 if (fetchParams.processResponseEndOfBody != null) { 48379 queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) 48380 } 48381 } 48382 48383 // 3. If fetchParams’s process response is non-null, then queue a fetch task 48384 // to run fetchParams’s process response given response, with fetchParams’s 48385 // task destination. 48386 if (fetchParams.processResponse != null) { 48387 queueMicrotask(() => fetchParams.processResponse(response)) 48388 } 48389 48390 // 4. If response’s body is null, then run processResponseEndOfBody. 48391 if (response.body == null) { 48392 processResponseEndOfBody() 48393 } else { 48394 // 5. Otherwise: 48395 48396 // 1. Let transformStream be a new a TransformStream. 48397 48398 // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, 48399 // enqueues chunk in transformStream. 48400 const identityTransformAlgorithm = (chunk, controller) => { 48401 controller.enqueue(chunk) 48402 } 48403 48404 // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm 48405 // and flushAlgorithm set to processResponseEndOfBody. 48406 const transformStream = new TransformStream({ 48407 start () {}, 48408 transform: identityTransformAlgorithm, 48409 flush: processResponseEndOfBody 48410 }, { 48411 size () { 48412 return 1 48413 } 48414 }, { 48415 size () { 48416 return 1 48417 } 48418 }) 48419 48420 // 4. Set response’s body to the result of piping response’s body through transformStream. 48421 response.body = { stream: response.body.stream.pipeThrough(transformStream) } 48422 } 48423 48424 // 6. If fetchParams’s process response consume body is non-null, then: 48425 if (fetchParams.processResponseConsumeBody != null) { 48426 // 1. Let processBody given nullOrBytes be this step: run fetchParams’s 48427 // process response consume body given response and nullOrBytes. 48428 const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) 48429 48430 // 2. Let processBodyError be this step: run fetchParams’s process 48431 // response consume body given response and failure. 48432 const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) 48433 48434 // 3. If response’s body is null, then queue a fetch task to run processBody 48435 // given null, with fetchParams’s task destination. 48436 if (response.body == null) { 48437 queueMicrotask(() => processBody(null)) 48438 } else { 48439 // 4. Otherwise, fully read response’s body given processBody, processBodyError, 48440 // and fetchParams’s task destination. 48441 return fullyReadBody(response.body, processBody, processBodyError) 48442 } 48443 return Promise.resolve() 48444 } 48445 } 48446 48447 // https://fetch.spec.whatwg.org/#http-fetch 48448 async function httpFetch (fetchParams) { 48449 // 1. Let request be fetchParams’s request. 48450 const request = fetchParams.request 48451 48452 // 2. Let response be null. 48453 let response = null 48454 48455 // 3. Let actualResponse be null. 48456 let actualResponse = null 48457 48458 // 4. Let timingInfo be fetchParams’s timing info. 48459 const timingInfo = fetchParams.timingInfo 48460 48461 // 5. If request’s service-workers mode is "all", then: 48462 if (request.serviceWorkers === 'all') { 48463 // TODO 48464 } 48465 48466 // 6. If response is null, then: 48467 if (response === null) { 48468 // 1. If makeCORSPreflight is true and one of these conditions is true: 48469 // TODO 48470 48471 // 2. If request’s redirect mode is "follow", then set request’s 48472 // service-workers mode to "none". 48473 if (request.redirect === 'follow') { 48474 request.serviceWorkers = 'none' 48475 } 48476 48477 // 3. Set response and actualResponse to the result of running 48478 // HTTP-network-or-cache fetch given fetchParams. 48479 actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) 48480 48481 // 4. If request’s response tainting is "cors" and a CORS check 48482 // for request and response returns failure, then return a network error. 48483 if ( 48484 request.responseTainting === 'cors' && 48485 corsCheck(request, response) === 'failure' 48486 ) { 48487 return makeNetworkError('cors failure') 48488 } 48489 48490 // 5. If the TAO check for request and response returns failure, then set 48491 // request’s timing allow failed flag. 48492 if (TAOCheck(request, response) === 'failure') { 48493 request.timingAllowFailed = true 48494 } 48495 } 48496 48497 // 7. If either request’s response tainting or response’s type 48498 // is "opaque", and the cross-origin resource policy check with 48499 // request’s origin, request’s client, request’s destination, 48500 // and actualResponse returns blocked, then return a network error. 48501 if ( 48502 (request.responseTainting === 'opaque' || response.type === 'opaque') && 48503 crossOriginResourcePolicyCheck( 48504 request.origin, 48505 request.client, 48506 request.destination, 48507 actualResponse 48508 ) === 'blocked' 48509 ) { 48510 return makeNetworkError('blocked') 48511 } 48512 48513 // 8. If actualResponse’s status is a redirect status, then: 48514 if (redirectStatusSet.has(actualResponse.status)) { 48515 // 1. If actualResponse’s status is not 303, request’s body is not null, 48516 // and the connection uses HTTP/2, then user agents may, and are even 48517 // encouraged to, transmit an RST_STREAM frame. 48518 // See, https://github.com/whatwg/fetch/issues/1288 48519 if (request.redirect !== 'manual') { 48520 fetchParams.controller.connection.destroy() 48521 } 48522 48523 // 2. Switch on request’s redirect mode: 48524 if (request.redirect === 'error') { 48525 // Set response to a network error. 48526 response = makeNetworkError('unexpected redirect') 48527 } else if (request.redirect === 'manual') { 48528 // Set response to an opaque-redirect filtered response whose internal 48529 // response is actualResponse. 48530 // NOTE(spec): On the web this would return an `opaqueredirect` response, 48531 // but that doesn't make sense server side. 48532 // See https://github.com/nodejs/undici/issues/1193. 48533 response = actualResponse 48534 } else if (request.redirect === 'follow') { 48535 // Set response to the result of running HTTP-redirect fetch given 48536 // fetchParams and response. 48537 response = await httpRedirectFetch(fetchParams, response) 48538 } else { 48539 assert(false) 48540 } 48541 } 48542 48543 // 9. Set response’s timing info to timingInfo. 48544 response.timingInfo = timingInfo 48545 48546 // 10. Return response. 48547 return response 48548 } 48549 48550 // https://fetch.spec.whatwg.org/#http-redirect-fetch 48551 function httpRedirectFetch (fetchParams, response) { 48552 // 1. Let request be fetchParams’s request. 48553 const request = fetchParams.request 48554 48555 // 2. Let actualResponse be response, if response is not a filtered response, 48556 // and response’s internal response otherwise. 48557 const actualResponse = response.internalResponse 48558 ? response.internalResponse 48559 : response 48560 48561 // 3. Let locationURL be actualResponse’s location URL given request’s current 48562 // URL’s fragment. 48563 let locationURL 48564 48565 try { 48566 locationURL = responseLocationURL( 48567 actualResponse, 48568 requestCurrentURL(request).hash 48569 ) 48570 48571 // 4. If locationURL is null, then return response. 48572 if (locationURL == null) { 48573 return response 48574 } 48575 } catch (err) { 48576 // 5. If locationURL is failure, then return a network error. 48577 return Promise.resolve(makeNetworkError(err)) 48578 } 48579 48580 // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network 48581 // error. 48582 if (!urlIsHttpHttpsScheme(locationURL)) { 48583 return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) 48584 } 48585 48586 // 7. If request’s redirect count is 20, then return a network error. 48587 if (request.redirectCount === 20) { 48588 return Promise.resolve(makeNetworkError('redirect count exceeded')) 48589 } 48590 48591 // 8. Increase request’s redirect count by 1. 48592 request.redirectCount += 1 48593 48594 // 9. If request’s mode is "cors", locationURL includes credentials, and 48595 // request’s origin is not same origin with locationURL’s origin, then return 48596 // a network error. 48597 if ( 48598 request.mode === 'cors' && 48599 (locationURL.username || locationURL.password) && 48600 !sameOrigin(request, locationURL) 48601 ) { 48602 return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) 48603 } 48604 48605 // 10. If request’s response tainting is "cors" and locationURL includes 48606 // credentials, then return a network error. 48607 if ( 48608 request.responseTainting === 'cors' && 48609 (locationURL.username || locationURL.password) 48610 ) { 48611 return Promise.resolve(makeNetworkError( 48612 'URL cannot contain credentials for request mode "cors"' 48613 )) 48614 } 48615 48616 // 11. If actualResponse’s status is not 303, request’s body is non-null, 48617 // and request’s body’s source is null, then return a network error. 48618 if ( 48619 actualResponse.status !== 303 && 48620 request.body != null && 48621 request.body.source == null 48622 ) { 48623 return Promise.resolve(makeNetworkError()) 48624 } 48625 48626 // 12. If one of the following is true 48627 // - actualResponse’s status is 301 or 302 and request’s method is `POST` 48628 // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` 48629 if ( 48630 ([301, 302].includes(actualResponse.status) && request.method === 'POST') || 48631 (actualResponse.status === 303 && 48632 !GET_OR_HEAD.includes(request.method)) 48633 ) { 48634 // then: 48635 // 1. Set request’s method to `GET` and request’s body to null. 48636 request.method = 'GET' 48637 request.body = null 48638 48639 // 2. For each headerName of request-body-header name, delete headerName from 48640 // request’s header list. 48641 for (const headerName of requestBodyHeader) { 48642 request.headersList.delete(headerName) 48643 } 48644 } 48645 48646 // 13. If request’s current URL’s origin is not same origin with locationURL’s 48647 // origin, then for each headerName of CORS non-wildcard request-header name, 48648 // delete headerName from request’s header list. 48649 if (!sameOrigin(requestCurrentURL(request), locationURL)) { 48650 // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name 48651 request.headersList.delete('authorization') 48652 48653 // https://fetch.spec.whatwg.org/#authentication-entries 48654 request.headersList.delete('proxy-authorization', true) 48655 48656 // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. 48657 request.headersList.delete('cookie') 48658 request.headersList.delete('host') 48659 } 48660 48661 // 14. If request’s body is non-null, then set request’s body to the first return 48662 // value of safely extracting request’s body’s source. 48663 if (request.body != null) { 48664 assert(request.body.source != null) 48665 request.body = safelyExtractBody(request.body.source)[0] 48666 } 48667 48668 // 15. Let timingInfo be fetchParams’s timing info. 48669 const timingInfo = fetchParams.timingInfo 48670 48671 // 16. Set timingInfo’s redirect end time and post-redirect start time to the 48672 // coarsened shared current time given fetchParams’s cross-origin isolated 48673 // capability. 48674 timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = 48675 coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) 48676 48677 // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s 48678 // redirect start time to timingInfo’s start time. 48679 if (timingInfo.redirectStartTime === 0) { 48680 timingInfo.redirectStartTime = timingInfo.startTime 48681 } 48682 48683 // 18. Append locationURL to request’s URL list. 48684 request.urlList.push(locationURL) 48685 48686 // 19. Invoke set request’s referrer policy on redirect on request and 48687 // actualResponse. 48688 setRequestReferrerPolicyOnRedirect(request, actualResponse) 48689 48690 // 20. Return the result of running main fetch given fetchParams and true. 48691 return mainFetch(fetchParams, true) 48692 } 48693 48694 // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch 48695 async function httpNetworkOrCacheFetch ( 48696 fetchParams, 48697 isAuthenticationFetch = false, 48698 isNewConnectionFetch = false 48699 ) { 48700 // 1. Let request be fetchParams’s request. 48701 const request = fetchParams.request 48702 48703 // 2. Let httpFetchParams be null. 48704 let httpFetchParams = null 48705 48706 // 3. Let httpRequest be null. 48707 let httpRequest = null 48708 48709 // 4. Let response be null. 48710 let response = null 48711 48712 // 5. Let storedResponse be null. 48713 // TODO: cache 48714 48715 // 6. Let httpCache be null. 48716 const httpCache = null 48717 48718 // 7. Let the revalidatingFlag be unset. 48719 const revalidatingFlag = false 48720 48721 // 8. Run these steps, but abort when the ongoing fetch is terminated: 48722 48723 // 1. If request’s window is "no-window" and request’s redirect mode is 48724 // "error", then set httpFetchParams to fetchParams and httpRequest to 48725 // request. 48726 if (request.window === 'no-window' && request.redirect === 'error') { 48727 httpFetchParams = fetchParams 48728 httpRequest = request 48729 } else { 48730 // Otherwise: 48731 48732 // 1. Set httpRequest to a clone of request. 48733 httpRequest = makeRequest(request) 48734 48735 // 2. Set httpFetchParams to a copy of fetchParams. 48736 httpFetchParams = { ...fetchParams } 48737 48738 // 3. Set httpFetchParams’s request to httpRequest. 48739 httpFetchParams.request = httpRequest 48740 } 48741 48742 // 3. Let includeCredentials be true if one of 48743 const includeCredentials = 48744 request.credentials === 'include' || 48745 (request.credentials === 'same-origin' && 48746 request.responseTainting === 'basic') 48747 48748 // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s 48749 // body is non-null; otherwise null. 48750 const contentLength = httpRequest.body ? httpRequest.body.length : null 48751 48752 // 5. Let contentLengthHeaderValue be null. 48753 let contentLengthHeaderValue = null 48754 48755 // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or 48756 // `PUT`, then set contentLengthHeaderValue to `0`. 48757 if ( 48758 httpRequest.body == null && 48759 ['POST', 'PUT'].includes(httpRequest.method) 48760 ) { 48761 contentLengthHeaderValue = '0' 48762 } 48763 48764 // 7. If contentLength is non-null, then set contentLengthHeaderValue to 48765 // contentLength, serialized and isomorphic encoded. 48766 if (contentLength != null) { 48767 contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) 48768 } 48769 48770 // 8. If contentLengthHeaderValue is non-null, then append 48771 // `Content-Length`/contentLengthHeaderValue to httpRequest’s header 48772 // list. 48773 if (contentLengthHeaderValue != null) { 48774 httpRequest.headersList.append('content-length', contentLengthHeaderValue) 48775 } 48776 48777 // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, 48778 // contentLengthHeaderValue) to httpRequest’s header list. 48779 48780 // 10. If contentLength is non-null and httpRequest’s keepalive is true, 48781 // then: 48782 if (contentLength != null && httpRequest.keepalive) { 48783 // NOTE: keepalive is a noop outside of browser context. 48784 } 48785 48786 // 11. If httpRequest’s referrer is a URL, then append 48787 // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, 48788 // to httpRequest’s header list. 48789 if (httpRequest.referrer instanceof URL) { 48790 httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) 48791 } 48792 48793 // 12. Append a request `Origin` header for httpRequest. 48794 appendRequestOriginHeader(httpRequest) 48795 48796 // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] 48797 appendFetchMetadata(httpRequest) 48798 48799 // 14. If httpRequest’s header list does not contain `User-Agent`, then 48800 // user agents should append `User-Agent`/default `User-Agent` value to 48801 // httpRequest’s header list. 48802 if (!httpRequest.headersList.contains('user-agent')) { 48803 httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') 48804 } 48805 48806 // 15. If httpRequest’s cache mode is "default" and httpRequest’s header 48807 // list contains `If-Modified-Since`, `If-None-Match`, 48808 // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set 48809 // httpRequest’s cache mode to "no-store". 48810 if ( 48811 httpRequest.cache === 'default' && 48812 (httpRequest.headersList.contains('if-modified-since') || 48813 httpRequest.headersList.contains('if-none-match') || 48814 httpRequest.headersList.contains('if-unmodified-since') || 48815 httpRequest.headersList.contains('if-match') || 48816 httpRequest.headersList.contains('if-range')) 48817 ) { 48818 httpRequest.cache = 'no-store' 48819 } 48820 48821 // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent 48822 // no-cache cache-control header modification flag is unset, and 48823 // httpRequest’s header list does not contain `Cache-Control`, then append 48824 // `Cache-Control`/`max-age=0` to httpRequest’s header list. 48825 if ( 48826 httpRequest.cache === 'no-cache' && 48827 !httpRequest.preventNoCacheCacheControlHeaderModification && 48828 !httpRequest.headersList.contains('cache-control') 48829 ) { 48830 httpRequest.headersList.append('cache-control', 'max-age=0') 48831 } 48832 48833 // 17. If httpRequest’s cache mode is "no-store" or "reload", then: 48834 if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { 48835 // 1. If httpRequest’s header list does not contain `Pragma`, then append 48836 // `Pragma`/`no-cache` to httpRequest’s header list. 48837 if (!httpRequest.headersList.contains('pragma')) { 48838 httpRequest.headersList.append('pragma', 'no-cache') 48839 } 48840 48841 // 2. If httpRequest’s header list does not contain `Cache-Control`, 48842 // then append `Cache-Control`/`no-cache` to httpRequest’s header list. 48843 if (!httpRequest.headersList.contains('cache-control')) { 48844 httpRequest.headersList.append('cache-control', 'no-cache') 48845 } 48846 } 48847 48848 // 18. If httpRequest’s header list contains `Range`, then append 48849 // `Accept-Encoding`/`identity` to httpRequest’s header list. 48850 if (httpRequest.headersList.contains('range')) { 48851 httpRequest.headersList.append('accept-encoding', 'identity') 48852 } 48853 48854 // 19. Modify httpRequest’s header list per HTTP. Do not append a given 48855 // header if httpRequest’s header list contains that header’s name. 48856 // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 48857 if (!httpRequest.headersList.contains('accept-encoding')) { 48858 if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { 48859 httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') 48860 } else { 48861 httpRequest.headersList.append('accept-encoding', 'gzip, deflate') 48862 } 48863 } 48864 48865 httpRequest.headersList.delete('host') 48866 48867 // 20. If includeCredentials is true, then: 48868 if (includeCredentials) { 48869 // 1. If the user agent is not configured to block cookies for httpRequest 48870 // (see section 7 of [COOKIES]), then: 48871 // TODO: credentials 48872 // 2. If httpRequest’s header list does not contain `Authorization`, then: 48873 // TODO: credentials 48874 } 48875 48876 // 21. If there’s a proxy-authentication entry, use it as appropriate. 48877 // TODO: proxy-authentication 48878 48879 // 22. Set httpCache to the result of determining the HTTP cache 48880 // partition, given httpRequest. 48881 // TODO: cache 48882 48883 // 23. If httpCache is null, then set httpRequest’s cache mode to 48884 // "no-store". 48885 if (httpCache == null) { 48886 httpRequest.cache = 'no-store' 48887 } 48888 48889 // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", 48890 // then: 48891 if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { 48892 // TODO: cache 48893 } 48894 48895 // 9. If aborted, then return the appropriate network error for fetchParams. 48896 // TODO 48897 48898 // 10. If response is null, then: 48899 if (response == null) { 48900 // 1. If httpRequest’s cache mode is "only-if-cached", then return a 48901 // network error. 48902 if (httpRequest.mode === 'only-if-cached') { 48903 return makeNetworkError('only if cached') 48904 } 48905 48906 // 2. Let forwardResponse be the result of running HTTP-network fetch 48907 // given httpFetchParams, includeCredentials, and isNewConnectionFetch. 48908 const forwardResponse = await httpNetworkFetch( 48909 httpFetchParams, 48910 includeCredentials, 48911 isNewConnectionFetch 48912 ) 48913 48914 // 3. If httpRequest’s method is unsafe and forwardResponse’s status is 48915 // in the range 200 to 399, inclusive, invalidate appropriate stored 48916 // responses in httpCache, as per the "Invalidation" chapter of HTTP 48917 // Caching, and set storedResponse to null. [HTTP-CACHING] 48918 if ( 48919 !safeMethodsSet.has(httpRequest.method) && 48920 forwardResponse.status >= 200 && 48921 forwardResponse.status <= 399 48922 ) { 48923 // TODO: cache 48924 } 48925 48926 // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, 48927 // then: 48928 if (revalidatingFlag && forwardResponse.status === 304) { 48929 // TODO: cache 48930 } 48931 48932 // 5. If response is null, then: 48933 if (response == null) { 48934 // 1. Set response to forwardResponse. 48935 response = forwardResponse 48936 48937 // 2. Store httpRequest and forwardResponse in httpCache, as per the 48938 // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] 48939 // TODO: cache 48940 } 48941 } 48942 48943 // 11. Set response’s URL list to a clone of httpRequest’s URL list. 48944 response.urlList = [...httpRequest.urlList] 48945 48946 // 12. If httpRequest’s header list contains `Range`, then set response’s 48947 // range-requested flag. 48948 if (httpRequest.headersList.contains('range')) { 48949 response.rangeRequested = true 48950 } 48951 48952 // 13. Set response’s request-includes-credentials to includeCredentials. 48953 response.requestIncludesCredentials = includeCredentials 48954 48955 // 14. If response’s status is 401, httpRequest’s response tainting is not 48956 // "cors", includeCredentials is true, and request’s window is an environment 48957 // settings object, then: 48958 // TODO 48959 48960 // 15. If response’s status is 407, then: 48961 if (response.status === 407) { 48962 // 1. If request’s window is "no-window", then return a network error. 48963 if (request.window === 'no-window') { 48964 return makeNetworkError() 48965 } 48966 48967 // 2. ??? 48968 48969 // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. 48970 if (isCancelled(fetchParams)) { 48971 return makeAppropriateNetworkError(fetchParams) 48972 } 48973 48974 // 4. Prompt the end user as appropriate in request’s window and store 48975 // the result as a proxy-authentication entry. [HTTP-AUTH] 48976 // TODO: Invoke some kind of callback? 48977 48978 // 5. Set response to the result of running HTTP-network-or-cache fetch given 48979 // fetchParams. 48980 // TODO 48981 return makeNetworkError('proxy authentication required') 48982 } 48983 48984 // 16. If all of the following are true 48985 if ( 48986 // response’s status is 421 48987 response.status === 421 && 48988 // isNewConnectionFetch is false 48989 !isNewConnectionFetch && 48990 // request’s body is null, or request’s body is non-null and request’s body’s source is non-null 48991 (request.body == null || request.body.source != null) 48992 ) { 48993 // then: 48994 48995 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. 48996 if (isCancelled(fetchParams)) { 48997 return makeAppropriateNetworkError(fetchParams) 48998 } 48999 49000 // 2. Set response to the result of running HTTP-network-or-cache 49001 // fetch given fetchParams, isAuthenticationFetch, and true. 49002 49003 // TODO (spec): The spec doesn't specify this but we need to cancel 49004 // the active response before we can start a new one. 49005 // https://github.com/whatwg/fetch/issues/1293 49006 fetchParams.controller.connection.destroy() 49007 49008 response = await httpNetworkOrCacheFetch( 49009 fetchParams, 49010 isAuthenticationFetch, 49011 true 49012 ) 49013 } 49014 49015 // 17. If isAuthenticationFetch is true, then create an authentication entry 49016 if (isAuthenticationFetch) { 49017 // TODO 49018 } 49019 49020 // 18. Return response. 49021 return response 49022 } 49023 49024 // https://fetch.spec.whatwg.org/#http-network-fetch 49025 async function httpNetworkFetch ( 49026 fetchParams, 49027 includeCredentials = false, 49028 forceNewConnection = false 49029 ) { 49030 assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) 49031 49032 fetchParams.controller.connection = { 49033 abort: null, 49034 destroyed: false, 49035 destroy (err) { 49036 if (!this.destroyed) { 49037 this.destroyed = true 49038 this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) 49039 } 49040 } 49041 } 49042 49043 // 1. Let request be fetchParams’s request. 49044 const request = fetchParams.request 49045 49046 // 2. Let response be null. 49047 let response = null 49048 49049 // 3. Let timingInfo be fetchParams’s timing info. 49050 const timingInfo = fetchParams.timingInfo 49051 49052 // 4. Let httpCache be the result of determining the HTTP cache partition, 49053 // given request. 49054 // TODO: cache 49055 const httpCache = null 49056 49057 // 5. If httpCache is null, then set request’s cache mode to "no-store". 49058 if (httpCache == null) { 49059 request.cache = 'no-store' 49060 } 49061 49062 // 6. Let networkPartitionKey be the result of determining the network 49063 // partition key given request. 49064 // TODO 49065 49066 // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise 49067 // "no". 49068 const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars 49069 49070 // 8. Switch on request’s mode: 49071 if (request.mode === 'websocket') { 49072 // Let connection be the result of obtaining a WebSocket connection, 49073 // given request’s current URL. 49074 // TODO 49075 } else { 49076 // Let connection be the result of obtaining a connection, given 49077 // networkPartitionKey, request’s current URL’s origin, 49078 // includeCredentials, and forceNewConnection. 49079 // TODO 49080 } 49081 49082 // 9. Run these steps, but abort when the ongoing fetch is terminated: 49083 49084 // 1. If connection is failure, then return a network error. 49085 49086 // 2. Set timingInfo’s final connection timing info to the result of 49087 // calling clamp and coarsen connection timing info with connection’s 49088 // timing info, timingInfo’s post-redirect start time, and fetchParams’s 49089 // cross-origin isolated capability. 49090 49091 // 3. If connection is not an HTTP/2 connection, request’s body is non-null, 49092 // and request’s body’s source is null, then append (`Transfer-Encoding`, 49093 // `chunked`) to request’s header list. 49094 49095 // 4. Set timingInfo’s final network-request start time to the coarsened 49096 // shared current time given fetchParams’s cross-origin isolated 49097 // capability. 49098 49099 // 5. Set response to the result of making an HTTP request over connection 49100 // using request with the following caveats: 49101 49102 // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] 49103 // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] 49104 49105 // - If request’s body is non-null, and request’s body’s source is null, 49106 // then the user agent may have a buffer of up to 64 kibibytes and store 49107 // a part of request’s body in that buffer. If the user agent reads from 49108 // request’s body beyond that buffer’s size and the user agent needs to 49109 // resend request, then instead return a network error. 49110 49111 // - Set timingInfo’s final network-response start time to the coarsened 49112 // shared current time given fetchParams’s cross-origin isolated capability, 49113 // immediately after the user agent’s HTTP parser receives the first byte 49114 // of the response (e.g., frame header bytes for HTTP/2 or response status 49115 // line for HTTP/1.x). 49116 49117 // - Wait until all the headers are transmitted. 49118 49119 // - Any responses whose status is in the range 100 to 199, inclusive, 49120 // and is not 101, are to be ignored, except for the purposes of setting 49121 // timingInfo’s final network-response start time above. 49122 49123 // - If request’s header list contains `Transfer-Encoding`/`chunked` and 49124 // response is transferred via HTTP/1.0 or older, then return a network 49125 // error. 49126 49127 // - If the HTTP request results in a TLS client certificate dialog, then: 49128 49129 // 1. If request’s window is an environment settings object, make the 49130 // dialog available in request’s window. 49131 49132 // 2. Otherwise, return a network error. 49133 49134 // To transmit request’s body body, run these steps: 49135 let requestBody = null 49136 // 1. If body is null and fetchParams’s process request end-of-body is 49137 // non-null, then queue a fetch task given fetchParams’s process request 49138 // end-of-body and fetchParams’s task destination. 49139 if (request.body == null && fetchParams.processRequestEndOfBody) { 49140 queueMicrotask(() => fetchParams.processRequestEndOfBody()) 49141 } else if (request.body != null) { 49142 // 2. Otherwise, if body is non-null: 49143 49144 // 1. Let processBodyChunk given bytes be these steps: 49145 const processBodyChunk = async function * (bytes) { 49146 // 1. If the ongoing fetch is terminated, then abort these steps. 49147 if (isCancelled(fetchParams)) { 49148 return 49149 } 49150 49151 // 2. Run this step in parallel: transmit bytes. 49152 yield bytes 49153 49154 // 3. If fetchParams’s process request body is non-null, then run 49155 // fetchParams’s process request body given bytes’s length. 49156 fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) 49157 } 49158 49159 // 2. Let processEndOfBody be these steps: 49160 const processEndOfBody = () => { 49161 // 1. If fetchParams is canceled, then abort these steps. 49162 if (isCancelled(fetchParams)) { 49163 return 49164 } 49165 49166 // 2. If fetchParams’s process request end-of-body is non-null, 49167 // then run fetchParams’s process request end-of-body. 49168 if (fetchParams.processRequestEndOfBody) { 49169 fetchParams.processRequestEndOfBody() 49170 } 49171 } 49172 49173 // 3. Let processBodyError given e be these steps: 49174 const processBodyError = (e) => { 49175 // 1. If fetchParams is canceled, then abort these steps. 49176 if (isCancelled(fetchParams)) { 49177 return 49178 } 49179 49180 // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. 49181 if (e.name === 'AbortError') { 49182 fetchParams.controller.abort() 49183 } else { 49184 fetchParams.controller.terminate(e) 49185 } 49186 } 49187 49188 // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, 49189 // processBodyError, and fetchParams’s task destination. 49190 requestBody = (async function * () { 49191 try { 49192 for await (const bytes of request.body.stream) { 49193 yield * processBodyChunk(bytes) 49194 } 49195 processEndOfBody() 49196 } catch (err) { 49197 processBodyError(err) 49198 } 49199 })() 49200 } 49201 49202 try { 49203 // socket is only provided for websockets 49204 const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) 49205 49206 if (socket) { 49207 response = makeResponse({ status, statusText, headersList, socket }) 49208 } else { 49209 const iterator = body[Symbol.asyncIterator]() 49210 fetchParams.controller.next = () => iterator.next() 49211 49212 response = makeResponse({ status, statusText, headersList }) 49213 } 49214 } catch (err) { 49215 // 10. If aborted, then: 49216 if (err.name === 'AbortError') { 49217 // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. 49218 fetchParams.controller.connection.destroy() 49219 49220 // 2. Return the appropriate network error for fetchParams. 49221 return makeAppropriateNetworkError(fetchParams, err) 49222 } 49223 49224 return makeNetworkError(err) 49225 } 49226 49227 // 11. Let pullAlgorithm be an action that resumes the ongoing fetch 49228 // if it is suspended. 49229 const pullAlgorithm = () => { 49230 fetchParams.controller.resume() 49231 } 49232 49233 // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s 49234 // controller with reason, given reason. 49235 const cancelAlgorithm = (reason) => { 49236 fetchParams.controller.abort(reason) 49237 } 49238 49239 // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by 49240 // the user agent. 49241 // TODO 49242 49243 // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object 49244 // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. 49245 // TODO 49246 49247 // 15. Let stream be a new ReadableStream. 49248 // 16. Set up stream with pullAlgorithm set to pullAlgorithm, 49249 // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to 49250 // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. 49251 if (!ReadableStream) { 49252 ReadableStream = (__nccwpck_require__(5356).ReadableStream) 49253 } 49254 49255 const stream = new ReadableStream( 49256 { 49257 async start (controller) { 49258 fetchParams.controller.controller = controller 49259 }, 49260 async pull (controller) { 49261 await pullAlgorithm(controller) 49262 }, 49263 async cancel (reason) { 49264 await cancelAlgorithm(reason) 49265 } 49266 }, 49267 { 49268 highWaterMark: 0, 49269 size () { 49270 return 1 49271 } 49272 } 49273 ) 49274 49275 // 17. Run these steps, but abort when the ongoing fetch is terminated: 49276 49277 // 1. Set response’s body to a new body whose stream is stream. 49278 response.body = { stream } 49279 49280 // 2. If response is not a network error and request’s cache mode is 49281 // not "no-store", then update response in httpCache for request. 49282 // TODO 49283 49284 // 3. If includeCredentials is true and the user agent is not configured 49285 // to block cookies for request (see section 7 of [COOKIES]), then run the 49286 // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on 49287 // the value of each header whose name is a byte-case-insensitive match for 49288 // `Set-Cookie` in response’s header list, if any, and request’s current URL. 49289 // TODO 49290 49291 // 18. If aborted, then: 49292 // TODO 49293 49294 // 19. Run these steps in parallel: 49295 49296 // 1. Run these steps, but abort when fetchParams is canceled: 49297 fetchParams.controller.on('terminated', onAborted) 49298 fetchParams.controller.resume = async () => { 49299 // 1. While true 49300 while (true) { 49301 // 1-3. See onData... 49302 49303 // 4. Set bytes to the result of handling content codings given 49304 // codings and bytes. 49305 let bytes 49306 let isFailure 49307 try { 49308 const { done, value } = await fetchParams.controller.next() 49309 49310 if (isAborted(fetchParams)) { 49311 break 49312 } 49313 49314 bytes = done ? undefined : value 49315 } catch (err) { 49316 if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { 49317 // zlib doesn't like empty streams. 49318 bytes = undefined 49319 } else { 49320 bytes = err 49321 49322 // err may be propagated from the result of calling readablestream.cancel, 49323 // which might not be an error. https://github.com/nodejs/undici/issues/2009 49324 isFailure = true 49325 } 49326 } 49327 49328 if (bytes === undefined) { 49329 // 2. Otherwise, if the bytes transmission for response’s message 49330 // body is done normally and stream is readable, then close 49331 // stream, finalize response for fetchParams and response, and 49332 // abort these in-parallel steps. 49333 readableStreamClose(fetchParams.controller.controller) 49334 49335 finalizeResponse(fetchParams, response) 49336 49337 return 49338 } 49339 49340 // 5. Increase timingInfo’s decoded body size by bytes’s length. 49341 timingInfo.decodedBodySize += bytes?.byteLength ?? 0 49342 49343 // 6. If bytes is failure, then terminate fetchParams’s controller. 49344 if (isFailure) { 49345 fetchParams.controller.terminate(bytes) 49346 return 49347 } 49348 49349 // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes 49350 // into stream. 49351 fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) 49352 49353 // 8. If stream is errored, then terminate the ongoing fetch. 49354 if (isErrored(stream)) { 49355 fetchParams.controller.terminate() 49356 return 49357 } 49358 49359 // 9. If stream doesn’t need more data ask the user agent to suspend 49360 // the ongoing fetch. 49361 if (!fetchParams.controller.controller.desiredSize) { 49362 return 49363 } 49364 } 49365 } 49366 49367 // 2. If aborted, then: 49368 function onAborted (reason) { 49369 // 2. If fetchParams is aborted, then: 49370 if (isAborted(fetchParams)) { 49371 // 1. Set response’s aborted flag. 49372 response.aborted = true 49373 49374 // 2. If stream is readable, then error stream with the result of 49375 // deserialize a serialized abort reason given fetchParams’s 49376 // controller’s serialized abort reason and an 49377 // implementation-defined realm. 49378 if (isReadable(stream)) { 49379 fetchParams.controller.controller.error( 49380 fetchParams.controller.serializedAbortReason 49381 ) 49382 } 49383 } else { 49384 // 3. Otherwise, if stream is readable, error stream with a TypeError. 49385 if (isReadable(stream)) { 49386 fetchParams.controller.controller.error(new TypeError('terminated', { 49387 cause: isErrorLike(reason) ? reason : undefined 49388 })) 49389 } 49390 } 49391 49392 // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. 49393 // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. 49394 fetchParams.controller.connection.destroy() 49395 } 49396 49397 // 20. Return response. 49398 return response 49399 49400 async function dispatch ({ body }) { 49401 const url = requestCurrentURL(request) 49402 /** @type {import('../..').Agent} */ 49403 const agent = fetchParams.controller.dispatcher 49404 49405 return new Promise((resolve, reject) => agent.dispatch( 49406 { 49407 path: url.pathname + url.search, 49408 origin: url.origin, 49409 method: request.method, 49410 body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, 49411 headers: request.headersList.entries, 49412 maxRedirections: 0, 49413 upgrade: request.mode === 'websocket' ? 'websocket' : undefined 49414 }, 49415 { 49416 body: null, 49417 abort: null, 49418 49419 onConnect (abort) { 49420 // TODO (fix): Do we need connection here? 49421 const { connection } = fetchParams.controller 49422 49423 if (connection.destroyed) { 49424 abort(new DOMException('The operation was aborted.', 'AbortError')) 49425 } else { 49426 fetchParams.controller.on('terminated', abort) 49427 this.abort = connection.abort = abort 49428 } 49429 }, 49430 49431 onHeaders (status, headersList, resume, statusText) { 49432 if (status < 200) { 49433 return 49434 } 49435 49436 let codings = [] 49437 let location = '' 49438 49439 const headers = new Headers() 49440 49441 // For H2, the headers are a plain JS object 49442 // We distinguish between them and iterate accordingly 49443 if (Array.isArray(headersList)) { 49444 for (let n = 0; n < headersList.length; n += 2) { 49445 const key = headersList[n + 0].toString('latin1') 49446 const val = headersList[n + 1].toString('latin1') 49447 if (key.toLowerCase() === 'content-encoding') { 49448 // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 49449 // "All content-coding values are case-insensitive..." 49450 codings = val.toLowerCase().split(',').map((x) => x.trim()) 49451 } else if (key.toLowerCase() === 'location') { 49452 location = val 49453 } 49454 49455 headers[kHeadersList].append(key, val) 49456 } 49457 } else { 49458 const keys = Object.keys(headersList) 49459 for (const key of keys) { 49460 const val = headersList[key] 49461 if (key.toLowerCase() === 'content-encoding') { 49462 // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 49463 // "All content-coding values are case-insensitive..." 49464 codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() 49465 } else if (key.toLowerCase() === 'location') { 49466 location = val 49467 } 49468 49469 headers[kHeadersList].append(key, val) 49470 } 49471 } 49472 49473 this.body = new Readable({ read: resume }) 49474 49475 const decoders = [] 49476 49477 const willFollow = request.redirect === 'follow' && 49478 location && 49479 redirectStatusSet.has(status) 49480 49481 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding 49482 if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { 49483 for (const coding of codings) { 49484 // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 49485 if (coding === 'x-gzip' || coding === 'gzip') { 49486 decoders.push(zlib.createGunzip({ 49487 // Be less strict when decoding compressed responses, since sometimes 49488 // servers send slightly invalid responses that are still accepted 49489 // by common browsers. 49490 // Always using Z_SYNC_FLUSH is what cURL does. 49491 flush: zlib.constants.Z_SYNC_FLUSH, 49492 finishFlush: zlib.constants.Z_SYNC_FLUSH 49493 })) 49494 } else if (coding === 'deflate') { 49495 decoders.push(zlib.createInflate()) 49496 } else if (coding === 'br') { 49497 decoders.push(zlib.createBrotliDecompress()) 49498 } else { 49499 decoders.length = 0 49500 break 49501 } 49502 } 49503 } 49504 49505 resolve({ 49506 status, 49507 statusText, 49508 headersList: headers[kHeadersList], 49509 body: decoders.length 49510 ? pipeline(this.body, ...decoders, () => { }) 49511 : this.body.on('error', () => {}) 49512 }) 49513 49514 return true 49515 }, 49516 49517 onData (chunk) { 49518 if (fetchParams.controller.dump) { 49519 return 49520 } 49521 49522 // 1. If one or more bytes have been transmitted from response’s 49523 // message body, then: 49524 49525 // 1. Let bytes be the transmitted bytes. 49526 const bytes = chunk 49527 49528 // 2. Let codings be the result of extracting header list values 49529 // given `Content-Encoding` and response’s header list. 49530 // See pullAlgorithm. 49531 49532 // 3. Increase timingInfo’s encoded body size by bytes’s length. 49533 timingInfo.encodedBodySize += bytes.byteLength 49534 49535 // 4. See pullAlgorithm... 49536 49537 return this.body.push(bytes) 49538 }, 49539 49540 onComplete () { 49541 if (this.abort) { 49542 fetchParams.controller.off('terminated', this.abort) 49543 } 49544 49545 fetchParams.controller.ended = true 49546 49547 this.body.push(null) 49548 }, 49549 49550 onError (error) { 49551 if (this.abort) { 49552 fetchParams.controller.off('terminated', this.abort) 49553 } 49554 49555 this.body?.destroy(error) 49556 49557 fetchParams.controller.terminate(error) 49558 49559 reject(error) 49560 }, 49561 49562 onUpgrade (status, headersList, socket) { 49563 if (status !== 101) { 49564 return 49565 } 49566 49567 const headers = new Headers() 49568 49569 for (let n = 0; n < headersList.length; n += 2) { 49570 const key = headersList[n + 0].toString('latin1') 49571 const val = headersList[n + 1].toString('latin1') 49572 49573 headers[kHeadersList].append(key, val) 49574 } 49575 49576 resolve({ 49577 status, 49578 statusText: STATUS_CODES[status], 49579 headersList: headers[kHeadersList], 49580 socket 49581 }) 49582 49583 return true 49584 } 49585 } 49586 )) 49587 } 49588 } 49589 49590 module.exports = { 49591 fetch, 49592 Fetch, 49593 fetching, 49594 finalizeAndReportTiming 49595 } 49596 49597 49598 /***/ }), 49599 49600 /***/ 8359: 49601 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 49602 49603 "use strict"; 49604 /* globals AbortController */ 49605 49606 49607 49608 const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(1472) 49609 const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(554) 49610 const { FinalizationRegistry } = __nccwpck_require__(6436)() 49611 const util = __nccwpck_require__(3983) 49612 const { 49613 isValidHTTPToken, 49614 sameOrigin, 49615 normalizeMethod, 49616 makePolicyContainer, 49617 normalizeMethodRecord 49618 } = __nccwpck_require__(2538) 49619 const { 49620 forbiddenMethodsSet, 49621 corsSafeListedMethodsSet, 49622 referrerPolicy, 49623 requestRedirect, 49624 requestMode, 49625 requestCredentials, 49626 requestCache, 49627 requestDuplex 49628 } = __nccwpck_require__(1037) 49629 const { kEnumerableProperty } = util 49630 const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) 49631 const { webidl } = __nccwpck_require__(1744) 49632 const { getGlobalOrigin } = __nccwpck_require__(1246) 49633 const { URLSerializer } = __nccwpck_require__(685) 49634 const { kHeadersList, kConstruct } = __nccwpck_require__(2785) 49635 const assert = __nccwpck_require__(9491) 49636 const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) 49637 49638 let TransformStream = globalThis.TransformStream 49639 49640 const kAbortController = Symbol('abortController') 49641 49642 const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { 49643 signal.removeEventListener('abort', abort) 49644 }) 49645 49646 // https://fetch.spec.whatwg.org/#request-class 49647 class Request { 49648 // https://fetch.spec.whatwg.org/#dom-request 49649 constructor (input, init = {}) { 49650 if (input === kConstruct) { 49651 return 49652 } 49653 49654 webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) 49655 49656 input = webidl.converters.RequestInfo(input) 49657 init = webidl.converters.RequestInit(init) 49658 49659 // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object 49660 this[kRealm] = { 49661 settingsObject: { 49662 baseUrl: getGlobalOrigin(), 49663 get origin () { 49664 return this.baseUrl?.origin 49665 }, 49666 policyContainer: makePolicyContainer() 49667 } 49668 } 49669 49670 // 1. Let request be null. 49671 let request = null 49672 49673 // 2. Let fallbackMode be null. 49674 let fallbackMode = null 49675 49676 // 3. Let baseURL be this’s relevant settings object’s API base URL. 49677 const baseUrl = this[kRealm].settingsObject.baseUrl 49678 49679 // 4. Let signal be null. 49680 let signal = null 49681 49682 // 5. If input is a string, then: 49683 if (typeof input === 'string') { 49684 // 1. Let parsedURL be the result of parsing input with baseURL. 49685 // 2. If parsedURL is failure, then throw a TypeError. 49686 let parsedURL 49687 try { 49688 parsedURL = new URL(input, baseUrl) 49689 } catch (err) { 49690 throw new TypeError('Failed to parse URL from ' + input, { cause: err }) 49691 } 49692 49693 // 3. If parsedURL includes credentials, then throw a TypeError. 49694 if (parsedURL.username || parsedURL.password) { 49695 throw new TypeError( 49696 'Request cannot be constructed from a URL that includes credentials: ' + 49697 input 49698 ) 49699 } 49700 49701 // 4. Set request to a new request whose URL is parsedURL. 49702 request = makeRequest({ urlList: [parsedURL] }) 49703 49704 // 5. Set fallbackMode to "cors". 49705 fallbackMode = 'cors' 49706 } else { 49707 // 6. Otherwise: 49708 49709 // 7. Assert: input is a Request object. 49710 assert(input instanceof Request) 49711 49712 // 8. Set request to input’s request. 49713 request = input[kState] 49714 49715 // 9. Set signal to input’s signal. 49716 signal = input[kSignal] 49717 } 49718 49719 // 7. Let origin be this’s relevant settings object’s origin. 49720 const origin = this[kRealm].settingsObject.origin 49721 49722 // 8. Let window be "client". 49723 let window = 'client' 49724 49725 // 9. If request’s window is an environment settings object and its origin 49726 // is same origin with origin, then set window to request’s window. 49727 if ( 49728 request.window?.constructor?.name === 'EnvironmentSettingsObject' && 49729 sameOrigin(request.window, origin) 49730 ) { 49731 window = request.window 49732 } 49733 49734 // 10. If init["window"] exists and is non-null, then throw a TypeError. 49735 if (init.window != null) { 49736 throw new TypeError(`'window' option '${window}' must be null`) 49737 } 49738 49739 // 11. If init["window"] exists, then set window to "no-window". 49740 if ('window' in init) { 49741 window = 'no-window' 49742 } 49743 49744 // 12. Set request to a new request with the following properties: 49745 request = makeRequest({ 49746 // URL request’s URL. 49747 // undici implementation note: this is set as the first item in request's urlList in makeRequest 49748 // method request’s method. 49749 method: request.method, 49750 // header list A copy of request’s header list. 49751 // undici implementation note: headersList is cloned in makeRequest 49752 headersList: request.headersList, 49753 // unsafe-request flag Set. 49754 unsafeRequest: request.unsafeRequest, 49755 // client This’s relevant settings object. 49756 client: this[kRealm].settingsObject, 49757 // window window. 49758 window, 49759 // priority request’s priority. 49760 priority: request.priority, 49761 // origin request’s origin. The propagation of the origin is only significant for navigation requests 49762 // being handled by a service worker. In this scenario a request can have an origin that is different 49763 // from the current client. 49764 origin: request.origin, 49765 // referrer request’s referrer. 49766 referrer: request.referrer, 49767 // referrer policy request’s referrer policy. 49768 referrerPolicy: request.referrerPolicy, 49769 // mode request’s mode. 49770 mode: request.mode, 49771 // credentials mode request’s credentials mode. 49772 credentials: request.credentials, 49773 // cache mode request’s cache mode. 49774 cache: request.cache, 49775 // redirect mode request’s redirect mode. 49776 redirect: request.redirect, 49777 // integrity metadata request’s integrity metadata. 49778 integrity: request.integrity, 49779 // keepalive request’s keepalive. 49780 keepalive: request.keepalive, 49781 // reload-navigation flag request’s reload-navigation flag. 49782 reloadNavigation: request.reloadNavigation, 49783 // history-navigation flag request’s history-navigation flag. 49784 historyNavigation: request.historyNavigation, 49785 // URL list A clone of request’s URL list. 49786 urlList: [...request.urlList] 49787 }) 49788 49789 const initHasKey = Object.keys(init).length !== 0 49790 49791 // 13. If init is not empty, then: 49792 if (initHasKey) { 49793 // 1. If request’s mode is "navigate", then set it to "same-origin". 49794 if (request.mode === 'navigate') { 49795 request.mode = 'same-origin' 49796 } 49797 49798 // 2. Unset request’s reload-navigation flag. 49799 request.reloadNavigation = false 49800 49801 // 3. Unset request’s history-navigation flag. 49802 request.historyNavigation = false 49803 49804 // 4. Set request’s origin to "client". 49805 request.origin = 'client' 49806 49807 // 5. Set request’s referrer to "client" 49808 request.referrer = 'client' 49809 49810 // 6. Set request’s referrer policy to the empty string. 49811 request.referrerPolicy = '' 49812 49813 // 7. Set request’s URL to request’s current URL. 49814 request.url = request.urlList[request.urlList.length - 1] 49815 49816 // 8. Set request’s URL list to « request’s URL ». 49817 request.urlList = [request.url] 49818 } 49819 49820 // 14. If init["referrer"] exists, then: 49821 if (init.referrer !== undefined) { 49822 // 1. Let referrer be init["referrer"]. 49823 const referrer = init.referrer 49824 49825 // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". 49826 if (referrer === '') { 49827 request.referrer = 'no-referrer' 49828 } else { 49829 // 1. Let parsedReferrer be the result of parsing referrer with 49830 // baseURL. 49831 // 2. If parsedReferrer is failure, then throw a TypeError. 49832 let parsedReferrer 49833 try { 49834 parsedReferrer = new URL(referrer, baseUrl) 49835 } catch (err) { 49836 throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) 49837 } 49838 49839 // 3. If one of the following is true 49840 // - parsedReferrer’s scheme is "about" and path is the string "client" 49841 // - parsedReferrer’s origin is not same origin with origin 49842 // then set request’s referrer to "client". 49843 if ( 49844 (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || 49845 (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) 49846 ) { 49847 request.referrer = 'client' 49848 } else { 49849 // 4. Otherwise, set request’s referrer to parsedReferrer. 49850 request.referrer = parsedReferrer 49851 } 49852 } 49853 } 49854 49855 // 15. If init["referrerPolicy"] exists, then set request’s referrer policy 49856 // to it. 49857 if (init.referrerPolicy !== undefined) { 49858 request.referrerPolicy = init.referrerPolicy 49859 } 49860 49861 // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. 49862 let mode 49863 if (init.mode !== undefined) { 49864 mode = init.mode 49865 } else { 49866 mode = fallbackMode 49867 } 49868 49869 // 17. If mode is "navigate", then throw a TypeError. 49870 if (mode === 'navigate') { 49871 throw webidl.errors.exception({ 49872 header: 'Request constructor', 49873 message: 'invalid request mode navigate.' 49874 }) 49875 } 49876 49877 // 18. If mode is non-null, set request’s mode to mode. 49878 if (mode != null) { 49879 request.mode = mode 49880 } 49881 49882 // 19. If init["credentials"] exists, then set request’s credentials mode 49883 // to it. 49884 if (init.credentials !== undefined) { 49885 request.credentials = init.credentials 49886 } 49887 49888 // 18. If init["cache"] exists, then set request’s cache mode to it. 49889 if (init.cache !== undefined) { 49890 request.cache = init.cache 49891 } 49892 49893 // 21. If request’s cache mode is "only-if-cached" and request’s mode is 49894 // not "same-origin", then throw a TypeError. 49895 if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { 49896 throw new TypeError( 49897 "'only-if-cached' can be set only with 'same-origin' mode" 49898 ) 49899 } 49900 49901 // 22. If init["redirect"] exists, then set request’s redirect mode to it. 49902 if (init.redirect !== undefined) { 49903 request.redirect = init.redirect 49904 } 49905 49906 // 23. If init["integrity"] exists, then set request’s integrity metadata to it. 49907 if (init.integrity != null) { 49908 request.integrity = String(init.integrity) 49909 } 49910 49911 // 24. If init["keepalive"] exists, then set request’s keepalive to it. 49912 if (init.keepalive !== undefined) { 49913 request.keepalive = Boolean(init.keepalive) 49914 } 49915 49916 // 25. If init["method"] exists, then: 49917 if (init.method !== undefined) { 49918 // 1. Let method be init["method"]. 49919 let method = init.method 49920 49921 // 2. If method is not a method or method is a forbidden method, then 49922 // throw a TypeError. 49923 if (!isValidHTTPToken(method)) { 49924 throw new TypeError(`'${method}' is not a valid HTTP method.`) 49925 } 49926 49927 if (forbiddenMethodsSet.has(method.toUpperCase())) { 49928 throw new TypeError(`'${method}' HTTP method is unsupported.`) 49929 } 49930 49931 // 3. Normalize method. 49932 method = normalizeMethodRecord[method] ?? normalizeMethod(method) 49933 49934 // 4. Set request’s method to method. 49935 request.method = method 49936 } 49937 49938 // 26. If init["signal"] exists, then set signal to it. 49939 if (init.signal !== undefined) { 49940 signal = init.signal 49941 } 49942 49943 // 27. Set this’s request to request. 49944 this[kState] = request 49945 49946 // 28. Set this’s signal to a new AbortSignal object with this’s relevant 49947 // Realm. 49948 // TODO: could this be simplified with AbortSignal.any 49949 // (https://dom.spec.whatwg.org/#dom-abortsignal-any) 49950 const ac = new AbortController() 49951 this[kSignal] = ac.signal 49952 this[kSignal][kRealm] = this[kRealm] 49953 49954 // 29. If signal is not null, then make this’s signal follow signal. 49955 if (signal != null) { 49956 if ( 49957 !signal || 49958 typeof signal.aborted !== 'boolean' || 49959 typeof signal.addEventListener !== 'function' 49960 ) { 49961 throw new TypeError( 49962 "Failed to construct 'Request': member signal is not of type AbortSignal." 49963 ) 49964 } 49965 49966 if (signal.aborted) { 49967 ac.abort(signal.reason) 49968 } else { 49969 // Keep a strong ref to ac while request object 49970 // is alive. This is needed to prevent AbortController 49971 // from being prematurely garbage collected. 49972 // See, https://github.com/nodejs/undici/issues/1926. 49973 this[kAbortController] = ac 49974 49975 const acRef = new WeakRef(ac) 49976 const abort = function () { 49977 const ac = acRef.deref() 49978 if (ac !== undefined) { 49979 ac.abort(this.reason) 49980 } 49981 } 49982 49983 // Third-party AbortControllers may not work with these. 49984 // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. 49985 try { 49986 // If the max amount of listeners is equal to the default, increase it 49987 // This is only available in node >= v19.9.0 49988 if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { 49989 setMaxListeners(100, signal) 49990 } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { 49991 setMaxListeners(100, signal) 49992 } 49993 } catch {} 49994 49995 util.addAbortListener(signal, abort) 49996 requestFinalizer.register(ac, { signal, abort }) 49997 } 49998 } 49999 50000 // 30. Set this’s headers to a new Headers object with this’s relevant 50001 // Realm, whose header list is request’s header list and guard is 50002 // "request". 50003 this[kHeaders] = new Headers(kConstruct) 50004 this[kHeaders][kHeadersList] = request.headersList 50005 this[kHeaders][kGuard] = 'request' 50006 this[kHeaders][kRealm] = this[kRealm] 50007 50008 // 31. If this’s request’s mode is "no-cors", then: 50009 if (mode === 'no-cors') { 50010 // 1. If this’s request’s method is not a CORS-safelisted method, 50011 // then throw a TypeError. 50012 if (!corsSafeListedMethodsSet.has(request.method)) { 50013 throw new TypeError( 50014 `'${request.method} is unsupported in no-cors mode.` 50015 ) 50016 } 50017 50018 // 2. Set this’s headers’s guard to "request-no-cors". 50019 this[kHeaders][kGuard] = 'request-no-cors' 50020 } 50021 50022 // 32. If init is not empty, then: 50023 if (initHasKey) { 50024 /** @type {HeadersList} */ 50025 const headersList = this[kHeaders][kHeadersList] 50026 // 1. Let headers be a copy of this’s headers and its associated header 50027 // list. 50028 // 2. If init["headers"] exists, then set headers to init["headers"]. 50029 const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) 50030 50031 // 3. Empty this’s headers’s header list. 50032 headersList.clear() 50033 50034 // 4. If headers is a Headers object, then for each header in its header 50035 // list, append header’s name/header’s value to this’s headers. 50036 if (headers instanceof HeadersList) { 50037 for (const [key, val] of headers) { 50038 headersList.append(key, val) 50039 } 50040 // Note: Copy the `set-cookie` meta-data. 50041 headersList.cookies = headers.cookies 50042 } else { 50043 // 5. Otherwise, fill this’s headers with headers. 50044 fillHeaders(this[kHeaders], headers) 50045 } 50046 } 50047 50048 // 33. Let inputBody be input’s request’s body if input is a Request 50049 // object; otherwise null. 50050 const inputBody = input instanceof Request ? input[kState].body : null 50051 50052 // 34. If either init["body"] exists and is non-null or inputBody is 50053 // non-null, and request’s method is `GET` or `HEAD`, then throw a 50054 // TypeError. 50055 if ( 50056 (init.body != null || inputBody != null) && 50057 (request.method === 'GET' || request.method === 'HEAD') 50058 ) { 50059 throw new TypeError('Request with GET/HEAD method cannot have body.') 50060 } 50061 50062 // 35. Let initBody be null. 50063 let initBody = null 50064 50065 // 36. If init["body"] exists and is non-null, then: 50066 if (init.body != null) { 50067 // 1. Let Content-Type be null. 50068 // 2. Set initBody and Content-Type to the result of extracting 50069 // init["body"], with keepalive set to request’s keepalive. 50070 const [extractedBody, contentType] = extractBody( 50071 init.body, 50072 request.keepalive 50073 ) 50074 initBody = extractedBody 50075 50076 // 3, If Content-Type is non-null and this’s headers’s header list does 50077 // not contain `Content-Type`, then append `Content-Type`/Content-Type to 50078 // this’s headers. 50079 if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { 50080 this[kHeaders].append('content-type', contentType) 50081 } 50082 } 50083 50084 // 37. Let inputOrInitBody be initBody if it is non-null; otherwise 50085 // inputBody. 50086 const inputOrInitBody = initBody ?? inputBody 50087 50088 // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is 50089 // null, then: 50090 if (inputOrInitBody != null && inputOrInitBody.source == null) { 50091 // 1. If initBody is non-null and init["duplex"] does not exist, 50092 // then throw a TypeError. 50093 if (initBody != null && init.duplex == null) { 50094 throw new TypeError('RequestInit: duplex option is required when sending a body.') 50095 } 50096 50097 // 2. If this’s request’s mode is neither "same-origin" nor "cors", 50098 // then throw a TypeError. 50099 if (request.mode !== 'same-origin' && request.mode !== 'cors') { 50100 throw new TypeError( 50101 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' 50102 ) 50103 } 50104 50105 // 3. Set this’s request’s use-CORS-preflight flag. 50106 request.useCORSPreflightFlag = true 50107 } 50108 50109 // 39. Let finalBody be inputOrInitBody. 50110 let finalBody = inputOrInitBody 50111 50112 // 40. If initBody is null and inputBody is non-null, then: 50113 if (initBody == null && inputBody != null) { 50114 // 1. If input is unusable, then throw a TypeError. 50115 if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { 50116 throw new TypeError( 50117 'Cannot construct a Request with a Request object that has already been used.' 50118 ) 50119 } 50120 50121 // 2. Set finalBody to the result of creating a proxy for inputBody. 50122 if (!TransformStream) { 50123 TransformStream = (__nccwpck_require__(5356).TransformStream) 50124 } 50125 50126 // https://streams.spec.whatwg.org/#readablestream-create-a-proxy 50127 const identityTransform = new TransformStream() 50128 inputBody.stream.pipeThrough(identityTransform) 50129 finalBody = { 50130 source: inputBody.source, 50131 length: inputBody.length, 50132 stream: identityTransform.readable 50133 } 50134 } 50135 50136 // 41. Set this’s request’s body to finalBody. 50137 this[kState].body = finalBody 50138 } 50139 50140 // Returns request’s HTTP method, which is "GET" by default. 50141 get method () { 50142 webidl.brandCheck(this, Request) 50143 50144 // The method getter steps are to return this’s request’s method. 50145 return this[kState].method 50146 } 50147 50148 // Returns the URL of request as a string. 50149 get url () { 50150 webidl.brandCheck(this, Request) 50151 50152 // The url getter steps are to return this’s request’s URL, serialized. 50153 return URLSerializer(this[kState].url) 50154 } 50155 50156 // Returns a Headers object consisting of the headers associated with request. 50157 // Note that headers added in the network layer by the user agent will not 50158 // be accounted for in this object, e.g., the "Host" header. 50159 get headers () { 50160 webidl.brandCheck(this, Request) 50161 50162 // The headers getter steps are to return this’s headers. 50163 return this[kHeaders] 50164 } 50165 50166 // Returns the kind of resource requested by request, e.g., "document" 50167 // or "script". 50168 get destination () { 50169 webidl.brandCheck(this, Request) 50170 50171 // The destination getter are to return this’s request’s destination. 50172 return this[kState].destination 50173 } 50174 50175 // Returns the referrer of request. Its value can be a same-origin URL if 50176 // explicitly set in init, the empty string to indicate no referrer, and 50177 // "about:client" when defaulting to the global’s default. This is used 50178 // during fetching to determine the value of the `Referer` header of the 50179 // request being made. 50180 get referrer () { 50181 webidl.brandCheck(this, Request) 50182 50183 // 1. If this’s request’s referrer is "no-referrer", then return the 50184 // empty string. 50185 if (this[kState].referrer === 'no-referrer') { 50186 return '' 50187 } 50188 50189 // 2. If this’s request’s referrer is "client", then return 50190 // "about:client". 50191 if (this[kState].referrer === 'client') { 50192 return 'about:client' 50193 } 50194 50195 // Return this’s request’s referrer, serialized. 50196 return this[kState].referrer.toString() 50197 } 50198 50199 // Returns the referrer policy associated with request. 50200 // This is used during fetching to compute the value of the request’s 50201 // referrer. 50202 get referrerPolicy () { 50203 webidl.brandCheck(this, Request) 50204 50205 // The referrerPolicy getter steps are to return this’s request’s referrer policy. 50206 return this[kState].referrerPolicy 50207 } 50208 50209 // Returns the mode associated with request, which is a string indicating 50210 // whether the request will use CORS, or will be restricted to same-origin 50211 // URLs. 50212 get mode () { 50213 webidl.brandCheck(this, Request) 50214 50215 // The mode getter steps are to return this’s request’s mode. 50216 return this[kState].mode 50217 } 50218 50219 // Returns the credentials mode associated with request, 50220 // which is a string indicating whether credentials will be sent with the 50221 // request always, never, or only when sent to a same-origin URL. 50222 get credentials () { 50223 // The credentials getter steps are to return this’s request’s credentials mode. 50224 return this[kState].credentials 50225 } 50226 50227 // Returns the cache mode associated with request, 50228 // which is a string indicating how the request will 50229 // interact with the browser’s cache when fetching. 50230 get cache () { 50231 webidl.brandCheck(this, Request) 50232 50233 // The cache getter steps are to return this’s request’s cache mode. 50234 return this[kState].cache 50235 } 50236 50237 // Returns the redirect mode associated with request, 50238 // which is a string indicating how redirects for the 50239 // request will be handled during fetching. A request 50240 // will follow redirects by default. 50241 get redirect () { 50242 webidl.brandCheck(this, Request) 50243 50244 // The redirect getter steps are to return this’s request’s redirect mode. 50245 return this[kState].redirect 50246 } 50247 50248 // Returns request’s subresource integrity metadata, which is a 50249 // cryptographic hash of the resource being fetched. Its value 50250 // consists of multiple hashes separated by whitespace. [SRI] 50251 get integrity () { 50252 webidl.brandCheck(this, Request) 50253 50254 // The integrity getter steps are to return this’s request’s integrity 50255 // metadata. 50256 return this[kState].integrity 50257 } 50258 50259 // Returns a boolean indicating whether or not request can outlive the 50260 // global in which it was created. 50261 get keepalive () { 50262 webidl.brandCheck(this, Request) 50263 50264 // The keepalive getter steps are to return this’s request’s keepalive. 50265 return this[kState].keepalive 50266 } 50267 50268 // Returns a boolean indicating whether or not request is for a reload 50269 // navigation. 50270 get isReloadNavigation () { 50271 webidl.brandCheck(this, Request) 50272 50273 // The isReloadNavigation getter steps are to return true if this’s 50274 // request’s reload-navigation flag is set; otherwise false. 50275 return this[kState].reloadNavigation 50276 } 50277 50278 // Returns a boolean indicating whether or not request is for a history 50279 // navigation (a.k.a. back-foward navigation). 50280 get isHistoryNavigation () { 50281 webidl.brandCheck(this, Request) 50282 50283 // The isHistoryNavigation getter steps are to return true if this’s request’s 50284 // history-navigation flag is set; otherwise false. 50285 return this[kState].historyNavigation 50286 } 50287 50288 // Returns the signal associated with request, which is an AbortSignal 50289 // object indicating whether or not request has been aborted, and its 50290 // abort event handler. 50291 get signal () { 50292 webidl.brandCheck(this, Request) 50293 50294 // The signal getter steps are to return this’s signal. 50295 return this[kSignal] 50296 } 50297 50298 get body () { 50299 webidl.brandCheck(this, Request) 50300 50301 return this[kState].body ? this[kState].body.stream : null 50302 } 50303 50304 get bodyUsed () { 50305 webidl.brandCheck(this, Request) 50306 50307 return !!this[kState].body && util.isDisturbed(this[kState].body.stream) 50308 } 50309 50310 get duplex () { 50311 webidl.brandCheck(this, Request) 50312 50313 return 'half' 50314 } 50315 50316 // Returns a clone of request. 50317 clone () { 50318 webidl.brandCheck(this, Request) 50319 50320 // 1. If this is unusable, then throw a TypeError. 50321 if (this.bodyUsed || this.body?.locked) { 50322 throw new TypeError('unusable') 50323 } 50324 50325 // 2. Let clonedRequest be the result of cloning this’s request. 50326 const clonedRequest = cloneRequest(this[kState]) 50327 50328 // 3. Let clonedRequestObject be the result of creating a Request object, 50329 // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. 50330 const clonedRequestObject = new Request(kConstruct) 50331 clonedRequestObject[kState] = clonedRequest 50332 clonedRequestObject[kRealm] = this[kRealm] 50333 clonedRequestObject[kHeaders] = new Headers(kConstruct) 50334 clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList 50335 clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] 50336 clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] 50337 50338 // 4. Make clonedRequestObject’s signal follow this’s signal. 50339 const ac = new AbortController() 50340 if (this.signal.aborted) { 50341 ac.abort(this.signal.reason) 50342 } else { 50343 util.addAbortListener( 50344 this.signal, 50345 () => { 50346 ac.abort(this.signal.reason) 50347 } 50348 ) 50349 } 50350 clonedRequestObject[kSignal] = ac.signal 50351 50352 // 4. Return clonedRequestObject. 50353 return clonedRequestObject 50354 } 50355 } 50356 50357 mixinBody(Request) 50358 50359 function makeRequest (init) { 50360 // https://fetch.spec.whatwg.org/#requests 50361 const request = { 50362 method: 'GET', 50363 localURLsOnly: false, 50364 unsafeRequest: false, 50365 body: null, 50366 client: null, 50367 reservedClient: null, 50368 replacesClientId: '', 50369 window: 'client', 50370 keepalive: false, 50371 serviceWorkers: 'all', 50372 initiator: '', 50373 destination: '', 50374 priority: null, 50375 origin: 'client', 50376 policyContainer: 'client', 50377 referrer: 'client', 50378 referrerPolicy: '', 50379 mode: 'no-cors', 50380 useCORSPreflightFlag: false, 50381 credentials: 'same-origin', 50382 useCredentials: false, 50383 cache: 'default', 50384 redirect: 'follow', 50385 integrity: '', 50386 cryptoGraphicsNonceMetadata: '', 50387 parserMetadata: '', 50388 reloadNavigation: false, 50389 historyNavigation: false, 50390 userActivation: false, 50391 taintedOrigin: false, 50392 redirectCount: 0, 50393 responseTainting: 'basic', 50394 preventNoCacheCacheControlHeaderModification: false, 50395 done: false, 50396 timingAllowFailed: false, 50397 ...init, 50398 headersList: init.headersList 50399 ? new HeadersList(init.headersList) 50400 : new HeadersList() 50401 } 50402 request.url = request.urlList[0] 50403 return request 50404 } 50405 50406 // https://fetch.spec.whatwg.org/#concept-request-clone 50407 function cloneRequest (request) { 50408 // To clone a request request, run these steps: 50409 50410 // 1. Let newRequest be a copy of request, except for its body. 50411 const newRequest = makeRequest({ ...request, body: null }) 50412 50413 // 2. If request’s body is non-null, set newRequest’s body to the 50414 // result of cloning request’s body. 50415 if (request.body != null) { 50416 newRequest.body = cloneBody(request.body) 50417 } 50418 50419 // 3. Return newRequest. 50420 return newRequest 50421 } 50422 50423 Object.defineProperties(Request.prototype, { 50424 method: kEnumerableProperty, 50425 url: kEnumerableProperty, 50426 headers: kEnumerableProperty, 50427 redirect: kEnumerableProperty, 50428 clone: kEnumerableProperty, 50429 signal: kEnumerableProperty, 50430 duplex: kEnumerableProperty, 50431 destination: kEnumerableProperty, 50432 body: kEnumerableProperty, 50433 bodyUsed: kEnumerableProperty, 50434 isHistoryNavigation: kEnumerableProperty, 50435 isReloadNavigation: kEnumerableProperty, 50436 keepalive: kEnumerableProperty, 50437 integrity: kEnumerableProperty, 50438 cache: kEnumerableProperty, 50439 credentials: kEnumerableProperty, 50440 attribute: kEnumerableProperty, 50441 referrerPolicy: kEnumerableProperty, 50442 referrer: kEnumerableProperty, 50443 mode: kEnumerableProperty, 50444 [Symbol.toStringTag]: { 50445 value: 'Request', 50446 configurable: true 50447 } 50448 }) 50449 50450 webidl.converters.Request = webidl.interfaceConverter( 50451 Request 50452 ) 50453 50454 // https://fetch.spec.whatwg.org/#requestinfo 50455 webidl.converters.RequestInfo = function (V) { 50456 if (typeof V === 'string') { 50457 return webidl.converters.USVString(V) 50458 } 50459 50460 if (V instanceof Request) { 50461 return webidl.converters.Request(V) 50462 } 50463 50464 return webidl.converters.USVString(V) 50465 } 50466 50467 webidl.converters.AbortSignal = webidl.interfaceConverter( 50468 AbortSignal 50469 ) 50470 50471 // https://fetch.spec.whatwg.org/#requestinit 50472 webidl.converters.RequestInit = webidl.dictionaryConverter([ 50473 { 50474 key: 'method', 50475 converter: webidl.converters.ByteString 50476 }, 50477 { 50478 key: 'headers', 50479 converter: webidl.converters.HeadersInit 50480 }, 50481 { 50482 key: 'body', 50483 converter: webidl.nullableConverter( 50484 webidl.converters.BodyInit 50485 ) 50486 }, 50487 { 50488 key: 'referrer', 50489 converter: webidl.converters.USVString 50490 }, 50491 { 50492 key: 'referrerPolicy', 50493 converter: webidl.converters.DOMString, 50494 // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy 50495 allowedValues: referrerPolicy 50496 }, 50497 { 50498 key: 'mode', 50499 converter: webidl.converters.DOMString, 50500 // https://fetch.spec.whatwg.org/#concept-request-mode 50501 allowedValues: requestMode 50502 }, 50503 { 50504 key: 'credentials', 50505 converter: webidl.converters.DOMString, 50506 // https://fetch.spec.whatwg.org/#requestcredentials 50507 allowedValues: requestCredentials 50508 }, 50509 { 50510 key: 'cache', 50511 converter: webidl.converters.DOMString, 50512 // https://fetch.spec.whatwg.org/#requestcache 50513 allowedValues: requestCache 50514 }, 50515 { 50516 key: 'redirect', 50517 converter: webidl.converters.DOMString, 50518 // https://fetch.spec.whatwg.org/#requestredirect 50519 allowedValues: requestRedirect 50520 }, 50521 { 50522 key: 'integrity', 50523 converter: webidl.converters.DOMString 50524 }, 50525 { 50526 key: 'keepalive', 50527 converter: webidl.converters.boolean 50528 }, 50529 { 50530 key: 'signal', 50531 converter: webidl.nullableConverter( 50532 (signal) => webidl.converters.AbortSignal( 50533 signal, 50534 { strict: false } 50535 ) 50536 ) 50537 }, 50538 { 50539 key: 'window', 50540 converter: webidl.converters.any 50541 }, 50542 { 50543 key: 'duplex', 50544 converter: webidl.converters.DOMString, 50545 allowedValues: requestDuplex 50546 } 50547 ]) 50548 50549 module.exports = { Request, makeRequest } 50550 50551 50552 /***/ }), 50553 50554 /***/ 7823: 50555 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 50556 50557 "use strict"; 50558 50559 50560 const { Headers, HeadersList, fill } = __nccwpck_require__(554) 50561 const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(1472) 50562 const util = __nccwpck_require__(3983) 50563 const { kEnumerableProperty } = util 50564 const { 50565 isValidReasonPhrase, 50566 isCancelled, 50567 isAborted, 50568 isBlobLike, 50569 serializeJavascriptValueToJSONString, 50570 isErrorLike, 50571 isomorphicEncode 50572 } = __nccwpck_require__(2538) 50573 const { 50574 redirectStatusSet, 50575 nullBodyStatus, 50576 DOMException 50577 } = __nccwpck_require__(1037) 50578 const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) 50579 const { webidl } = __nccwpck_require__(1744) 50580 const { FormData } = __nccwpck_require__(2015) 50581 const { getGlobalOrigin } = __nccwpck_require__(1246) 50582 const { URLSerializer } = __nccwpck_require__(685) 50583 const { kHeadersList, kConstruct } = __nccwpck_require__(2785) 50584 const assert = __nccwpck_require__(9491) 50585 const { types } = __nccwpck_require__(3837) 50586 50587 const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) 50588 const textEncoder = new TextEncoder('utf-8') 50589 50590 // https://fetch.spec.whatwg.org/#response-class 50591 class Response { 50592 // Creates network error Response. 50593 static error () { 50594 // TODO 50595 const relevantRealm = { settingsObject: {} } 50596 50597 // The static error() method steps are to return the result of creating a 50598 // Response object, given a new network error, "immutable", and this’s 50599 // relevant Realm. 50600 const responseObject = new Response() 50601 responseObject[kState] = makeNetworkError() 50602 responseObject[kRealm] = relevantRealm 50603 responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList 50604 responseObject[kHeaders][kGuard] = 'immutable' 50605 responseObject[kHeaders][kRealm] = relevantRealm 50606 return responseObject 50607 } 50608 50609 // https://fetch.spec.whatwg.org/#dom-response-json 50610 static json (data, init = {}) { 50611 webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) 50612 50613 if (init !== null) { 50614 init = webidl.converters.ResponseInit(init) 50615 } 50616 50617 // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. 50618 const bytes = textEncoder.encode( 50619 serializeJavascriptValueToJSONString(data) 50620 ) 50621 50622 // 2. Let body be the result of extracting bytes. 50623 const body = extractBody(bytes) 50624 50625 // 3. Let responseObject be the result of creating a Response object, given a new response, 50626 // "response", and this’s relevant Realm. 50627 const relevantRealm = { settingsObject: {} } 50628 const responseObject = new Response() 50629 responseObject[kRealm] = relevantRealm 50630 responseObject[kHeaders][kGuard] = 'response' 50631 responseObject[kHeaders][kRealm] = relevantRealm 50632 50633 // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). 50634 initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) 50635 50636 // 5. Return responseObject. 50637 return responseObject 50638 } 50639 50640 // Creates a redirect Response that redirects to url with status status. 50641 static redirect (url, status = 302) { 50642 const relevantRealm = { settingsObject: {} } 50643 50644 webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) 50645 50646 url = webidl.converters.USVString(url) 50647 status = webidl.converters['unsigned short'](status) 50648 50649 // 1. Let parsedURL be the result of parsing url with current settings 50650 // object’s API base URL. 50651 // 2. If parsedURL is failure, then throw a TypeError. 50652 // TODO: base-URL? 50653 let parsedURL 50654 try { 50655 parsedURL = new URL(url, getGlobalOrigin()) 50656 } catch (err) { 50657 throw Object.assign(new TypeError('Failed to parse URL from ' + url), { 50658 cause: err 50659 }) 50660 } 50661 50662 // 3. If status is not a redirect status, then throw a RangeError. 50663 if (!redirectStatusSet.has(status)) { 50664 throw new RangeError('Invalid status code ' + status) 50665 } 50666 50667 // 4. Let responseObject be the result of creating a Response object, 50668 // given a new response, "immutable", and this’s relevant Realm. 50669 const responseObject = new Response() 50670 responseObject[kRealm] = relevantRealm 50671 responseObject[kHeaders][kGuard] = 'immutable' 50672 responseObject[kHeaders][kRealm] = relevantRealm 50673 50674 // 5. Set responseObject’s response’s status to status. 50675 responseObject[kState].status = status 50676 50677 // 6. Let value be parsedURL, serialized and isomorphic encoded. 50678 const value = isomorphicEncode(URLSerializer(parsedURL)) 50679 50680 // 7. Append `Location`/value to responseObject’s response’s header list. 50681 responseObject[kState].headersList.append('location', value) 50682 50683 // 8. Return responseObject. 50684 return responseObject 50685 } 50686 50687 // https://fetch.spec.whatwg.org/#dom-response 50688 constructor (body = null, init = {}) { 50689 if (body !== null) { 50690 body = webidl.converters.BodyInit(body) 50691 } 50692 50693 init = webidl.converters.ResponseInit(init) 50694 50695 // TODO 50696 this[kRealm] = { settingsObject: {} } 50697 50698 // 1. Set this’s response to a new response. 50699 this[kState] = makeResponse({}) 50700 50701 // 2. Set this’s headers to a new Headers object with this’s relevant 50702 // Realm, whose header list is this’s response’s header list and guard 50703 // is "response". 50704 this[kHeaders] = new Headers(kConstruct) 50705 this[kHeaders][kGuard] = 'response' 50706 this[kHeaders][kHeadersList] = this[kState].headersList 50707 this[kHeaders][kRealm] = this[kRealm] 50708 50709 // 3. Let bodyWithType be null. 50710 let bodyWithType = null 50711 50712 // 4. If body is non-null, then set bodyWithType to the result of extracting body. 50713 if (body != null) { 50714 const [extractedBody, type] = extractBody(body) 50715 bodyWithType = { body: extractedBody, type } 50716 } 50717 50718 // 5. Perform initialize a response given this, init, and bodyWithType. 50719 initializeResponse(this, init, bodyWithType) 50720 } 50721 50722 // Returns response’s type, e.g., "cors". 50723 get type () { 50724 webidl.brandCheck(this, Response) 50725 50726 // The type getter steps are to return this’s response’s type. 50727 return this[kState].type 50728 } 50729 50730 // Returns response’s URL, if it has one; otherwise the empty string. 50731 get url () { 50732 webidl.brandCheck(this, Response) 50733 50734 const urlList = this[kState].urlList 50735 50736 // The url getter steps are to return the empty string if this’s 50737 // response’s URL is null; otherwise this’s response’s URL, 50738 // serialized with exclude fragment set to true. 50739 const url = urlList[urlList.length - 1] ?? null 50740 50741 if (url === null) { 50742 return '' 50743 } 50744 50745 return URLSerializer(url, true) 50746 } 50747 50748 // Returns whether response was obtained through a redirect. 50749 get redirected () { 50750 webidl.brandCheck(this, Response) 50751 50752 // The redirected getter steps are to return true if this’s response’s URL 50753 // list has more than one item; otherwise false. 50754 return this[kState].urlList.length > 1 50755 } 50756 50757 // Returns response’s status. 50758 get status () { 50759 webidl.brandCheck(this, Response) 50760 50761 // The status getter steps are to return this’s response’s status. 50762 return this[kState].status 50763 } 50764 50765 // Returns whether response’s status is an ok status. 50766 get ok () { 50767 webidl.brandCheck(this, Response) 50768 50769 // The ok getter steps are to return true if this’s response’s status is an 50770 // ok status; otherwise false. 50771 return this[kState].status >= 200 && this[kState].status <= 299 50772 } 50773 50774 // Returns response’s status message. 50775 get statusText () { 50776 webidl.brandCheck(this, Response) 50777 50778 // The statusText getter steps are to return this’s response’s status 50779 // message. 50780 return this[kState].statusText 50781 } 50782 50783 // Returns response’s headers as Headers. 50784 get headers () { 50785 webidl.brandCheck(this, Response) 50786 50787 // The headers getter steps are to return this’s headers. 50788 return this[kHeaders] 50789 } 50790 50791 get body () { 50792 webidl.brandCheck(this, Response) 50793 50794 return this[kState].body ? this[kState].body.stream : null 50795 } 50796 50797 get bodyUsed () { 50798 webidl.brandCheck(this, Response) 50799 50800 return !!this[kState].body && util.isDisturbed(this[kState].body.stream) 50801 } 50802 50803 // Returns a clone of response. 50804 clone () { 50805 webidl.brandCheck(this, Response) 50806 50807 // 1. If this is unusable, then throw a TypeError. 50808 if (this.bodyUsed || (this.body && this.body.locked)) { 50809 throw webidl.errors.exception({ 50810 header: 'Response.clone', 50811 message: 'Body has already been consumed.' 50812 }) 50813 } 50814 50815 // 2. Let clonedResponse be the result of cloning this’s response. 50816 const clonedResponse = cloneResponse(this[kState]) 50817 50818 // 3. Return the result of creating a Response object, given 50819 // clonedResponse, this’s headers’s guard, and this’s relevant Realm. 50820 const clonedResponseObject = new Response() 50821 clonedResponseObject[kState] = clonedResponse 50822 clonedResponseObject[kRealm] = this[kRealm] 50823 clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList 50824 clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] 50825 clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] 50826 50827 return clonedResponseObject 50828 } 50829 } 50830 50831 mixinBody(Response) 50832 50833 Object.defineProperties(Response.prototype, { 50834 type: kEnumerableProperty, 50835 url: kEnumerableProperty, 50836 status: kEnumerableProperty, 50837 ok: kEnumerableProperty, 50838 redirected: kEnumerableProperty, 50839 statusText: kEnumerableProperty, 50840 headers: kEnumerableProperty, 50841 clone: kEnumerableProperty, 50842 body: kEnumerableProperty, 50843 bodyUsed: kEnumerableProperty, 50844 [Symbol.toStringTag]: { 50845 value: 'Response', 50846 configurable: true 50847 } 50848 }) 50849 50850 Object.defineProperties(Response, { 50851 json: kEnumerableProperty, 50852 redirect: kEnumerableProperty, 50853 error: kEnumerableProperty 50854 }) 50855 50856 // https://fetch.spec.whatwg.org/#concept-response-clone 50857 function cloneResponse (response) { 50858 // To clone a response response, run these steps: 50859 50860 // 1. If response is a filtered response, then return a new identical 50861 // filtered response whose internal response is a clone of response’s 50862 // internal response. 50863 if (response.internalResponse) { 50864 return filterResponse( 50865 cloneResponse(response.internalResponse), 50866 response.type 50867 ) 50868 } 50869 50870 // 2. Let newResponse be a copy of response, except for its body. 50871 const newResponse = makeResponse({ ...response, body: null }) 50872 50873 // 3. If response’s body is non-null, then set newResponse’s body to the 50874 // result of cloning response’s body. 50875 if (response.body != null) { 50876 newResponse.body = cloneBody(response.body) 50877 } 50878 50879 // 4. Return newResponse. 50880 return newResponse 50881 } 50882 50883 function makeResponse (init) { 50884 return { 50885 aborted: false, 50886 rangeRequested: false, 50887 timingAllowPassed: false, 50888 requestIncludesCredentials: false, 50889 type: 'default', 50890 status: 200, 50891 timingInfo: null, 50892 cacheState: '', 50893 statusText: '', 50894 ...init, 50895 headersList: init.headersList 50896 ? new HeadersList(init.headersList) 50897 : new HeadersList(), 50898 urlList: init.urlList ? [...init.urlList] : [] 50899 } 50900 } 50901 50902 function makeNetworkError (reason) { 50903 const isError = isErrorLike(reason) 50904 return makeResponse({ 50905 type: 'error', 50906 status: 0, 50907 error: isError 50908 ? reason 50909 : new Error(reason ? String(reason) : reason), 50910 aborted: reason && reason.name === 'AbortError' 50911 }) 50912 } 50913 50914 function makeFilteredResponse (response, state) { 50915 state = { 50916 internalResponse: response, 50917 ...state 50918 } 50919 50920 return new Proxy(response, { 50921 get (target, p) { 50922 return p in state ? state[p] : target[p] 50923 }, 50924 set (target, p, value) { 50925 assert(!(p in state)) 50926 target[p] = value 50927 return true 50928 } 50929 }) 50930 } 50931 50932 // https://fetch.spec.whatwg.org/#concept-filtered-response 50933 function filterResponse (response, type) { 50934 // Set response to the following filtered response with response as its 50935 // internal response, depending on request’s response tainting: 50936 if (type === 'basic') { 50937 // A basic filtered response is a filtered response whose type is "basic" 50938 // and header list excludes any headers in internal response’s header list 50939 // whose name is a forbidden response-header name. 50940 50941 // Note: undici does not implement forbidden response-header names 50942 return makeFilteredResponse(response, { 50943 type: 'basic', 50944 headersList: response.headersList 50945 }) 50946 } else if (type === 'cors') { 50947 // A CORS filtered response is a filtered response whose type is "cors" 50948 // and header list excludes any headers in internal response’s header 50949 // list whose name is not a CORS-safelisted response-header name, given 50950 // internal response’s CORS-exposed header-name list. 50951 50952 // Note: undici does not implement CORS-safelisted response-header names 50953 return makeFilteredResponse(response, { 50954 type: 'cors', 50955 headersList: response.headersList 50956 }) 50957 } else if (type === 'opaque') { 50958 // An opaque filtered response is a filtered response whose type is 50959 // "opaque", URL list is the empty list, status is 0, status message 50960 // is the empty byte sequence, header list is empty, and body is null. 50961 50962 return makeFilteredResponse(response, { 50963 type: 'opaque', 50964 urlList: Object.freeze([]), 50965 status: 0, 50966 statusText: '', 50967 body: null 50968 }) 50969 } else if (type === 'opaqueredirect') { 50970 // An opaque-redirect filtered response is a filtered response whose type 50971 // is "opaqueredirect", status is 0, status message is the empty byte 50972 // sequence, header list is empty, and body is null. 50973 50974 return makeFilteredResponse(response, { 50975 type: 'opaqueredirect', 50976 status: 0, 50977 statusText: '', 50978 headersList: [], 50979 body: null 50980 }) 50981 } else { 50982 assert(false) 50983 } 50984 } 50985 50986 // https://fetch.spec.whatwg.org/#appropriate-network-error 50987 function makeAppropriateNetworkError (fetchParams, err = null) { 50988 // 1. Assert: fetchParams is canceled. 50989 assert(isCancelled(fetchParams)) 50990 50991 // 2. Return an aborted network error if fetchParams is aborted; 50992 // otherwise return a network error. 50993 return isAborted(fetchParams) 50994 ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) 50995 : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) 50996 } 50997 50998 // https://whatpr.org/fetch/1392.html#initialize-a-response 50999 function initializeResponse (response, init, body) { 51000 // 1. If init["status"] is not in the range 200 to 599, inclusive, then 51001 // throw a RangeError. 51002 if (init.status !== null && (init.status < 200 || init.status > 599)) { 51003 throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') 51004 } 51005 51006 // 2. If init["statusText"] does not match the reason-phrase token production, 51007 // then throw a TypeError. 51008 if ('statusText' in init && init.statusText != null) { 51009 // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: 51010 // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) 51011 if (!isValidReasonPhrase(String(init.statusText))) { 51012 throw new TypeError('Invalid statusText') 51013 } 51014 } 51015 51016 // 3. Set response’s response’s status to init["status"]. 51017 if ('status' in init && init.status != null) { 51018 response[kState].status = init.status 51019 } 51020 51021 // 4. Set response’s response’s status message to init["statusText"]. 51022 if ('statusText' in init && init.statusText != null) { 51023 response[kState].statusText = init.statusText 51024 } 51025 51026 // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. 51027 if ('headers' in init && init.headers != null) { 51028 fill(response[kHeaders], init.headers) 51029 } 51030 51031 // 6. If body was given, then: 51032 if (body) { 51033 // 1. If response's status is a null body status, then throw a TypeError. 51034 if (nullBodyStatus.includes(response.status)) { 51035 throw webidl.errors.exception({ 51036 header: 'Response constructor', 51037 message: 'Invalid response status code ' + response.status 51038 }) 51039 } 51040 51041 // 2. Set response's body to body's body. 51042 response[kState].body = body.body 51043 51044 // 3. If body's type is non-null and response's header list does not contain 51045 // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. 51046 if (body.type != null && !response[kState].headersList.contains('Content-Type')) { 51047 response[kState].headersList.append('content-type', body.type) 51048 } 51049 } 51050 } 51051 51052 webidl.converters.ReadableStream = webidl.interfaceConverter( 51053 ReadableStream 51054 ) 51055 51056 webidl.converters.FormData = webidl.interfaceConverter( 51057 FormData 51058 ) 51059 51060 webidl.converters.URLSearchParams = webidl.interfaceConverter( 51061 URLSearchParams 51062 ) 51063 51064 // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit 51065 webidl.converters.XMLHttpRequestBodyInit = function (V) { 51066 if (typeof V === 'string') { 51067 return webidl.converters.USVString(V) 51068 } 51069 51070 if (isBlobLike(V)) { 51071 return webidl.converters.Blob(V, { strict: false }) 51072 } 51073 51074 if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { 51075 return webidl.converters.BufferSource(V) 51076 } 51077 51078 if (util.isFormDataLike(V)) { 51079 return webidl.converters.FormData(V, { strict: false }) 51080 } 51081 51082 if (V instanceof URLSearchParams) { 51083 return webidl.converters.URLSearchParams(V) 51084 } 51085 51086 return webidl.converters.DOMString(V) 51087 } 51088 51089 // https://fetch.spec.whatwg.org/#bodyinit 51090 webidl.converters.BodyInit = function (V) { 51091 if (V instanceof ReadableStream) { 51092 return webidl.converters.ReadableStream(V) 51093 } 51094 51095 // Note: the spec doesn't include async iterables, 51096 // this is an undici extension. 51097 if (V?.[Symbol.asyncIterator]) { 51098 return V 51099 } 51100 51101 return webidl.converters.XMLHttpRequestBodyInit(V) 51102 } 51103 51104 webidl.converters.ResponseInit = webidl.dictionaryConverter([ 51105 { 51106 key: 'status', 51107 converter: webidl.converters['unsigned short'], 51108 defaultValue: 200 51109 }, 51110 { 51111 key: 'statusText', 51112 converter: webidl.converters.ByteString, 51113 defaultValue: '' 51114 }, 51115 { 51116 key: 'headers', 51117 converter: webidl.converters.HeadersInit 51118 } 51119 ]) 51120 51121 module.exports = { 51122 makeNetworkError, 51123 makeResponse, 51124 makeAppropriateNetworkError, 51125 filterResponse, 51126 Response, 51127 cloneResponse 51128 } 51129 51130 51131 /***/ }), 51132 51133 /***/ 5861: 51134 /***/ ((module) => { 51135 51136 "use strict"; 51137 51138 51139 module.exports = { 51140 kUrl: Symbol('url'), 51141 kHeaders: Symbol('headers'), 51142 kSignal: Symbol('signal'), 51143 kState: Symbol('state'), 51144 kGuard: Symbol('guard'), 51145 kRealm: Symbol('realm') 51146 } 51147 51148 51149 /***/ }), 51150 51151 /***/ 2538: 51152 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 51153 51154 "use strict"; 51155 51156 51157 const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1037) 51158 const { getGlobalOrigin } = __nccwpck_require__(1246) 51159 const { performance } = __nccwpck_require__(4074) 51160 const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983) 51161 const assert = __nccwpck_require__(9491) 51162 const { isUint8Array } = __nccwpck_require__(9830) 51163 51164 let supportedHashes = [] 51165 51166 // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable 51167 /** @type {import('crypto')|undefined} */ 51168 let crypto 51169 51170 try { 51171 crypto = __nccwpck_require__(6113) 51172 const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] 51173 supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) 51174 /* c8 ignore next 3 */ 51175 } catch { 51176 } 51177 51178 function responseURL (response) { 51179 // https://fetch.spec.whatwg.org/#responses 51180 // A response has an associated URL. It is a pointer to the last URL 51181 // in response’s URL list and null if response’s URL list is empty. 51182 const urlList = response.urlList 51183 const length = urlList.length 51184 return length === 0 ? null : urlList[length - 1].toString() 51185 } 51186 51187 // https://fetch.spec.whatwg.org/#concept-response-location-url 51188 function responseLocationURL (response, requestFragment) { 51189 // 1. If response’s status is not a redirect status, then return null. 51190 if (!redirectStatusSet.has(response.status)) { 51191 return null 51192 } 51193 51194 // 2. Let location be the result of extracting header list values given 51195 // `Location` and response’s header list. 51196 let location = response.headersList.get('location') 51197 51198 // 3. If location is a header value, then set location to the result of 51199 // parsing location with response’s URL. 51200 if (location !== null && isValidHeaderValue(location)) { 51201 location = new URL(location, responseURL(response)) 51202 } 51203 51204 // 4. If location is a URL whose fragment is null, then set location’s 51205 // fragment to requestFragment. 51206 if (location && !location.hash) { 51207 location.hash = requestFragment 51208 } 51209 51210 // 5. Return location. 51211 return location 51212 } 51213 51214 /** @returns {URL} */ 51215 function requestCurrentURL (request) { 51216 return request.urlList[request.urlList.length - 1] 51217 } 51218 51219 function requestBadPort (request) { 51220 // 1. Let url be request’s current URL. 51221 const url = requestCurrentURL(request) 51222 51223 // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, 51224 // then return blocked. 51225 if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { 51226 return 'blocked' 51227 } 51228 51229 // 3. Return allowed. 51230 return 'allowed' 51231 } 51232 51233 function isErrorLike (object) { 51234 return object instanceof Error || ( 51235 object?.constructor?.name === 'Error' || 51236 object?.constructor?.name === 'DOMException' 51237 ) 51238 } 51239 51240 // Check whether |statusText| is a ByteString and 51241 // matches the Reason-Phrase token production. 51242 // RFC 2616: https://tools.ietf.org/html/rfc2616 51243 // RFC 7230: https://tools.ietf.org/html/rfc7230 51244 // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" 51245 // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 51246 function isValidReasonPhrase (statusText) { 51247 for (let i = 0; i < statusText.length; ++i) { 51248 const c = statusText.charCodeAt(i) 51249 if ( 51250 !( 51251 ( 51252 c === 0x09 || // HTAB 51253 (c >= 0x20 && c <= 0x7e) || // SP / VCHAR 51254 (c >= 0x80 && c <= 0xff) 51255 ) // obs-text 51256 ) 51257 ) { 51258 return false 51259 } 51260 } 51261 return true 51262 } 51263 51264 /** 51265 * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 51266 * @param {number} c 51267 */ 51268 function isTokenCharCode (c) { 51269 switch (c) { 51270 case 0x22: 51271 case 0x28: 51272 case 0x29: 51273 case 0x2c: 51274 case 0x2f: 51275 case 0x3a: 51276 case 0x3b: 51277 case 0x3c: 51278 case 0x3d: 51279 case 0x3e: 51280 case 0x3f: 51281 case 0x40: 51282 case 0x5b: 51283 case 0x5c: 51284 case 0x5d: 51285 case 0x7b: 51286 case 0x7d: 51287 // DQUOTE and "(),/:;<=>?@[\]{}" 51288 return false 51289 default: 51290 // VCHAR %x21-7E 51291 return c >= 0x21 && c <= 0x7e 51292 } 51293 } 51294 51295 /** 51296 * @param {string} characters 51297 */ 51298 function isValidHTTPToken (characters) { 51299 if (characters.length === 0) { 51300 return false 51301 } 51302 for (let i = 0; i < characters.length; ++i) { 51303 if (!isTokenCharCode(characters.charCodeAt(i))) { 51304 return false 51305 } 51306 } 51307 return true 51308 } 51309 51310 /** 51311 * @see https://fetch.spec.whatwg.org/#header-name 51312 * @param {string} potentialValue 51313 */ 51314 function isValidHeaderName (potentialValue) { 51315 return isValidHTTPToken(potentialValue) 51316 } 51317 51318 /** 51319 * @see https://fetch.spec.whatwg.org/#header-value 51320 * @param {string} potentialValue 51321 */ 51322 function isValidHeaderValue (potentialValue) { 51323 // - Has no leading or trailing HTTP tab or space bytes. 51324 // - Contains no 0x00 (NUL) or HTTP newline bytes. 51325 if ( 51326 potentialValue.startsWith('\t') || 51327 potentialValue.startsWith(' ') || 51328 potentialValue.endsWith('\t') || 51329 potentialValue.endsWith(' ') 51330 ) { 51331 return false 51332 } 51333 51334 if ( 51335 potentialValue.includes('\0') || 51336 potentialValue.includes('\r') || 51337 potentialValue.includes('\n') 51338 ) { 51339 return false 51340 } 51341 51342 return true 51343 } 51344 51345 // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect 51346 function setRequestReferrerPolicyOnRedirect (request, actualResponse) { 51347 // Given a request request and a response actualResponse, this algorithm 51348 // updates request’s referrer policy according to the Referrer-Policy 51349 // header (if any) in actualResponse. 51350 51351 // 1. Let policy be the result of executing § 8.1 Parse a referrer policy 51352 // from a Referrer-Policy header on actualResponse. 51353 51354 // 8.1 Parse a referrer policy from a Referrer-Policy header 51355 // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. 51356 const { headersList } = actualResponse 51357 // 2. Let policy be the empty string. 51358 // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. 51359 // 4. Return policy. 51360 const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') 51361 51362 // Note: As the referrer-policy can contain multiple policies 51363 // separated by comma, we need to loop through all of them 51364 // and pick the first valid one. 51365 // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy 51366 let policy = '' 51367 if (policyHeader.length > 0) { 51368 // The right-most policy takes precedence. 51369 // The left-most policy is the fallback. 51370 for (let i = policyHeader.length; i !== 0; i--) { 51371 const token = policyHeader[i - 1].trim() 51372 if (referrerPolicyTokens.has(token)) { 51373 policy = token 51374 break 51375 } 51376 } 51377 } 51378 51379 // 2. If policy is not the empty string, then set request’s referrer policy to policy. 51380 if (policy !== '') { 51381 request.referrerPolicy = policy 51382 } 51383 } 51384 51385 // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check 51386 function crossOriginResourcePolicyCheck () { 51387 // TODO 51388 return 'allowed' 51389 } 51390 51391 // https://fetch.spec.whatwg.org/#concept-cors-check 51392 function corsCheck () { 51393 // TODO 51394 return 'success' 51395 } 51396 51397 // https://fetch.spec.whatwg.org/#concept-tao-check 51398 function TAOCheck () { 51399 // TODO 51400 return 'success' 51401 } 51402 51403 function appendFetchMetadata (httpRequest) { 51404 // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header 51405 // TODO 51406 51407 // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header 51408 51409 // 1. Assert: r’s url is a potentially trustworthy URL. 51410 // TODO 51411 51412 // 2. Let header be a Structured Header whose value is a token. 51413 let header = null 51414 51415 // 3. Set header’s value to r’s mode. 51416 header = httpRequest.mode 51417 51418 // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. 51419 httpRequest.headersList.set('sec-fetch-mode', header) 51420 51421 // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header 51422 // TODO 51423 51424 // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header 51425 // TODO 51426 } 51427 51428 // https://fetch.spec.whatwg.org/#append-a-request-origin-header 51429 function appendRequestOriginHeader (request) { 51430 // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. 51431 let serializedOrigin = request.origin 51432 51433 // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. 51434 if (request.responseTainting === 'cors' || request.mode === 'websocket') { 51435 if (serializedOrigin) { 51436 request.headersList.append('origin', serializedOrigin) 51437 } 51438 51439 // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: 51440 } else if (request.method !== 'GET' && request.method !== 'HEAD') { 51441 // 1. Switch on request’s referrer policy: 51442 switch (request.referrerPolicy) { 51443 case 'no-referrer': 51444 // Set serializedOrigin to `null`. 51445 serializedOrigin = null 51446 break 51447 case 'no-referrer-when-downgrade': 51448 case 'strict-origin': 51449 case 'strict-origin-when-cross-origin': 51450 // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. 51451 if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { 51452 serializedOrigin = null 51453 } 51454 break 51455 case 'same-origin': 51456 // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. 51457 if (!sameOrigin(request, requestCurrentURL(request))) { 51458 serializedOrigin = null 51459 } 51460 break 51461 default: 51462 // Do nothing. 51463 } 51464 51465 if (serializedOrigin) { 51466 // 2. Append (`Origin`, serializedOrigin) to request’s header list. 51467 request.headersList.append('origin', serializedOrigin) 51468 } 51469 } 51470 } 51471 51472 function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { 51473 // TODO 51474 return performance.now() 51475 } 51476 51477 // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info 51478 function createOpaqueTimingInfo (timingInfo) { 51479 return { 51480 startTime: timingInfo.startTime ?? 0, 51481 redirectStartTime: 0, 51482 redirectEndTime: 0, 51483 postRedirectStartTime: timingInfo.startTime ?? 0, 51484 finalServiceWorkerStartTime: 0, 51485 finalNetworkResponseStartTime: 0, 51486 finalNetworkRequestStartTime: 0, 51487 endTime: 0, 51488 encodedBodySize: 0, 51489 decodedBodySize: 0, 51490 finalConnectionTimingInfo: null 51491 } 51492 } 51493 51494 // https://html.spec.whatwg.org/multipage/origin.html#policy-container 51495 function makePolicyContainer () { 51496 // Note: the fetch spec doesn't make use of embedder policy or CSP list 51497 return { 51498 referrerPolicy: 'strict-origin-when-cross-origin' 51499 } 51500 } 51501 51502 // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container 51503 function clonePolicyContainer (policyContainer) { 51504 return { 51505 referrerPolicy: policyContainer.referrerPolicy 51506 } 51507 } 51508 51509 // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer 51510 function determineRequestsReferrer (request) { 51511 // 1. Let policy be request's referrer policy. 51512 const policy = request.referrerPolicy 51513 51514 // Note: policy cannot (shouldn't) be null or an empty string. 51515 assert(policy) 51516 51517 // 2. Let environment be request’s client. 51518 51519 let referrerSource = null 51520 51521 // 3. Switch on request’s referrer: 51522 if (request.referrer === 'client') { 51523 // Note: node isn't a browser and doesn't implement document/iframes, 51524 // so we bypass this step and replace it with our own. 51525 51526 const globalOrigin = getGlobalOrigin() 51527 51528 if (!globalOrigin || globalOrigin.origin === 'null') { 51529 return 'no-referrer' 51530 } 51531 51532 // note: we need to clone it as it's mutated 51533 referrerSource = new URL(globalOrigin) 51534 } else if (request.referrer instanceof URL) { 51535 // Let referrerSource be request’s referrer. 51536 referrerSource = request.referrer 51537 } 51538 51539 // 4. Let request’s referrerURL be the result of stripping referrerSource for 51540 // use as a referrer. 51541 let referrerURL = stripURLForReferrer(referrerSource) 51542 51543 // 5. Let referrerOrigin be the result of stripping referrerSource for use as 51544 // a referrer, with the origin-only flag set to true. 51545 const referrerOrigin = stripURLForReferrer(referrerSource, true) 51546 51547 // 6. If the result of serializing referrerURL is a string whose length is 51548 // greater than 4096, set referrerURL to referrerOrigin. 51549 if (referrerURL.toString().length > 4096) { 51550 referrerURL = referrerOrigin 51551 } 51552 51553 const areSameOrigin = sameOrigin(request, referrerURL) 51554 const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && 51555 !isURLPotentiallyTrustworthy(request.url) 51556 51557 // 8. Execute the switch statements corresponding to the value of policy: 51558 switch (policy) { 51559 case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) 51560 case 'unsafe-url': return referrerURL 51561 case 'same-origin': 51562 return areSameOrigin ? referrerOrigin : 'no-referrer' 51563 case 'origin-when-cross-origin': 51564 return areSameOrigin ? referrerURL : referrerOrigin 51565 case 'strict-origin-when-cross-origin': { 51566 const currentURL = requestCurrentURL(request) 51567 51568 // 1. If the origin of referrerURL and the origin of request’s current 51569 // URL are the same, then return referrerURL. 51570 if (sameOrigin(referrerURL, currentURL)) { 51571 return referrerURL 51572 } 51573 51574 // 2. If referrerURL is a potentially trustworthy URL and request’s 51575 // current URL is not a potentially trustworthy URL, then return no 51576 // referrer. 51577 if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { 51578 return 'no-referrer' 51579 } 51580 51581 // 3. Return referrerOrigin. 51582 return referrerOrigin 51583 } 51584 case 'strict-origin': // eslint-disable-line 51585 /** 51586 * 1. If referrerURL is a potentially trustworthy URL and 51587 * request’s current URL is not a potentially trustworthy URL, 51588 * then return no referrer. 51589 * 2. Return referrerOrigin 51590 */ 51591 case 'no-referrer-when-downgrade': // eslint-disable-line 51592 /** 51593 * 1. If referrerURL is a potentially trustworthy URL and 51594 * request’s current URL is not a potentially trustworthy URL, 51595 * then return no referrer. 51596 * 2. Return referrerOrigin 51597 */ 51598 51599 default: // eslint-disable-line 51600 return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin 51601 } 51602 } 51603 51604 /** 51605 * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url 51606 * @param {URL} url 51607 * @param {boolean|undefined} originOnly 51608 */ 51609 function stripURLForReferrer (url, originOnly) { 51610 // 1. Assert: url is a URL. 51611 assert(url instanceof URL) 51612 51613 // 2. If url’s scheme is a local scheme, then return no referrer. 51614 if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { 51615 return 'no-referrer' 51616 } 51617 51618 // 3. Set url’s username to the empty string. 51619 url.username = '' 51620 51621 // 4. Set url’s password to the empty string. 51622 url.password = '' 51623 51624 // 5. Set url’s fragment to null. 51625 url.hash = '' 51626 51627 // 6. If the origin-only flag is true, then: 51628 if (originOnly) { 51629 // 1. Set url’s path to « the empty string ». 51630 url.pathname = '' 51631 51632 // 2. Set url’s query to null. 51633 url.search = '' 51634 } 51635 51636 // 7. Return url. 51637 return url 51638 } 51639 51640 function isURLPotentiallyTrustworthy (url) { 51641 if (!(url instanceof URL)) { 51642 return false 51643 } 51644 51645 // If child of about, return true 51646 if (url.href === 'about:blank' || url.href === 'about:srcdoc') { 51647 return true 51648 } 51649 51650 // If scheme is data, return true 51651 if (url.protocol === 'data:') return true 51652 51653 // If file, return true 51654 if (url.protocol === 'file:') return true 51655 51656 return isOriginPotentiallyTrustworthy(url.origin) 51657 51658 function isOriginPotentiallyTrustworthy (origin) { 51659 // If origin is explicitly null, return false 51660 if (origin == null || origin === 'null') return false 51661 51662 const originAsURL = new URL(origin) 51663 51664 // If secure, return true 51665 if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { 51666 return true 51667 } 51668 51669 // If localhost or variants, return true 51670 if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || 51671 (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || 51672 (originAsURL.hostname.endsWith('.localhost'))) { 51673 return true 51674 } 51675 51676 // If any other, return false 51677 return false 51678 } 51679 } 51680 51681 /** 51682 * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist 51683 * @param {Uint8Array} bytes 51684 * @param {string} metadataList 51685 */ 51686 function bytesMatch (bytes, metadataList) { 51687 // If node is not built with OpenSSL support, we cannot check 51688 // a request's integrity, so allow it by default (the spec will 51689 // allow requests if an invalid hash is given, as precedence). 51690 /* istanbul ignore if: only if node is built with --without-ssl */ 51691 if (crypto === undefined) { 51692 return true 51693 } 51694 51695 // 1. Let parsedMetadata be the result of parsing metadataList. 51696 const parsedMetadata = parseMetadata(metadataList) 51697 51698 // 2. If parsedMetadata is no metadata, return true. 51699 if (parsedMetadata === 'no metadata') { 51700 return true 51701 } 51702 51703 // 3. If response is not eligible for integrity validation, return false. 51704 // TODO 51705 51706 // 4. If parsedMetadata is the empty set, return true. 51707 if (parsedMetadata.length === 0) { 51708 return true 51709 } 51710 51711 // 5. Let metadata be the result of getting the strongest 51712 // metadata from parsedMetadata. 51713 const strongest = getStrongestMetadata(parsedMetadata) 51714 const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) 51715 51716 // 6. For each item in metadata: 51717 for (const item of metadata) { 51718 // 1. Let algorithm be the alg component of item. 51719 const algorithm = item.algo 51720 51721 // 2. Let expectedValue be the val component of item. 51722 const expectedValue = item.hash 51723 51724 // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e 51725 // "be liberal with padding". This is annoying, and it's not even in the spec. 51726 51727 // 3. Let actualValue be the result of applying algorithm to bytes. 51728 let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') 51729 51730 if (actualValue[actualValue.length - 1] === '=') { 51731 if (actualValue[actualValue.length - 2] === '=') { 51732 actualValue = actualValue.slice(0, -2) 51733 } else { 51734 actualValue = actualValue.slice(0, -1) 51735 } 51736 } 51737 51738 // 4. If actualValue is a case-sensitive match for expectedValue, 51739 // return true. 51740 if (compareBase64Mixed(actualValue, expectedValue)) { 51741 return true 51742 } 51743 } 51744 51745 // 7. Return false. 51746 return false 51747 } 51748 51749 // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options 51750 // https://www.w3.org/TR/CSP2/#source-list-syntax 51751 // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 51752 const parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i 51753 51754 /** 51755 * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata 51756 * @param {string} metadata 51757 */ 51758 function parseMetadata (metadata) { 51759 // 1. Let result be the empty set. 51760 /** @type {{ algo: string, hash: string }[]} */ 51761 const result = [] 51762 51763 // 2. Let empty be equal to true. 51764 let empty = true 51765 51766 // 3. For each token returned by splitting metadata on spaces: 51767 for (const token of metadata.split(' ')) { 51768 // 1. Set empty to false. 51769 empty = false 51770 51771 // 2. Parse token as a hash-with-options. 51772 const parsedToken = parseHashWithOptions.exec(token) 51773 51774 // 3. If token does not parse, continue to the next token. 51775 if ( 51776 parsedToken === null || 51777 parsedToken.groups === undefined || 51778 parsedToken.groups.algo === undefined 51779 ) { 51780 // Note: Chromium blocks the request at this point, but Firefox 51781 // gives a warning that an invalid integrity was given. The 51782 // correct behavior is to ignore these, and subsequently not 51783 // check the integrity of the resource. 51784 continue 51785 } 51786 51787 // 4. Let algorithm be the hash-algo component of token. 51788 const algorithm = parsedToken.groups.algo.toLowerCase() 51789 51790 // 5. If algorithm is a hash function recognized by the user 51791 // agent, add the parsed token to result. 51792 if (supportedHashes.includes(algorithm)) { 51793 result.push(parsedToken.groups) 51794 } 51795 } 51796 51797 // 4. Return no metadata if empty is true, otherwise return result. 51798 if (empty === true) { 51799 return 'no metadata' 51800 } 51801 51802 return result 51803 } 51804 51805 /** 51806 * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList 51807 */ 51808 function getStrongestMetadata (metadataList) { 51809 // Let algorithm be the algo component of the first item in metadataList. 51810 // Can be sha256 51811 let algorithm = metadataList[0].algo 51812 // If the algorithm is sha512, then it is the strongest 51813 // and we can return immediately 51814 if (algorithm[3] === '5') { 51815 return algorithm 51816 } 51817 51818 for (let i = 1; i < metadataList.length; ++i) { 51819 const metadata = metadataList[i] 51820 // If the algorithm is sha512, then it is the strongest 51821 // and we can break the loop immediately 51822 if (metadata.algo[3] === '5') { 51823 algorithm = 'sha512' 51824 break 51825 // If the algorithm is sha384, then a potential sha256 or sha384 is ignored 51826 } else if (algorithm[3] === '3') { 51827 continue 51828 // algorithm is sha256, check if algorithm is sha384 and if so, set it as 51829 // the strongest 51830 } else if (metadata.algo[3] === '3') { 51831 algorithm = 'sha384' 51832 } 51833 } 51834 return algorithm 51835 } 51836 51837 function filterMetadataListByAlgorithm (metadataList, algorithm) { 51838 if (metadataList.length === 1) { 51839 return metadataList 51840 } 51841 51842 let pos = 0 51843 for (let i = 0; i < metadataList.length; ++i) { 51844 if (metadataList[i].algo === algorithm) { 51845 metadataList[pos++] = metadataList[i] 51846 } 51847 } 51848 51849 metadataList.length = pos 51850 51851 return metadataList 51852 } 51853 51854 /** 51855 * Compares two base64 strings, allowing for base64url 51856 * in the second string. 51857 * 51858 * @param {string} actualValue always base64 51859 * @param {string} expectedValue base64 or base64url 51860 * @returns {boolean} 51861 */ 51862 function compareBase64Mixed (actualValue, expectedValue) { 51863 if (actualValue.length !== expectedValue.length) { 51864 return false 51865 } 51866 for (let i = 0; i < actualValue.length; ++i) { 51867 if (actualValue[i] !== expectedValue[i]) { 51868 if ( 51869 (actualValue[i] === '+' && expectedValue[i] === '-') || 51870 (actualValue[i] === '/' && expectedValue[i] === '_') 51871 ) { 51872 continue 51873 } 51874 return false 51875 } 51876 } 51877 51878 return true 51879 } 51880 51881 // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request 51882 function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { 51883 // TODO 51884 } 51885 51886 /** 51887 * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} 51888 * @param {URL} A 51889 * @param {URL} B 51890 */ 51891 function sameOrigin (A, B) { 51892 // 1. If A and B are the same opaque origin, then return true. 51893 if (A.origin === B.origin && A.origin === 'null') { 51894 return true 51895 } 51896 51897 // 2. If A and B are both tuple origins and their schemes, 51898 // hosts, and port are identical, then return true. 51899 if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { 51900 return true 51901 } 51902 51903 // 3. Return false. 51904 return false 51905 } 51906 51907 function createDeferredPromise () { 51908 let res 51909 let rej 51910 const promise = new Promise((resolve, reject) => { 51911 res = resolve 51912 rej = reject 51913 }) 51914 51915 return { promise, resolve: res, reject: rej } 51916 } 51917 51918 function isAborted (fetchParams) { 51919 return fetchParams.controller.state === 'aborted' 51920 } 51921 51922 function isCancelled (fetchParams) { 51923 return fetchParams.controller.state === 'aborted' || 51924 fetchParams.controller.state === 'terminated' 51925 } 51926 51927 const normalizeMethodRecord = { 51928 delete: 'DELETE', 51929 DELETE: 'DELETE', 51930 get: 'GET', 51931 GET: 'GET', 51932 head: 'HEAD', 51933 HEAD: 'HEAD', 51934 options: 'OPTIONS', 51935 OPTIONS: 'OPTIONS', 51936 post: 'POST', 51937 POST: 'POST', 51938 put: 'PUT', 51939 PUT: 'PUT' 51940 } 51941 51942 // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. 51943 Object.setPrototypeOf(normalizeMethodRecord, null) 51944 51945 /** 51946 * @see https://fetch.spec.whatwg.org/#concept-method-normalize 51947 * @param {string} method 51948 */ 51949 function normalizeMethod (method) { 51950 return normalizeMethodRecord[method.toLowerCase()] ?? method 51951 } 51952 51953 // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string 51954 function serializeJavascriptValueToJSONString (value) { 51955 // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). 51956 const result = JSON.stringify(value) 51957 51958 // 2. If result is undefined, then throw a TypeError. 51959 if (result === undefined) { 51960 throw new TypeError('Value is not JSON serializable') 51961 } 51962 51963 // 3. Assert: result is a string. 51964 assert(typeof result === 'string') 51965 51966 // 4. Return result. 51967 return result 51968 } 51969 51970 // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object 51971 const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) 51972 51973 /** 51974 * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object 51975 * @param {() => unknown[]} iterator 51976 * @param {string} name name of the instance 51977 * @param {'key'|'value'|'key+value'} kind 51978 */ 51979 function makeIterator (iterator, name, kind) { 51980 const object = { 51981 index: 0, 51982 kind, 51983 target: iterator 51984 } 51985 51986 const i = { 51987 next () { 51988 // 1. Let interface be the interface for which the iterator prototype object exists. 51989 51990 // 2. Let thisValue be the this value. 51991 51992 // 3. Let object be ? ToObject(thisValue). 51993 51994 // 4. If object is a platform object, then perform a security 51995 // check, passing: 51996 51997 // 5. If object is not a default iterator object for interface, 51998 // then throw a TypeError. 51999 if (Object.getPrototypeOf(this) !== i) { 52000 throw new TypeError( 52001 `'next' called on an object that does not implement interface ${name} Iterator.` 52002 ) 52003 } 52004 52005 // 6. Let index be object’s index. 52006 // 7. Let kind be object’s kind. 52007 // 8. Let values be object’s target's value pairs to iterate over. 52008 const { index, kind, target } = object 52009 const values = target() 52010 52011 // 9. Let len be the length of values. 52012 const len = values.length 52013 52014 // 10. If index is greater than or equal to len, then return 52015 // CreateIterResultObject(undefined, true). 52016 if (index >= len) { 52017 return { value: undefined, done: true } 52018 } 52019 52020 // 11. Let pair be the entry in values at index index. 52021 const pair = values[index] 52022 52023 // 12. Set object’s index to index + 1. 52024 object.index = index + 1 52025 52026 // 13. Return the iterator result for pair and kind. 52027 return iteratorResult(pair, kind) 52028 }, 52029 // The class string of an iterator prototype object for a given interface is the 52030 // result of concatenating the identifier of the interface and the string " Iterator". 52031 [Symbol.toStringTag]: `${name} Iterator` 52032 } 52033 52034 // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. 52035 Object.setPrototypeOf(i, esIteratorPrototype) 52036 // esIteratorPrototype needs to be the prototype of i 52037 // which is the prototype of an empty object. Yes, it's confusing. 52038 return Object.setPrototypeOf({}, i) 52039 } 52040 52041 // https://webidl.spec.whatwg.org/#iterator-result 52042 function iteratorResult (pair, kind) { 52043 let result 52044 52045 // 1. Let result be a value determined by the value of kind: 52046 switch (kind) { 52047 case 'key': { 52048 // 1. Let idlKey be pair’s key. 52049 // 2. Let key be the result of converting idlKey to an 52050 // ECMAScript value. 52051 // 3. result is key. 52052 result = pair[0] 52053 break 52054 } 52055 case 'value': { 52056 // 1. Let idlValue be pair’s value. 52057 // 2. Let value be the result of converting idlValue to 52058 // an ECMAScript value. 52059 // 3. result is value. 52060 result = pair[1] 52061 break 52062 } 52063 case 'key+value': { 52064 // 1. Let idlKey be pair’s key. 52065 // 2. Let idlValue be pair’s value. 52066 // 3. Let key be the result of converting idlKey to an 52067 // ECMAScript value. 52068 // 4. Let value be the result of converting idlValue to 52069 // an ECMAScript value. 52070 // 5. Let array be ! ArrayCreate(2). 52071 // 6. Call ! CreateDataProperty(array, "0", key). 52072 // 7. Call ! CreateDataProperty(array, "1", value). 52073 // 8. result is array. 52074 result = pair 52075 break 52076 } 52077 } 52078 52079 // 2. Return CreateIterResultObject(result, false). 52080 return { value: result, done: false } 52081 } 52082 52083 /** 52084 * @see https://fetch.spec.whatwg.org/#body-fully-read 52085 */ 52086 async function fullyReadBody (body, processBody, processBodyError) { 52087 // 1. If taskDestination is null, then set taskDestination to 52088 // the result of starting a new parallel queue. 52089 52090 // 2. Let successSteps given a byte sequence bytes be to queue a 52091 // fetch task to run processBody given bytes, with taskDestination. 52092 const successSteps = processBody 52093 52094 // 3. Let errorSteps be to queue a fetch task to run processBodyError, 52095 // with taskDestination. 52096 const errorSteps = processBodyError 52097 52098 // 4. Let reader be the result of getting a reader for body’s stream. 52099 // If that threw an exception, then run errorSteps with that 52100 // exception and return. 52101 let reader 52102 52103 try { 52104 reader = body.stream.getReader() 52105 } catch (e) { 52106 errorSteps(e) 52107 return 52108 } 52109 52110 // 5. Read all bytes from reader, given successSteps and errorSteps. 52111 try { 52112 const result = await readAllBytes(reader) 52113 successSteps(result) 52114 } catch (e) { 52115 errorSteps(e) 52116 } 52117 } 52118 52119 /** @type {ReadableStream} */ 52120 let ReadableStream = globalThis.ReadableStream 52121 52122 function isReadableStreamLike (stream) { 52123 if (!ReadableStream) { 52124 ReadableStream = (__nccwpck_require__(5356).ReadableStream) 52125 } 52126 52127 return stream instanceof ReadableStream || ( 52128 stream[Symbol.toStringTag] === 'ReadableStream' && 52129 typeof stream.tee === 'function' 52130 ) 52131 } 52132 52133 const MAXIMUM_ARGUMENT_LENGTH = 65535 52134 52135 /** 52136 * @see https://infra.spec.whatwg.org/#isomorphic-decode 52137 * @param {number[]|Uint8Array} input 52138 */ 52139 function isomorphicDecode (input) { 52140 // 1. To isomorphic decode a byte sequence input, return a string whose code point 52141 // length is equal to input’s length and whose code points have the same values 52142 // as the values of input’s bytes, in the same order. 52143 52144 if (input.length < MAXIMUM_ARGUMENT_LENGTH) { 52145 return String.fromCharCode(...input) 52146 } 52147 52148 return input.reduce((previous, current) => previous + String.fromCharCode(current), '') 52149 } 52150 52151 /** 52152 * @param {ReadableStreamController<Uint8Array>} controller 52153 */ 52154 function readableStreamClose (controller) { 52155 try { 52156 controller.close() 52157 } catch (err) { 52158 // TODO: add comment explaining why this error occurs. 52159 if (!err.message.includes('Controller is already closed')) { 52160 throw err 52161 } 52162 } 52163 } 52164 52165 /** 52166 * @see https://infra.spec.whatwg.org/#isomorphic-encode 52167 * @param {string} input 52168 */ 52169 function isomorphicEncode (input) { 52170 // 1. Assert: input contains no code points greater than U+00FF. 52171 for (let i = 0; i < input.length; i++) { 52172 assert(input.charCodeAt(i) <= 0xFF) 52173 } 52174 52175 // 2. Return a byte sequence whose length is equal to input’s code 52176 // point length and whose bytes have the same values as the 52177 // values of input’s code points, in the same order 52178 return input 52179 } 52180 52181 /** 52182 * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes 52183 * @see https://streams.spec.whatwg.org/#read-loop 52184 * @param {ReadableStreamDefaultReader} reader 52185 */ 52186 async function readAllBytes (reader) { 52187 const bytes = [] 52188 let byteLength = 0 52189 52190 while (true) { 52191 const { done, value: chunk } = await reader.read() 52192 52193 if (done) { 52194 // 1. Call successSteps with bytes. 52195 return Buffer.concat(bytes, byteLength) 52196 } 52197 52198 // 1. If chunk is not a Uint8Array object, call failureSteps 52199 // with a TypeError and abort these steps. 52200 if (!isUint8Array(chunk)) { 52201 throw new TypeError('Received non-Uint8Array chunk') 52202 } 52203 52204 // 2. Append the bytes represented by chunk to bytes. 52205 bytes.push(chunk) 52206 byteLength += chunk.length 52207 52208 // 3. Read-loop given reader, bytes, successSteps, and failureSteps. 52209 } 52210 } 52211 52212 /** 52213 * @see https://fetch.spec.whatwg.org/#is-local 52214 * @param {URL} url 52215 */ 52216 function urlIsLocal (url) { 52217 assert('protocol' in url) // ensure it's a url object 52218 52219 const protocol = url.protocol 52220 52221 return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' 52222 } 52223 52224 /** 52225 * @param {string|URL} url 52226 */ 52227 function urlHasHttpsScheme (url) { 52228 if (typeof url === 'string') { 52229 return url.startsWith('https:') 52230 } 52231 52232 return url.protocol === 'https:' 52233 } 52234 52235 /** 52236 * @see https://fetch.spec.whatwg.org/#http-scheme 52237 * @param {URL} url 52238 */ 52239 function urlIsHttpHttpsScheme (url) { 52240 assert('protocol' in url) // ensure it's a url object 52241 52242 const protocol = url.protocol 52243 52244 return protocol === 'http:' || protocol === 'https:' 52245 } 52246 52247 /** 52248 * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. 52249 */ 52250 const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) 52251 52252 module.exports = { 52253 isAborted, 52254 isCancelled, 52255 createDeferredPromise, 52256 ReadableStreamFrom, 52257 toUSVString, 52258 tryUpgradeRequestToAPotentiallyTrustworthyURL, 52259 coarsenedSharedCurrentTime, 52260 determineRequestsReferrer, 52261 makePolicyContainer, 52262 clonePolicyContainer, 52263 appendFetchMetadata, 52264 appendRequestOriginHeader, 52265 TAOCheck, 52266 corsCheck, 52267 crossOriginResourcePolicyCheck, 52268 createOpaqueTimingInfo, 52269 setRequestReferrerPolicyOnRedirect, 52270 isValidHTTPToken, 52271 requestBadPort, 52272 requestCurrentURL, 52273 responseURL, 52274 responseLocationURL, 52275 isBlobLike, 52276 isURLPotentiallyTrustworthy, 52277 isValidReasonPhrase, 52278 sameOrigin, 52279 normalizeMethod, 52280 serializeJavascriptValueToJSONString, 52281 makeIterator, 52282 isValidHeaderName, 52283 isValidHeaderValue, 52284 hasOwn, 52285 isErrorLike, 52286 fullyReadBody, 52287 bytesMatch, 52288 isReadableStreamLike, 52289 readableStreamClose, 52290 isomorphicEncode, 52291 isomorphicDecode, 52292 urlIsLocal, 52293 urlHasHttpsScheme, 52294 urlIsHttpHttpsScheme, 52295 readAllBytes, 52296 normalizeMethodRecord, 52297 parseMetadata 52298 } 52299 52300 52301 /***/ }), 52302 52303 /***/ 1744: 52304 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 52305 52306 "use strict"; 52307 52308 52309 const { types } = __nccwpck_require__(3837) 52310 const { hasOwn, toUSVString } = __nccwpck_require__(2538) 52311 52312 /** @type {import('../../types/webidl').Webidl} */ 52313 const webidl = {} 52314 webidl.converters = {} 52315 webidl.util = {} 52316 webidl.errors = {} 52317 52318 webidl.errors.exception = function (message) { 52319 return new TypeError(`${message.header}: ${message.message}`) 52320 } 52321 52322 webidl.errors.conversionFailed = function (context) { 52323 const plural = context.types.length === 1 ? '' : ' one of' 52324 const message = 52325 `${context.argument} could not be converted to` + 52326 `${plural}: ${context.types.join(', ')}.` 52327 52328 return webidl.errors.exception({ 52329 header: context.prefix, 52330 message 52331 }) 52332 } 52333 52334 webidl.errors.invalidArgument = function (context) { 52335 return webidl.errors.exception({ 52336 header: context.prefix, 52337 message: `"${context.value}" is an invalid ${context.type}.` 52338 }) 52339 } 52340 52341 // https://webidl.spec.whatwg.org/#implements 52342 webidl.brandCheck = function (V, I, opts = undefined) { 52343 if (opts?.strict !== false && !(V instanceof I)) { 52344 throw new TypeError('Illegal invocation') 52345 } else { 52346 return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] 52347 } 52348 } 52349 52350 webidl.argumentLengthCheck = function ({ length }, min, ctx) { 52351 if (length < min) { 52352 throw webidl.errors.exception({ 52353 message: `${min} argument${min !== 1 ? 's' : ''} required, ` + 52354 `but${length ? ' only' : ''} ${length} found.`, 52355 ...ctx 52356 }) 52357 } 52358 } 52359 52360 webidl.illegalConstructor = function () { 52361 throw webidl.errors.exception({ 52362 header: 'TypeError', 52363 message: 'Illegal constructor' 52364 }) 52365 } 52366 52367 // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values 52368 webidl.util.Type = function (V) { 52369 switch (typeof V) { 52370 case 'undefined': return 'Undefined' 52371 case 'boolean': return 'Boolean' 52372 case 'string': return 'String' 52373 case 'symbol': return 'Symbol' 52374 case 'number': return 'Number' 52375 case 'bigint': return 'BigInt' 52376 case 'function': 52377 case 'object': { 52378 if (V === null) { 52379 return 'Null' 52380 } 52381 52382 return 'Object' 52383 } 52384 } 52385 } 52386 52387 // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint 52388 webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { 52389 let upperBound 52390 let lowerBound 52391 52392 // 1. If bitLength is 64, then: 52393 if (bitLength === 64) { 52394 // 1. Let upperBound be 2^53 − 1. 52395 upperBound = Math.pow(2, 53) - 1 52396 52397 // 2. If signedness is "unsigned", then let lowerBound be 0. 52398 if (signedness === 'unsigned') { 52399 lowerBound = 0 52400 } else { 52401 // 3. Otherwise let lowerBound be −2^53 + 1. 52402 lowerBound = Math.pow(-2, 53) + 1 52403 } 52404 } else if (signedness === 'unsigned') { 52405 // 2. Otherwise, if signedness is "unsigned", then: 52406 52407 // 1. Let lowerBound be 0. 52408 lowerBound = 0 52409 52410 // 2. Let upperBound be 2^bitLength − 1. 52411 upperBound = Math.pow(2, bitLength) - 1 52412 } else { 52413 // 3. Otherwise: 52414 52415 // 1. Let lowerBound be -2^bitLength − 1. 52416 lowerBound = Math.pow(-2, bitLength) - 1 52417 52418 // 2. Let upperBound be 2^bitLength − 1 − 1. 52419 upperBound = Math.pow(2, bitLength - 1) - 1 52420 } 52421 52422 // 4. Let x be ? ToNumber(V). 52423 let x = Number(V) 52424 52425 // 5. If x is −0, then set x to +0. 52426 if (x === 0) { 52427 x = 0 52428 } 52429 52430 // 6. If the conversion is to an IDL type associated 52431 // with the [EnforceRange] extended attribute, then: 52432 if (opts.enforceRange === true) { 52433 // 1. If x is NaN, +∞, or −∞, then throw a TypeError. 52434 if ( 52435 Number.isNaN(x) || 52436 x === Number.POSITIVE_INFINITY || 52437 x === Number.NEGATIVE_INFINITY 52438 ) { 52439 throw webidl.errors.exception({ 52440 header: 'Integer conversion', 52441 message: `Could not convert ${V} to an integer.` 52442 }) 52443 } 52444 52445 // 2. Set x to IntegerPart(x). 52446 x = webidl.util.IntegerPart(x) 52447 52448 // 3. If x < lowerBound or x > upperBound, then 52449 // throw a TypeError. 52450 if (x < lowerBound || x > upperBound) { 52451 throw webidl.errors.exception({ 52452 header: 'Integer conversion', 52453 message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` 52454 }) 52455 } 52456 52457 // 4. Return x. 52458 return x 52459 } 52460 52461 // 7. If x is not NaN and the conversion is to an IDL 52462 // type associated with the [Clamp] extended 52463 // attribute, then: 52464 if (!Number.isNaN(x) && opts.clamp === true) { 52465 // 1. Set x to min(max(x, lowerBound), upperBound). 52466 x = Math.min(Math.max(x, lowerBound), upperBound) 52467 52468 // 2. Round x to the nearest integer, choosing the 52469 // even integer if it lies halfway between two, 52470 // and choosing +0 rather than −0. 52471 if (Math.floor(x) % 2 === 0) { 52472 x = Math.floor(x) 52473 } else { 52474 x = Math.ceil(x) 52475 } 52476 52477 // 3. Return x. 52478 return x 52479 } 52480 52481 // 8. If x is NaN, +0, +∞, or −∞, then return +0. 52482 if ( 52483 Number.isNaN(x) || 52484 (x === 0 && Object.is(0, x)) || 52485 x === Number.POSITIVE_INFINITY || 52486 x === Number.NEGATIVE_INFINITY 52487 ) { 52488 return 0 52489 } 52490 52491 // 9. Set x to IntegerPart(x). 52492 x = webidl.util.IntegerPart(x) 52493 52494 // 10. Set x to x modulo 2^bitLength. 52495 x = x % Math.pow(2, bitLength) 52496 52497 // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, 52498 // then return x − 2^bitLength. 52499 if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { 52500 return x - Math.pow(2, bitLength) 52501 } 52502 52503 // 12. Otherwise, return x. 52504 return x 52505 } 52506 52507 // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart 52508 webidl.util.IntegerPart = function (n) { 52509 // 1. Let r be floor(abs(n)). 52510 const r = Math.floor(Math.abs(n)) 52511 52512 // 2. If n < 0, then return -1 × r. 52513 if (n < 0) { 52514 return -1 * r 52515 } 52516 52517 // 3. Otherwise, return r. 52518 return r 52519 } 52520 52521 // https://webidl.spec.whatwg.org/#es-sequence 52522 webidl.sequenceConverter = function (converter) { 52523 return (V) => { 52524 // 1. If Type(V) is not Object, throw a TypeError. 52525 if (webidl.util.Type(V) !== 'Object') { 52526 throw webidl.errors.exception({ 52527 header: 'Sequence', 52528 message: `Value of type ${webidl.util.Type(V)} is not an Object.` 52529 }) 52530 } 52531 52532 // 2. Let method be ? GetMethod(V, @@iterator). 52533 /** @type {Generator} */ 52534 const method = V?.[Symbol.iterator]?.() 52535 const seq = [] 52536 52537 // 3. If method is undefined, throw a TypeError. 52538 if ( 52539 method === undefined || 52540 typeof method.next !== 'function' 52541 ) { 52542 throw webidl.errors.exception({ 52543 header: 'Sequence', 52544 message: 'Object is not an iterator.' 52545 }) 52546 } 52547 52548 // https://webidl.spec.whatwg.org/#create-sequence-from-iterable 52549 while (true) { 52550 const { done, value } = method.next() 52551 52552 if (done) { 52553 break 52554 } 52555 52556 seq.push(converter(value)) 52557 } 52558 52559 return seq 52560 } 52561 } 52562 52563 // https://webidl.spec.whatwg.org/#es-to-record 52564 webidl.recordConverter = function (keyConverter, valueConverter) { 52565 return (O) => { 52566 // 1. If Type(O) is not Object, throw a TypeError. 52567 if (webidl.util.Type(O) !== 'Object') { 52568 throw webidl.errors.exception({ 52569 header: 'Record', 52570 message: `Value of type ${webidl.util.Type(O)} is not an Object.` 52571 }) 52572 } 52573 52574 // 2. Let result be a new empty instance of record<K, V>. 52575 const result = {} 52576 52577 if (!types.isProxy(O)) { 52578 // Object.keys only returns enumerable properties 52579 const keys = Object.keys(O) 52580 52581 for (const key of keys) { 52582 // 1. Let typedKey be key converted to an IDL value of type K. 52583 const typedKey = keyConverter(key) 52584 52585 // 2. Let value be ? Get(O, key). 52586 // 3. Let typedValue be value converted to an IDL value of type V. 52587 const typedValue = valueConverter(O[key]) 52588 52589 // 4. Set result[typedKey] to typedValue. 52590 result[typedKey] = typedValue 52591 } 52592 52593 // 5. Return result. 52594 return result 52595 } 52596 52597 // 3. Let keys be ? O.[[OwnPropertyKeys]](). 52598 const keys = Reflect.ownKeys(O) 52599 52600 // 4. For each key of keys. 52601 for (const key of keys) { 52602 // 1. Let desc be ? O.[[GetOwnProperty]](key). 52603 const desc = Reflect.getOwnPropertyDescriptor(O, key) 52604 52605 // 2. If desc is not undefined and desc.[[Enumerable]] is true: 52606 if (desc?.enumerable) { 52607 // 1. Let typedKey be key converted to an IDL value of type K. 52608 const typedKey = keyConverter(key) 52609 52610 // 2. Let value be ? Get(O, key). 52611 // 3. Let typedValue be value converted to an IDL value of type V. 52612 const typedValue = valueConverter(O[key]) 52613 52614 // 4. Set result[typedKey] to typedValue. 52615 result[typedKey] = typedValue 52616 } 52617 } 52618 52619 // 5. Return result. 52620 return result 52621 } 52622 } 52623 52624 webidl.interfaceConverter = function (i) { 52625 return (V, opts = {}) => { 52626 if (opts.strict !== false && !(V instanceof i)) { 52627 throw webidl.errors.exception({ 52628 header: i.name, 52629 message: `Expected ${V} to be an instance of ${i.name}.` 52630 }) 52631 } 52632 52633 return V 52634 } 52635 } 52636 52637 webidl.dictionaryConverter = function (converters) { 52638 return (dictionary) => { 52639 const type = webidl.util.Type(dictionary) 52640 const dict = {} 52641 52642 if (type === 'Null' || type === 'Undefined') { 52643 return dict 52644 } else if (type !== 'Object') { 52645 throw webidl.errors.exception({ 52646 header: 'Dictionary', 52647 message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` 52648 }) 52649 } 52650 52651 for (const options of converters) { 52652 const { key, defaultValue, required, converter } = options 52653 52654 if (required === true) { 52655 if (!hasOwn(dictionary, key)) { 52656 throw webidl.errors.exception({ 52657 header: 'Dictionary', 52658 message: `Missing required key "${key}".` 52659 }) 52660 } 52661 } 52662 52663 let value = dictionary[key] 52664 const hasDefault = hasOwn(options, 'defaultValue') 52665 52666 // Only use defaultValue if value is undefined and 52667 // a defaultValue options was provided. 52668 if (hasDefault && value !== null) { 52669 value = value ?? defaultValue 52670 } 52671 52672 // A key can be optional and have no default value. 52673 // When this happens, do not perform a conversion, 52674 // and do not assign the key a value. 52675 if (required || hasDefault || value !== undefined) { 52676 value = converter(value) 52677 52678 if ( 52679 options.allowedValues && 52680 !options.allowedValues.includes(value) 52681 ) { 52682 throw webidl.errors.exception({ 52683 header: 'Dictionary', 52684 message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` 52685 }) 52686 } 52687 52688 dict[key] = value 52689 } 52690 } 52691 52692 return dict 52693 } 52694 } 52695 52696 webidl.nullableConverter = function (converter) { 52697 return (V) => { 52698 if (V === null) { 52699 return V 52700 } 52701 52702 return converter(V) 52703 } 52704 } 52705 52706 // https://webidl.spec.whatwg.org/#es-DOMString 52707 webidl.converters.DOMString = function (V, opts = {}) { 52708 // 1. If V is null and the conversion is to an IDL type 52709 // associated with the [LegacyNullToEmptyString] 52710 // extended attribute, then return the DOMString value 52711 // that represents the empty string. 52712 if (V === null && opts.legacyNullToEmptyString) { 52713 return '' 52714 } 52715 52716 // 2. Let x be ? ToString(V). 52717 if (typeof V === 'symbol') { 52718 throw new TypeError('Could not convert argument of type symbol to string.') 52719 } 52720 52721 // 3. Return the IDL DOMString value that represents the 52722 // same sequence of code units as the one the 52723 // ECMAScript String value x represents. 52724 return String(V) 52725 } 52726 52727 // https://webidl.spec.whatwg.org/#es-ByteString 52728 webidl.converters.ByteString = function (V) { 52729 // 1. Let x be ? ToString(V). 52730 // Note: DOMString converter perform ? ToString(V) 52731 const x = webidl.converters.DOMString(V) 52732 52733 // 2. If the value of any element of x is greater than 52734 // 255, then throw a TypeError. 52735 for (let index = 0; index < x.length; index++) { 52736 if (x.charCodeAt(index) > 255) { 52737 throw new TypeError( 52738 'Cannot convert argument to a ByteString because the character at ' + 52739 `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` 52740 ) 52741 } 52742 } 52743 52744 // 3. Return an IDL ByteString value whose length is the 52745 // length of x, and where the value of each element is 52746 // the value of the corresponding element of x. 52747 return x 52748 } 52749 52750 // https://webidl.spec.whatwg.org/#es-USVString 52751 webidl.converters.USVString = toUSVString 52752 52753 // https://webidl.spec.whatwg.org/#es-boolean 52754 webidl.converters.boolean = function (V) { 52755 // 1. Let x be the result of computing ToBoolean(V). 52756 const x = Boolean(V) 52757 52758 // 2. Return the IDL boolean value that is the one that represents 52759 // the same truth value as the ECMAScript Boolean value x. 52760 return x 52761 } 52762 52763 // https://webidl.spec.whatwg.org/#es-any 52764 webidl.converters.any = function (V) { 52765 return V 52766 } 52767 52768 // https://webidl.spec.whatwg.org/#es-long-long 52769 webidl.converters['long long'] = function (V) { 52770 // 1. Let x be ? ConvertToInt(V, 64, "signed"). 52771 const x = webidl.util.ConvertToInt(V, 64, 'signed') 52772 52773 // 2. Return the IDL long long value that represents 52774 // the same numeric value as x. 52775 return x 52776 } 52777 52778 // https://webidl.spec.whatwg.org/#es-unsigned-long-long 52779 webidl.converters['unsigned long long'] = function (V) { 52780 // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). 52781 const x = webidl.util.ConvertToInt(V, 64, 'unsigned') 52782 52783 // 2. Return the IDL unsigned long long value that 52784 // represents the same numeric value as x. 52785 return x 52786 } 52787 52788 // https://webidl.spec.whatwg.org/#es-unsigned-long 52789 webidl.converters['unsigned long'] = function (V) { 52790 // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). 52791 const x = webidl.util.ConvertToInt(V, 32, 'unsigned') 52792 52793 // 2. Return the IDL unsigned long value that 52794 // represents the same numeric value as x. 52795 return x 52796 } 52797 52798 // https://webidl.spec.whatwg.org/#es-unsigned-short 52799 webidl.converters['unsigned short'] = function (V, opts) { 52800 // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). 52801 const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) 52802 52803 // 2. Return the IDL unsigned short value that represents 52804 // the same numeric value as x. 52805 return x 52806 } 52807 52808 // https://webidl.spec.whatwg.org/#idl-ArrayBuffer 52809 webidl.converters.ArrayBuffer = function (V, opts = {}) { 52810 // 1. If Type(V) is not Object, or V does not have an 52811 // [[ArrayBufferData]] internal slot, then throw a 52812 // TypeError. 52813 // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances 52814 // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances 52815 if ( 52816 webidl.util.Type(V) !== 'Object' || 52817 !types.isAnyArrayBuffer(V) 52818 ) { 52819 throw webidl.errors.conversionFailed({ 52820 prefix: `${V}`, 52821 argument: `${V}`, 52822 types: ['ArrayBuffer'] 52823 }) 52824 } 52825 52826 // 2. If the conversion is not to an IDL type associated 52827 // with the [AllowShared] extended attribute, and 52828 // IsSharedArrayBuffer(V) is true, then throw a 52829 // TypeError. 52830 if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { 52831 throw webidl.errors.exception({ 52832 header: 'ArrayBuffer', 52833 message: 'SharedArrayBuffer is not allowed.' 52834 }) 52835 } 52836 52837 // 3. If the conversion is not to an IDL type associated 52838 // with the [AllowResizable] extended attribute, and 52839 // IsResizableArrayBuffer(V) is true, then throw a 52840 // TypeError. 52841 // Note: resizable ArrayBuffers are currently a proposal. 52842 52843 // 4. Return the IDL ArrayBuffer value that is a 52844 // reference to the same object as V. 52845 return V 52846 } 52847 52848 webidl.converters.TypedArray = function (V, T, opts = {}) { 52849 // 1. Let T be the IDL type V is being converted to. 52850 52851 // 2. If Type(V) is not Object, or V does not have a 52852 // [[TypedArrayName]] internal slot with a value 52853 // equal to T’s name, then throw a TypeError. 52854 if ( 52855 webidl.util.Type(V) !== 'Object' || 52856 !types.isTypedArray(V) || 52857 V.constructor.name !== T.name 52858 ) { 52859 throw webidl.errors.conversionFailed({ 52860 prefix: `${T.name}`, 52861 argument: `${V}`, 52862 types: [T.name] 52863 }) 52864 } 52865 52866 // 3. If the conversion is not to an IDL type associated 52867 // with the [AllowShared] extended attribute, and 52868 // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is 52869 // true, then throw a TypeError. 52870 if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { 52871 throw webidl.errors.exception({ 52872 header: 'ArrayBuffer', 52873 message: 'SharedArrayBuffer is not allowed.' 52874 }) 52875 } 52876 52877 // 4. If the conversion is not to an IDL type associated 52878 // with the [AllowResizable] extended attribute, and 52879 // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is 52880 // true, then throw a TypeError. 52881 // Note: resizable array buffers are currently a proposal 52882 52883 // 5. Return the IDL value of type T that is a reference 52884 // to the same object as V. 52885 return V 52886 } 52887 52888 webidl.converters.DataView = function (V, opts = {}) { 52889 // 1. If Type(V) is not Object, or V does not have a 52890 // [[DataView]] internal slot, then throw a TypeError. 52891 if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { 52892 throw webidl.errors.exception({ 52893 header: 'DataView', 52894 message: 'Object is not a DataView.' 52895 }) 52896 } 52897 52898 // 2. If the conversion is not to an IDL type associated 52899 // with the [AllowShared] extended attribute, and 52900 // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, 52901 // then throw a TypeError. 52902 if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { 52903 throw webidl.errors.exception({ 52904 header: 'ArrayBuffer', 52905 message: 'SharedArrayBuffer is not allowed.' 52906 }) 52907 } 52908 52909 // 3. If the conversion is not to an IDL type associated 52910 // with the [AllowResizable] extended attribute, and 52911 // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is 52912 // true, then throw a TypeError. 52913 // Note: resizable ArrayBuffers are currently a proposal 52914 52915 // 4. Return the IDL DataView value that is a reference 52916 // to the same object as V. 52917 return V 52918 } 52919 52920 // https://webidl.spec.whatwg.org/#BufferSource 52921 webidl.converters.BufferSource = function (V, opts = {}) { 52922 if (types.isAnyArrayBuffer(V)) { 52923 return webidl.converters.ArrayBuffer(V, opts) 52924 } 52925 52926 if (types.isTypedArray(V)) { 52927 return webidl.converters.TypedArray(V, V.constructor) 52928 } 52929 52930 if (types.isDataView(V)) { 52931 return webidl.converters.DataView(V, opts) 52932 } 52933 52934 throw new TypeError(`Could not convert ${V} to a BufferSource.`) 52935 } 52936 52937 webidl.converters['sequence<ByteString>'] = webidl.sequenceConverter( 52938 webidl.converters.ByteString 52939 ) 52940 52941 webidl.converters['sequence<sequence<ByteString>>'] = webidl.sequenceConverter( 52942 webidl.converters['sequence<ByteString>'] 52943 ) 52944 52945 webidl.converters['record<ByteString, ByteString>'] = webidl.recordConverter( 52946 webidl.converters.ByteString, 52947 webidl.converters.ByteString 52948 ) 52949 52950 module.exports = { 52951 webidl 52952 } 52953 52954 52955 /***/ }), 52956 52957 /***/ 4854: 52958 /***/ ((module) => { 52959 52960 "use strict"; 52961 52962 52963 /** 52964 * @see https://encoding.spec.whatwg.org/#concept-encoding-get 52965 * @param {string|undefined} label 52966 */ 52967 function getEncoding (label) { 52968 if (!label) { 52969 return 'failure' 52970 } 52971 52972 // 1. Remove any leading and trailing ASCII whitespace from label. 52973 // 2. If label is an ASCII case-insensitive match for any of the 52974 // labels listed in the table below, then return the 52975 // corresponding encoding; otherwise return failure. 52976 switch (label.trim().toLowerCase()) { 52977 case 'unicode-1-1-utf-8': 52978 case 'unicode11utf8': 52979 case 'unicode20utf8': 52980 case 'utf-8': 52981 case 'utf8': 52982 case 'x-unicode20utf8': 52983 return 'UTF-8' 52984 case '866': 52985 case 'cp866': 52986 case 'csibm866': 52987 case 'ibm866': 52988 return 'IBM866' 52989 case 'csisolatin2': 52990 case 'iso-8859-2': 52991 case 'iso-ir-101': 52992 case 'iso8859-2': 52993 case 'iso88592': 52994 case 'iso_8859-2': 52995 case 'iso_8859-2:1987': 52996 case 'l2': 52997 case 'latin2': 52998 return 'ISO-8859-2' 52999 case 'csisolatin3': 53000 case 'iso-8859-3': 53001 case 'iso-ir-109': 53002 case 'iso8859-3': 53003 case 'iso88593': 53004 case 'iso_8859-3': 53005 case 'iso_8859-3:1988': 53006 case 'l3': 53007 case 'latin3': 53008 return 'ISO-8859-3' 53009 case 'csisolatin4': 53010 case 'iso-8859-4': 53011 case 'iso-ir-110': 53012 case 'iso8859-4': 53013 case 'iso88594': 53014 case 'iso_8859-4': 53015 case 'iso_8859-4:1988': 53016 case 'l4': 53017 case 'latin4': 53018 return 'ISO-8859-4' 53019 case 'csisolatincyrillic': 53020 case 'cyrillic': 53021 case 'iso-8859-5': 53022 case 'iso-ir-144': 53023 case 'iso8859-5': 53024 case 'iso88595': 53025 case 'iso_8859-5': 53026 case 'iso_8859-5:1988': 53027 return 'ISO-8859-5' 53028 case 'arabic': 53029 case 'asmo-708': 53030 case 'csiso88596e': 53031 case 'csiso88596i': 53032 case 'csisolatinarabic': 53033 case 'ecma-114': 53034 case 'iso-8859-6': 53035 case 'iso-8859-6-e': 53036 case 'iso-8859-6-i': 53037 case 'iso-ir-127': 53038 case 'iso8859-6': 53039 case 'iso88596': 53040 case 'iso_8859-6': 53041 case 'iso_8859-6:1987': 53042 return 'ISO-8859-6' 53043 case 'csisolatingreek': 53044 case 'ecma-118': 53045 case 'elot_928': 53046 case 'greek': 53047 case 'greek8': 53048 case 'iso-8859-7': 53049 case 'iso-ir-126': 53050 case 'iso8859-7': 53051 case 'iso88597': 53052 case 'iso_8859-7': 53053 case 'iso_8859-7:1987': 53054 case 'sun_eu_greek': 53055 return 'ISO-8859-7' 53056 case 'csiso88598e': 53057 case 'csisolatinhebrew': 53058 case 'hebrew': 53059 case 'iso-8859-8': 53060 case 'iso-8859-8-e': 53061 case 'iso-ir-138': 53062 case 'iso8859-8': 53063 case 'iso88598': 53064 case 'iso_8859-8': 53065 case 'iso_8859-8:1988': 53066 case 'visual': 53067 return 'ISO-8859-8' 53068 case 'csiso88598i': 53069 case 'iso-8859-8-i': 53070 case 'logical': 53071 return 'ISO-8859-8-I' 53072 case 'csisolatin6': 53073 case 'iso-8859-10': 53074 case 'iso-ir-157': 53075 case 'iso8859-10': 53076 case 'iso885910': 53077 case 'l6': 53078 case 'latin6': 53079 return 'ISO-8859-10' 53080 case 'iso-8859-13': 53081 case 'iso8859-13': 53082 case 'iso885913': 53083 return 'ISO-8859-13' 53084 case 'iso-8859-14': 53085 case 'iso8859-14': 53086 case 'iso885914': 53087 return 'ISO-8859-14' 53088 case 'csisolatin9': 53089 case 'iso-8859-15': 53090 case 'iso8859-15': 53091 case 'iso885915': 53092 case 'iso_8859-15': 53093 case 'l9': 53094 return 'ISO-8859-15' 53095 case 'iso-8859-16': 53096 return 'ISO-8859-16' 53097 case 'cskoi8r': 53098 case 'koi': 53099 case 'koi8': 53100 case 'koi8-r': 53101 case 'koi8_r': 53102 return 'KOI8-R' 53103 case 'koi8-ru': 53104 case 'koi8-u': 53105 return 'KOI8-U' 53106 case 'csmacintosh': 53107 case 'mac': 53108 case 'macintosh': 53109 case 'x-mac-roman': 53110 return 'macintosh' 53111 case 'iso-8859-11': 53112 case 'iso8859-11': 53113 case 'iso885911': 53114 case 'tis-620': 53115 case 'windows-874': 53116 return 'windows-874' 53117 case 'cp1250': 53118 case 'windows-1250': 53119 case 'x-cp1250': 53120 return 'windows-1250' 53121 case 'cp1251': 53122 case 'windows-1251': 53123 case 'x-cp1251': 53124 return 'windows-1251' 53125 case 'ansi_x3.4-1968': 53126 case 'ascii': 53127 case 'cp1252': 53128 case 'cp819': 53129 case 'csisolatin1': 53130 case 'ibm819': 53131 case 'iso-8859-1': 53132 case 'iso-ir-100': 53133 case 'iso8859-1': 53134 case 'iso88591': 53135 case 'iso_8859-1': 53136 case 'iso_8859-1:1987': 53137 case 'l1': 53138 case 'latin1': 53139 case 'us-ascii': 53140 case 'windows-1252': 53141 case 'x-cp1252': 53142 return 'windows-1252' 53143 case 'cp1253': 53144 case 'windows-1253': 53145 case 'x-cp1253': 53146 return 'windows-1253' 53147 case 'cp1254': 53148 case 'csisolatin5': 53149 case 'iso-8859-9': 53150 case 'iso-ir-148': 53151 case 'iso8859-9': 53152 case 'iso88599': 53153 case 'iso_8859-9': 53154 case 'iso_8859-9:1989': 53155 case 'l5': 53156 case 'latin5': 53157 case 'windows-1254': 53158 case 'x-cp1254': 53159 return 'windows-1254' 53160 case 'cp1255': 53161 case 'windows-1255': 53162 case 'x-cp1255': 53163 return 'windows-1255' 53164 case 'cp1256': 53165 case 'windows-1256': 53166 case 'x-cp1256': 53167 return 'windows-1256' 53168 case 'cp1257': 53169 case 'windows-1257': 53170 case 'x-cp1257': 53171 return 'windows-1257' 53172 case 'cp1258': 53173 case 'windows-1258': 53174 case 'x-cp1258': 53175 return 'windows-1258' 53176 case 'x-mac-cyrillic': 53177 case 'x-mac-ukrainian': 53178 return 'x-mac-cyrillic' 53179 case 'chinese': 53180 case 'csgb2312': 53181 case 'csiso58gb231280': 53182 case 'gb2312': 53183 case 'gb_2312': 53184 case 'gb_2312-80': 53185 case 'gbk': 53186 case 'iso-ir-58': 53187 case 'x-gbk': 53188 return 'GBK' 53189 case 'gb18030': 53190 return 'gb18030' 53191 case 'big5': 53192 case 'big5-hkscs': 53193 case 'cn-big5': 53194 case 'csbig5': 53195 case 'x-x-big5': 53196 return 'Big5' 53197 case 'cseucpkdfmtjapanese': 53198 case 'euc-jp': 53199 case 'x-euc-jp': 53200 return 'EUC-JP' 53201 case 'csiso2022jp': 53202 case 'iso-2022-jp': 53203 return 'ISO-2022-JP' 53204 case 'csshiftjis': 53205 case 'ms932': 53206 case 'ms_kanji': 53207 case 'shift-jis': 53208 case 'shift_jis': 53209 case 'sjis': 53210 case 'windows-31j': 53211 case 'x-sjis': 53212 return 'Shift_JIS' 53213 case 'cseuckr': 53214 case 'csksc56011987': 53215 case 'euc-kr': 53216 case 'iso-ir-149': 53217 case 'korean': 53218 case 'ks_c_5601-1987': 53219 case 'ks_c_5601-1989': 53220 case 'ksc5601': 53221 case 'ksc_5601': 53222 case 'windows-949': 53223 return 'EUC-KR' 53224 case 'csiso2022kr': 53225 case 'hz-gb-2312': 53226 case 'iso-2022-cn': 53227 case 'iso-2022-cn-ext': 53228 case 'iso-2022-kr': 53229 case 'replacement': 53230 return 'replacement' 53231 case 'unicodefffe': 53232 case 'utf-16be': 53233 return 'UTF-16BE' 53234 case 'csunicode': 53235 case 'iso-10646-ucs-2': 53236 case 'ucs-2': 53237 case 'unicode': 53238 case 'unicodefeff': 53239 case 'utf-16': 53240 case 'utf-16le': 53241 return 'UTF-16LE' 53242 case 'x-user-defined': 53243 return 'x-user-defined' 53244 default: return 'failure' 53245 } 53246 } 53247 53248 module.exports = { 53249 getEncoding 53250 } 53251 53252 53253 /***/ }), 53254 53255 /***/ 1446: 53256 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 53257 53258 "use strict"; 53259 53260 53261 const { 53262 staticPropertyDescriptors, 53263 readOperation, 53264 fireAProgressEvent 53265 } = __nccwpck_require__(7530) 53266 const { 53267 kState, 53268 kError, 53269 kResult, 53270 kEvents, 53271 kAborted 53272 } = __nccwpck_require__(9054) 53273 const { webidl } = __nccwpck_require__(1744) 53274 const { kEnumerableProperty } = __nccwpck_require__(3983) 53275 53276 class FileReader extends EventTarget { 53277 constructor () { 53278 super() 53279 53280 this[kState] = 'empty' 53281 this[kResult] = null 53282 this[kError] = null 53283 this[kEvents] = { 53284 loadend: null, 53285 error: null, 53286 abort: null, 53287 load: null, 53288 progress: null, 53289 loadstart: null 53290 } 53291 } 53292 53293 /** 53294 * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer 53295 * @param {import('buffer').Blob} blob 53296 */ 53297 readAsArrayBuffer (blob) { 53298 webidl.brandCheck(this, FileReader) 53299 53300 webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) 53301 53302 blob = webidl.converters.Blob(blob, { strict: false }) 53303 53304 // The readAsArrayBuffer(blob) method, when invoked, 53305 // must initiate a read operation for blob with ArrayBuffer. 53306 readOperation(this, blob, 'ArrayBuffer') 53307 } 53308 53309 /** 53310 * @see https://w3c.github.io/FileAPI/#readAsBinaryString 53311 * @param {import('buffer').Blob} blob 53312 */ 53313 readAsBinaryString (blob) { 53314 webidl.brandCheck(this, FileReader) 53315 53316 webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) 53317 53318 blob = webidl.converters.Blob(blob, { strict: false }) 53319 53320 // The readAsBinaryString(blob) method, when invoked, 53321 // must initiate a read operation for blob with BinaryString. 53322 readOperation(this, blob, 'BinaryString') 53323 } 53324 53325 /** 53326 * @see https://w3c.github.io/FileAPI/#readAsDataText 53327 * @param {import('buffer').Blob} blob 53328 * @param {string?} encoding 53329 */ 53330 readAsText (blob, encoding = undefined) { 53331 webidl.brandCheck(this, FileReader) 53332 53333 webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) 53334 53335 blob = webidl.converters.Blob(blob, { strict: false }) 53336 53337 if (encoding !== undefined) { 53338 encoding = webidl.converters.DOMString(encoding) 53339 } 53340 53341 // The readAsText(blob, encoding) method, when invoked, 53342 // must initiate a read operation for blob with Text and encoding. 53343 readOperation(this, blob, 'Text', encoding) 53344 } 53345 53346 /** 53347 * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL 53348 * @param {import('buffer').Blob} blob 53349 */ 53350 readAsDataURL (blob) { 53351 webidl.brandCheck(this, FileReader) 53352 53353 webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) 53354 53355 blob = webidl.converters.Blob(blob, { strict: false }) 53356 53357 // The readAsDataURL(blob) method, when invoked, must 53358 // initiate a read operation for blob with DataURL. 53359 readOperation(this, blob, 'DataURL') 53360 } 53361 53362 /** 53363 * @see https://w3c.github.io/FileAPI/#dfn-abort 53364 */ 53365 abort () { 53366 // 1. If this's state is "empty" or if this's state is 53367 // "done" set this's result to null and terminate 53368 // this algorithm. 53369 if (this[kState] === 'empty' || this[kState] === 'done') { 53370 this[kResult] = null 53371 return 53372 } 53373 53374 // 2. If this's state is "loading" set this's state to 53375 // "done" and set this's result to null. 53376 if (this[kState] === 'loading') { 53377 this[kState] = 'done' 53378 this[kResult] = null 53379 } 53380 53381 // 3. If there are any tasks from this on the file reading 53382 // task source in an affiliated task queue, then remove 53383 // those tasks from that task queue. 53384 this[kAborted] = true 53385 53386 // 4. Terminate the algorithm for the read method being processed. 53387 // TODO 53388 53389 // 5. Fire a progress event called abort at this. 53390 fireAProgressEvent('abort', this) 53391 53392 // 6. If this's state is not "loading", fire a progress 53393 // event called loadend at this. 53394 if (this[kState] !== 'loading') { 53395 fireAProgressEvent('loadend', this) 53396 } 53397 } 53398 53399 /** 53400 * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate 53401 */ 53402 get readyState () { 53403 webidl.brandCheck(this, FileReader) 53404 53405 switch (this[kState]) { 53406 case 'empty': return this.EMPTY 53407 case 'loading': return this.LOADING 53408 case 'done': return this.DONE 53409 } 53410 } 53411 53412 /** 53413 * @see https://w3c.github.io/FileAPI/#dom-filereader-result 53414 */ 53415 get result () { 53416 webidl.brandCheck(this, FileReader) 53417 53418 // The result attribute’s getter, when invoked, must return 53419 // this's result. 53420 return this[kResult] 53421 } 53422 53423 /** 53424 * @see https://w3c.github.io/FileAPI/#dom-filereader-error 53425 */ 53426 get error () { 53427 webidl.brandCheck(this, FileReader) 53428 53429 // The error attribute’s getter, when invoked, must return 53430 // this's error. 53431 return this[kError] 53432 } 53433 53434 get onloadend () { 53435 webidl.brandCheck(this, FileReader) 53436 53437 return this[kEvents].loadend 53438 } 53439 53440 set onloadend (fn) { 53441 webidl.brandCheck(this, FileReader) 53442 53443 if (this[kEvents].loadend) { 53444 this.removeEventListener('loadend', this[kEvents].loadend) 53445 } 53446 53447 if (typeof fn === 'function') { 53448 this[kEvents].loadend = fn 53449 this.addEventListener('loadend', fn) 53450 } else { 53451 this[kEvents].loadend = null 53452 } 53453 } 53454 53455 get onerror () { 53456 webidl.brandCheck(this, FileReader) 53457 53458 return this[kEvents].error 53459 } 53460 53461 set onerror (fn) { 53462 webidl.brandCheck(this, FileReader) 53463 53464 if (this[kEvents].error) { 53465 this.removeEventListener('error', this[kEvents].error) 53466 } 53467 53468 if (typeof fn === 'function') { 53469 this[kEvents].error = fn 53470 this.addEventListener('error', fn) 53471 } else { 53472 this[kEvents].error = null 53473 } 53474 } 53475 53476 get onloadstart () { 53477 webidl.brandCheck(this, FileReader) 53478 53479 return this[kEvents].loadstart 53480 } 53481 53482 set onloadstart (fn) { 53483 webidl.brandCheck(this, FileReader) 53484 53485 if (this[kEvents].loadstart) { 53486 this.removeEventListener('loadstart', this[kEvents].loadstart) 53487 } 53488 53489 if (typeof fn === 'function') { 53490 this[kEvents].loadstart = fn 53491 this.addEventListener('loadstart', fn) 53492 } else { 53493 this[kEvents].loadstart = null 53494 } 53495 } 53496 53497 get onprogress () { 53498 webidl.brandCheck(this, FileReader) 53499 53500 return this[kEvents].progress 53501 } 53502 53503 set onprogress (fn) { 53504 webidl.brandCheck(this, FileReader) 53505 53506 if (this[kEvents].progress) { 53507 this.removeEventListener('progress', this[kEvents].progress) 53508 } 53509 53510 if (typeof fn === 'function') { 53511 this[kEvents].progress = fn 53512 this.addEventListener('progress', fn) 53513 } else { 53514 this[kEvents].progress = null 53515 } 53516 } 53517 53518 get onload () { 53519 webidl.brandCheck(this, FileReader) 53520 53521 return this[kEvents].load 53522 } 53523 53524 set onload (fn) { 53525 webidl.brandCheck(this, FileReader) 53526 53527 if (this[kEvents].load) { 53528 this.removeEventListener('load', this[kEvents].load) 53529 } 53530 53531 if (typeof fn === 'function') { 53532 this[kEvents].load = fn 53533 this.addEventListener('load', fn) 53534 } else { 53535 this[kEvents].load = null 53536 } 53537 } 53538 53539 get onabort () { 53540 webidl.brandCheck(this, FileReader) 53541 53542 return this[kEvents].abort 53543 } 53544 53545 set onabort (fn) { 53546 webidl.brandCheck(this, FileReader) 53547 53548 if (this[kEvents].abort) { 53549 this.removeEventListener('abort', this[kEvents].abort) 53550 } 53551 53552 if (typeof fn === 'function') { 53553 this[kEvents].abort = fn 53554 this.addEventListener('abort', fn) 53555 } else { 53556 this[kEvents].abort = null 53557 } 53558 } 53559 } 53560 53561 // https://w3c.github.io/FileAPI/#dom-filereader-empty 53562 FileReader.EMPTY = FileReader.prototype.EMPTY = 0 53563 // https://w3c.github.io/FileAPI/#dom-filereader-loading 53564 FileReader.LOADING = FileReader.prototype.LOADING = 1 53565 // https://w3c.github.io/FileAPI/#dom-filereader-done 53566 FileReader.DONE = FileReader.prototype.DONE = 2 53567 53568 Object.defineProperties(FileReader.prototype, { 53569 EMPTY: staticPropertyDescriptors, 53570 LOADING: staticPropertyDescriptors, 53571 DONE: staticPropertyDescriptors, 53572 readAsArrayBuffer: kEnumerableProperty, 53573 readAsBinaryString: kEnumerableProperty, 53574 readAsText: kEnumerableProperty, 53575 readAsDataURL: kEnumerableProperty, 53576 abort: kEnumerableProperty, 53577 readyState: kEnumerableProperty, 53578 result: kEnumerableProperty, 53579 error: kEnumerableProperty, 53580 onloadstart: kEnumerableProperty, 53581 onprogress: kEnumerableProperty, 53582 onload: kEnumerableProperty, 53583 onabort: kEnumerableProperty, 53584 onerror: kEnumerableProperty, 53585 onloadend: kEnumerableProperty, 53586 [Symbol.toStringTag]: { 53587 value: 'FileReader', 53588 writable: false, 53589 enumerable: false, 53590 configurable: true 53591 } 53592 }) 53593 53594 Object.defineProperties(FileReader, { 53595 EMPTY: staticPropertyDescriptors, 53596 LOADING: staticPropertyDescriptors, 53597 DONE: staticPropertyDescriptors 53598 }) 53599 53600 module.exports = { 53601 FileReader 53602 } 53603 53604 53605 /***/ }), 53606 53607 /***/ 5504: 53608 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 53609 53610 "use strict"; 53611 53612 53613 const { webidl } = __nccwpck_require__(1744) 53614 53615 const kState = Symbol('ProgressEvent state') 53616 53617 /** 53618 * @see https://xhr.spec.whatwg.org/#progressevent 53619 */ 53620 class ProgressEvent extends Event { 53621 constructor (type, eventInitDict = {}) { 53622 type = webidl.converters.DOMString(type) 53623 eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) 53624 53625 super(type, eventInitDict) 53626 53627 this[kState] = { 53628 lengthComputable: eventInitDict.lengthComputable, 53629 loaded: eventInitDict.loaded, 53630 total: eventInitDict.total 53631 } 53632 } 53633 53634 get lengthComputable () { 53635 webidl.brandCheck(this, ProgressEvent) 53636 53637 return this[kState].lengthComputable 53638 } 53639 53640 get loaded () { 53641 webidl.brandCheck(this, ProgressEvent) 53642 53643 return this[kState].loaded 53644 } 53645 53646 get total () { 53647 webidl.brandCheck(this, ProgressEvent) 53648 53649 return this[kState].total 53650 } 53651 } 53652 53653 webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ 53654 { 53655 key: 'lengthComputable', 53656 converter: webidl.converters.boolean, 53657 defaultValue: false 53658 }, 53659 { 53660 key: 'loaded', 53661 converter: webidl.converters['unsigned long long'], 53662 defaultValue: 0 53663 }, 53664 { 53665 key: 'total', 53666 converter: webidl.converters['unsigned long long'], 53667 defaultValue: 0 53668 }, 53669 { 53670 key: 'bubbles', 53671 converter: webidl.converters.boolean, 53672 defaultValue: false 53673 }, 53674 { 53675 key: 'cancelable', 53676 converter: webidl.converters.boolean, 53677 defaultValue: false 53678 }, 53679 { 53680 key: 'composed', 53681 converter: webidl.converters.boolean, 53682 defaultValue: false 53683 } 53684 ]) 53685 53686 module.exports = { 53687 ProgressEvent 53688 } 53689 53690 53691 /***/ }), 53692 53693 /***/ 9054: 53694 /***/ ((module) => { 53695 53696 "use strict"; 53697 53698 53699 module.exports = { 53700 kState: Symbol('FileReader state'), 53701 kResult: Symbol('FileReader result'), 53702 kError: Symbol('FileReader error'), 53703 kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), 53704 kEvents: Symbol('FileReader events'), 53705 kAborted: Symbol('FileReader aborted') 53706 } 53707 53708 53709 /***/ }), 53710 53711 /***/ 7530: 53712 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 53713 53714 "use strict"; 53715 53716 53717 const { 53718 kState, 53719 kError, 53720 kResult, 53721 kAborted, 53722 kLastProgressEventFired 53723 } = __nccwpck_require__(9054) 53724 const { ProgressEvent } = __nccwpck_require__(5504) 53725 const { getEncoding } = __nccwpck_require__(4854) 53726 const { DOMException } = __nccwpck_require__(1037) 53727 const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) 53728 const { types } = __nccwpck_require__(3837) 53729 const { StringDecoder } = __nccwpck_require__(1576) 53730 const { btoa } = __nccwpck_require__(4300) 53731 53732 /** @type {PropertyDescriptor} */ 53733 const staticPropertyDescriptors = { 53734 enumerable: true, 53735 writable: false, 53736 configurable: false 53737 } 53738 53739 /** 53740 * @see https://w3c.github.io/FileAPI/#readOperation 53741 * @param {import('./filereader').FileReader} fr 53742 * @param {import('buffer').Blob} blob 53743 * @param {string} type 53744 * @param {string?} encodingName 53745 */ 53746 function readOperation (fr, blob, type, encodingName) { 53747 // 1. If fr’s state is "loading", throw an InvalidStateError 53748 // DOMException. 53749 if (fr[kState] === 'loading') { 53750 throw new DOMException('Invalid state', 'InvalidStateError') 53751 } 53752 53753 // 2. Set fr’s state to "loading". 53754 fr[kState] = 'loading' 53755 53756 // 3. Set fr’s result to null. 53757 fr[kResult] = null 53758 53759 // 4. Set fr’s error to null. 53760 fr[kError] = null 53761 53762 // 5. Let stream be the result of calling get stream on blob. 53763 /** @type {import('stream/web').ReadableStream} */ 53764 const stream = blob.stream() 53765 53766 // 6. Let reader be the result of getting a reader from stream. 53767 const reader = stream.getReader() 53768 53769 // 7. Let bytes be an empty byte sequence. 53770 /** @type {Uint8Array[]} */ 53771 const bytes = [] 53772 53773 // 8. Let chunkPromise be the result of reading a chunk from 53774 // stream with reader. 53775 let chunkPromise = reader.read() 53776 53777 // 9. Let isFirstChunk be true. 53778 let isFirstChunk = true 53779 53780 // 10. In parallel, while true: 53781 // Note: "In parallel" just means non-blocking 53782 // Note 2: readOperation itself cannot be async as double 53783 // reading the body would then reject the promise, instead 53784 // of throwing an error. 53785 ;(async () => { 53786 while (!fr[kAborted]) { 53787 // 1. Wait for chunkPromise to be fulfilled or rejected. 53788 try { 53789 const { done, value } = await chunkPromise 53790 53791 // 2. If chunkPromise is fulfilled, and isFirstChunk is 53792 // true, queue a task to fire a progress event called 53793 // loadstart at fr. 53794 if (isFirstChunk && !fr[kAborted]) { 53795 queueMicrotask(() => { 53796 fireAProgressEvent('loadstart', fr) 53797 }) 53798 } 53799 53800 // 3. Set isFirstChunk to false. 53801 isFirstChunk = false 53802 53803 // 4. If chunkPromise is fulfilled with an object whose 53804 // done property is false and whose value property is 53805 // a Uint8Array object, run these steps: 53806 if (!done && types.isUint8Array(value)) { 53807 // 1. Let bs be the byte sequence represented by the 53808 // Uint8Array object. 53809 53810 // 2. Append bs to bytes. 53811 bytes.push(value) 53812 53813 // 3. If roughly 50ms have passed since these steps 53814 // were last invoked, queue a task to fire a 53815 // progress event called progress at fr. 53816 if ( 53817 ( 53818 fr[kLastProgressEventFired] === undefined || 53819 Date.now() - fr[kLastProgressEventFired] >= 50 53820 ) && 53821 !fr[kAborted] 53822 ) { 53823 fr[kLastProgressEventFired] = Date.now() 53824 queueMicrotask(() => { 53825 fireAProgressEvent('progress', fr) 53826 }) 53827 } 53828 53829 // 4. Set chunkPromise to the result of reading a 53830 // chunk from stream with reader. 53831 chunkPromise = reader.read() 53832 } else if (done) { 53833 // 5. Otherwise, if chunkPromise is fulfilled with an 53834 // object whose done property is true, queue a task 53835 // to run the following steps and abort this algorithm: 53836 queueMicrotask(() => { 53837 // 1. Set fr’s state to "done". 53838 fr[kState] = 'done' 53839 53840 // 2. Let result be the result of package data given 53841 // bytes, type, blob’s type, and encodingName. 53842 try { 53843 const result = packageData(bytes, type, blob.type, encodingName) 53844 53845 // 4. Else: 53846 53847 if (fr[kAborted]) { 53848 return 53849 } 53850 53851 // 1. Set fr’s result to result. 53852 fr[kResult] = result 53853 53854 // 2. Fire a progress event called load at the fr. 53855 fireAProgressEvent('load', fr) 53856 } catch (error) { 53857 // 3. If package data threw an exception error: 53858 53859 // 1. Set fr’s error to error. 53860 fr[kError] = error 53861 53862 // 2. Fire a progress event called error at fr. 53863 fireAProgressEvent('error', fr) 53864 } 53865 53866 // 5. If fr’s state is not "loading", fire a progress 53867 // event called loadend at the fr. 53868 if (fr[kState] !== 'loading') { 53869 fireAProgressEvent('loadend', fr) 53870 } 53871 }) 53872 53873 break 53874 } 53875 } catch (error) { 53876 if (fr[kAborted]) { 53877 return 53878 } 53879 53880 // 6. Otherwise, if chunkPromise is rejected with an 53881 // error error, queue a task to run the following 53882 // steps and abort this algorithm: 53883 queueMicrotask(() => { 53884 // 1. Set fr’s state to "done". 53885 fr[kState] = 'done' 53886 53887 // 2. Set fr’s error to error. 53888 fr[kError] = error 53889 53890 // 3. Fire a progress event called error at fr. 53891 fireAProgressEvent('error', fr) 53892 53893 // 4. If fr’s state is not "loading", fire a progress 53894 // event called loadend at fr. 53895 if (fr[kState] !== 'loading') { 53896 fireAProgressEvent('loadend', fr) 53897 } 53898 }) 53899 53900 break 53901 } 53902 } 53903 })() 53904 } 53905 53906 /** 53907 * @see https://w3c.github.io/FileAPI/#fire-a-progress-event 53908 * @see https://dom.spec.whatwg.org/#concept-event-fire 53909 * @param {string} e The name of the event 53910 * @param {import('./filereader').FileReader} reader 53911 */ 53912 function fireAProgressEvent (e, reader) { 53913 // The progress event e does not bubble. e.bubbles must be false 53914 // The progress event e is NOT cancelable. e.cancelable must be false 53915 const event = new ProgressEvent(e, { 53916 bubbles: false, 53917 cancelable: false 53918 }) 53919 53920 reader.dispatchEvent(event) 53921 } 53922 53923 /** 53924 * @see https://w3c.github.io/FileAPI/#blob-package-data 53925 * @param {Uint8Array[]} bytes 53926 * @param {string} type 53927 * @param {string?} mimeType 53928 * @param {string?} encodingName 53929 */ 53930 function packageData (bytes, type, mimeType, encodingName) { 53931 // 1. A Blob has an associated package data algorithm, given 53932 // bytes, a type, a optional mimeType, and a optional 53933 // encodingName, which switches on type and runs the 53934 // associated steps: 53935 53936 switch (type) { 53937 case 'DataURL': { 53938 // 1. Return bytes as a DataURL [RFC2397] subject to 53939 // the considerations below: 53940 // * Use mimeType as part of the Data URL if it is 53941 // available in keeping with the Data URL 53942 // specification [RFC2397]. 53943 // * If mimeType is not available return a Data URL 53944 // without a media-type. [RFC2397]. 53945 53946 // https://datatracker.ietf.org/doc/html/rfc2397#section-3 53947 // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data 53948 // mediatype := [ type "/" subtype ] *( ";" parameter ) 53949 // data := *urlchar 53950 // parameter := attribute "=" value 53951 let dataURL = 'data:' 53952 53953 const parsed = parseMIMEType(mimeType || 'application/octet-stream') 53954 53955 if (parsed !== 'failure') { 53956 dataURL += serializeAMimeType(parsed) 53957 } 53958 53959 dataURL += ';base64,' 53960 53961 const decoder = new StringDecoder('latin1') 53962 53963 for (const chunk of bytes) { 53964 dataURL += btoa(decoder.write(chunk)) 53965 } 53966 53967 dataURL += btoa(decoder.end()) 53968 53969 return dataURL 53970 } 53971 case 'Text': { 53972 // 1. Let encoding be failure 53973 let encoding = 'failure' 53974 53975 // 2. If the encodingName is present, set encoding to the 53976 // result of getting an encoding from encodingName. 53977 if (encodingName) { 53978 encoding = getEncoding(encodingName) 53979 } 53980 53981 // 3. If encoding is failure, and mimeType is present: 53982 if (encoding === 'failure' && mimeType) { 53983 // 1. Let type be the result of parse a MIME type 53984 // given mimeType. 53985 const type = parseMIMEType(mimeType) 53986 53987 // 2. If type is not failure, set encoding to the result 53988 // of getting an encoding from type’s parameters["charset"]. 53989 if (type !== 'failure') { 53990 encoding = getEncoding(type.parameters.get('charset')) 53991 } 53992 } 53993 53994 // 4. If encoding is failure, then set encoding to UTF-8. 53995 if (encoding === 'failure') { 53996 encoding = 'UTF-8' 53997 } 53998 53999 // 5. Decode bytes using fallback encoding encoding, and 54000 // return the result. 54001 return decode(bytes, encoding) 54002 } 54003 case 'ArrayBuffer': { 54004 // Return a new ArrayBuffer whose contents are bytes. 54005 const sequence = combineByteSequences(bytes) 54006 54007 return sequence.buffer 54008 } 54009 case 'BinaryString': { 54010 // Return bytes as a binary string, in which every byte 54011 // is represented by a code unit of equal value [0..255]. 54012 let binaryString = '' 54013 54014 const decoder = new StringDecoder('latin1') 54015 54016 for (const chunk of bytes) { 54017 binaryString += decoder.write(chunk) 54018 } 54019 54020 binaryString += decoder.end() 54021 54022 return binaryString 54023 } 54024 } 54025 } 54026 54027 /** 54028 * @see https://encoding.spec.whatwg.org/#decode 54029 * @param {Uint8Array[]} ioQueue 54030 * @param {string} encoding 54031 */ 54032 function decode (ioQueue, encoding) { 54033 const bytes = combineByteSequences(ioQueue) 54034 54035 // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. 54036 const BOMEncoding = BOMSniffing(bytes) 54037 54038 let slice = 0 54039 54040 // 2. If BOMEncoding is non-null: 54041 if (BOMEncoding !== null) { 54042 // 1. Set encoding to BOMEncoding. 54043 encoding = BOMEncoding 54044 54045 // 2. Read three bytes from ioQueue, if BOMEncoding is 54046 // UTF-8; otherwise read two bytes. 54047 // (Do nothing with those bytes.) 54048 slice = BOMEncoding === 'UTF-8' ? 3 : 2 54049 } 54050 54051 // 3. Process a queue with an instance of encoding’s 54052 // decoder, ioQueue, output, and "replacement". 54053 54054 // 4. Return output. 54055 54056 const sliced = bytes.slice(slice) 54057 return new TextDecoder(encoding).decode(sliced) 54058 } 54059 54060 /** 54061 * @see https://encoding.spec.whatwg.org/#bom-sniff 54062 * @param {Uint8Array} ioQueue 54063 */ 54064 function BOMSniffing (ioQueue) { 54065 // 1. Let BOM be the result of peeking 3 bytes from ioQueue, 54066 // converted to a byte sequence. 54067 const [a, b, c] = ioQueue 54068 54069 // 2. For each of the rows in the table below, starting with 54070 // the first one and going down, if BOM starts with the 54071 // bytes given in the first column, then return the 54072 // encoding given in the cell in the second column of that 54073 // row. Otherwise, return null. 54074 if (a === 0xEF && b === 0xBB && c === 0xBF) { 54075 return 'UTF-8' 54076 } else if (a === 0xFE && b === 0xFF) { 54077 return 'UTF-16BE' 54078 } else if (a === 0xFF && b === 0xFE) { 54079 return 'UTF-16LE' 54080 } 54081 54082 return null 54083 } 54084 54085 /** 54086 * @param {Uint8Array[]} sequences 54087 */ 54088 function combineByteSequences (sequences) { 54089 const size = sequences.reduce((a, b) => { 54090 return a + b.byteLength 54091 }, 0) 54092 54093 let offset = 0 54094 54095 return sequences.reduce((a, b) => { 54096 a.set(b, offset) 54097 offset += b.byteLength 54098 return a 54099 }, new Uint8Array(size)) 54100 } 54101 54102 module.exports = { 54103 staticPropertyDescriptors, 54104 readOperation, 54105 fireAProgressEvent 54106 } 54107 54108 54109 /***/ }), 54110 54111 /***/ 1892: 54112 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 54113 54114 "use strict"; 54115 54116 54117 // We include a version number for the Dispatcher API. In case of breaking changes, 54118 // this version number must be increased to avoid conflicts. 54119 const globalDispatcher = Symbol.for('undici.globalDispatcher.1') 54120 const { InvalidArgumentError } = __nccwpck_require__(8045) 54121 const Agent = __nccwpck_require__(7890) 54122 54123 if (getGlobalDispatcher() === undefined) { 54124 setGlobalDispatcher(new Agent()) 54125 } 54126 54127 function setGlobalDispatcher (agent) { 54128 if (!agent || typeof agent.dispatch !== 'function') { 54129 throw new InvalidArgumentError('Argument agent must implement Agent') 54130 } 54131 Object.defineProperty(globalThis, globalDispatcher, { 54132 value: agent, 54133 writable: true, 54134 enumerable: false, 54135 configurable: false 54136 }) 54137 } 54138 54139 function getGlobalDispatcher () { 54140 return globalThis[globalDispatcher] 54141 } 54142 54143 module.exports = { 54144 setGlobalDispatcher, 54145 getGlobalDispatcher 54146 } 54147 54148 54149 /***/ }), 54150 54151 /***/ 6930: 54152 /***/ ((module) => { 54153 54154 "use strict"; 54155 54156 54157 module.exports = class DecoratorHandler { 54158 constructor (handler) { 54159 this.handler = handler 54160 } 54161 54162 onConnect (...args) { 54163 return this.handler.onConnect(...args) 54164 } 54165 54166 onError (...args) { 54167 return this.handler.onError(...args) 54168 } 54169 54170 onUpgrade (...args) { 54171 return this.handler.onUpgrade(...args) 54172 } 54173 54174 onHeaders (...args) { 54175 return this.handler.onHeaders(...args) 54176 } 54177 54178 onData (...args) { 54179 return this.handler.onData(...args) 54180 } 54181 54182 onComplete (...args) { 54183 return this.handler.onComplete(...args) 54184 } 54185 54186 onBodySent (...args) { 54187 return this.handler.onBodySent(...args) 54188 } 54189 } 54190 54191 54192 /***/ }), 54193 54194 /***/ 2860: 54195 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 54196 54197 "use strict"; 54198 54199 54200 const util = __nccwpck_require__(3983) 54201 const { kBodyUsed } = __nccwpck_require__(2785) 54202 const assert = __nccwpck_require__(9491) 54203 const { InvalidArgumentError } = __nccwpck_require__(8045) 54204 const EE = __nccwpck_require__(2361) 54205 54206 const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] 54207 54208 const kBody = Symbol('body') 54209 54210 class BodyAsyncIterable { 54211 constructor (body) { 54212 this[kBody] = body 54213 this[kBodyUsed] = false 54214 } 54215 54216 async * [Symbol.asyncIterator] () { 54217 assert(!this[kBodyUsed], 'disturbed') 54218 this[kBodyUsed] = true 54219 yield * this[kBody] 54220 } 54221 } 54222 54223 class RedirectHandler { 54224 constructor (dispatch, maxRedirections, opts, handler) { 54225 if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { 54226 throw new InvalidArgumentError('maxRedirections must be a positive number') 54227 } 54228 54229 util.validateHandler(handler, opts.method, opts.upgrade) 54230 54231 this.dispatch = dispatch 54232 this.location = null 54233 this.abort = null 54234 this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy 54235 this.maxRedirections = maxRedirections 54236 this.handler = handler 54237 this.history = [] 54238 54239 if (util.isStream(this.opts.body)) { 54240 // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp 54241 // so that it can be dispatched again? 54242 // TODO (fix): Do we need 100-expect support to provide a way to do this properly? 54243 if (util.bodyLength(this.opts.body) === 0) { 54244 this.opts.body 54245 .on('data', function () { 54246 assert(false) 54247 }) 54248 } 54249 54250 if (typeof this.opts.body.readableDidRead !== 'boolean') { 54251 this.opts.body[kBodyUsed] = false 54252 EE.prototype.on.call(this.opts.body, 'data', function () { 54253 this[kBodyUsed] = true 54254 }) 54255 } 54256 } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { 54257 // TODO (fix): We can't access ReadableStream internal state 54258 // to determine whether or not it has been disturbed. This is just 54259 // a workaround. 54260 this.opts.body = new BodyAsyncIterable(this.opts.body) 54261 } else if ( 54262 this.opts.body && 54263 typeof this.opts.body !== 'string' && 54264 !ArrayBuffer.isView(this.opts.body) && 54265 util.isIterable(this.opts.body) 54266 ) { 54267 // TODO: Should we allow re-using iterable if !this.opts.idempotent 54268 // or through some other flag? 54269 this.opts.body = new BodyAsyncIterable(this.opts.body) 54270 } 54271 } 54272 54273 onConnect (abort) { 54274 this.abort = abort 54275 this.handler.onConnect(abort, { history: this.history }) 54276 } 54277 54278 onUpgrade (statusCode, headers, socket) { 54279 this.handler.onUpgrade(statusCode, headers, socket) 54280 } 54281 54282 onError (error) { 54283 this.handler.onError(error) 54284 } 54285 54286 onHeaders (statusCode, headers, resume, statusText) { 54287 this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) 54288 ? null 54289 : parseLocation(statusCode, headers) 54290 54291 if (this.opts.origin) { 54292 this.history.push(new URL(this.opts.path, this.opts.origin)) 54293 } 54294 54295 if (!this.location) { 54296 return this.handler.onHeaders(statusCode, headers, resume, statusText) 54297 } 54298 54299 const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) 54300 const path = search ? `${pathname}${search}` : pathname 54301 54302 // Remove headers referring to the original URL. 54303 // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. 54304 // https://tools.ietf.org/html/rfc7231#section-6.4 54305 this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) 54306 this.opts.path = path 54307 this.opts.origin = origin 54308 this.opts.maxRedirections = 0 54309 this.opts.query = null 54310 54311 // https://tools.ietf.org/html/rfc7231#section-6.4.4 54312 // In case of HTTP 303, always replace method to be either HEAD or GET 54313 if (statusCode === 303 && this.opts.method !== 'HEAD') { 54314 this.opts.method = 'GET' 54315 this.opts.body = null 54316 } 54317 } 54318 54319 onData (chunk) { 54320 if (this.location) { 54321 /* 54322 https://tools.ietf.org/html/rfc7231#section-6.4 54323 54324 TLDR: undici always ignores 3xx response bodies. 54325 54326 Redirection is used to serve the requested resource from another URL, so it is assumes that 54327 no body is generated (and thus can be ignored). Even though generating a body is not prohibited. 54328 54329 For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually 54330 (which means it's optional and not mandated) contain just an hyperlink to the value of 54331 the Location response header, so the body can be ignored safely. 54332 54333 For status 300, which is "Multiple Choices", the spec mentions both generating a Location 54334 response header AND a response body with the other possible location to follow. 54335 Since the spec explicitily chooses not to specify a format for such body and leave it to 54336 servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. 54337 */ 54338 } else { 54339 return this.handler.onData(chunk) 54340 } 54341 } 54342 54343 onComplete (trailers) { 54344 if (this.location) { 54345 /* 54346 https://tools.ietf.org/html/rfc7231#section-6.4 54347 54348 TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections 54349 and neither are useful if present. 54350 54351 See comment on onData method above for more detailed informations. 54352 */ 54353 54354 this.location = null 54355 this.abort = null 54356 54357 this.dispatch(this.opts, this) 54358 } else { 54359 this.handler.onComplete(trailers) 54360 } 54361 } 54362 54363 onBodySent (chunk) { 54364 if (this.handler.onBodySent) { 54365 this.handler.onBodySent(chunk) 54366 } 54367 } 54368 } 54369 54370 function parseLocation (statusCode, headers) { 54371 if (redirectableStatusCodes.indexOf(statusCode) === -1) { 54372 return null 54373 } 54374 54375 for (let i = 0; i < headers.length; i += 2) { 54376 if (headers[i].toString().toLowerCase() === 'location') { 54377 return headers[i + 1] 54378 } 54379 } 54380 } 54381 54382 // https://tools.ietf.org/html/rfc7231#section-6.4.4 54383 function shouldRemoveHeader (header, removeContent, unknownOrigin) { 54384 if (header.length === 4) { 54385 return util.headerNameToString(header) === 'host' 54386 } 54387 if (removeContent && util.headerNameToString(header).startsWith('content-')) { 54388 return true 54389 } 54390 if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { 54391 const name = util.headerNameToString(header) 54392 return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' 54393 } 54394 return false 54395 } 54396 54397 // https://tools.ietf.org/html/rfc7231#section-6.4 54398 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { 54399 const ret = [] 54400 if (Array.isArray(headers)) { 54401 for (let i = 0; i < headers.length; i += 2) { 54402 if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { 54403 ret.push(headers[i], headers[i + 1]) 54404 } 54405 } 54406 } else if (headers && typeof headers === 'object') { 54407 for (const key of Object.keys(headers)) { 54408 if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { 54409 ret.push(key, headers[key]) 54410 } 54411 } 54412 } else { 54413 assert(headers == null, 'headers must be an object or an array') 54414 } 54415 return ret 54416 } 54417 54418 module.exports = RedirectHandler 54419 54420 54421 /***/ }), 54422 54423 /***/ 2286: 54424 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 54425 54426 const assert = __nccwpck_require__(9491) 54427 54428 const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) 54429 const { RequestRetryError } = __nccwpck_require__(8045) 54430 const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) 54431 54432 function calculateRetryAfterHeader (retryAfter) { 54433 const current = Date.now() 54434 const diff = new Date(retryAfter).getTime() - current 54435 54436 return diff 54437 } 54438 54439 class RetryHandler { 54440 constructor (opts, handlers) { 54441 const { retryOptions, ...dispatchOpts } = opts 54442 const { 54443 // Retry scoped 54444 retry: retryFn, 54445 maxRetries, 54446 maxTimeout, 54447 minTimeout, 54448 timeoutFactor, 54449 // Response scoped 54450 methods, 54451 errorCodes, 54452 retryAfter, 54453 statusCodes 54454 } = retryOptions ?? {} 54455 54456 this.dispatch = handlers.dispatch 54457 this.handler = handlers.handler 54458 this.opts = dispatchOpts 54459 this.abort = null 54460 this.aborted = false 54461 this.retryOpts = { 54462 retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], 54463 retryAfter: retryAfter ?? true, 54464 maxTimeout: maxTimeout ?? 30 * 1000, // 30s, 54465 timeout: minTimeout ?? 500, // .5s 54466 timeoutFactor: timeoutFactor ?? 2, 54467 maxRetries: maxRetries ?? 5, 54468 // What errors we should retry 54469 methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], 54470 // Indicates which errors to retry 54471 statusCodes: statusCodes ?? [500, 502, 503, 504, 429], 54472 // List of errors to retry 54473 errorCodes: errorCodes ?? [ 54474 'ECONNRESET', 54475 'ECONNREFUSED', 54476 'ENOTFOUND', 54477 'ENETDOWN', 54478 'ENETUNREACH', 54479 'EHOSTDOWN', 54480 'EHOSTUNREACH', 54481 'EPIPE' 54482 ] 54483 } 54484 54485 this.retryCount = 0 54486 this.start = 0 54487 this.end = null 54488 this.etag = null 54489 this.resume = null 54490 54491 // Handle possible onConnect duplication 54492 this.handler.onConnect(reason => { 54493 this.aborted = true 54494 if (this.abort) { 54495 this.abort(reason) 54496 } else { 54497 this.reason = reason 54498 } 54499 }) 54500 } 54501 54502 onRequestSent () { 54503 if (this.handler.onRequestSent) { 54504 this.handler.onRequestSent() 54505 } 54506 } 54507 54508 onUpgrade (statusCode, headers, socket) { 54509 if (this.handler.onUpgrade) { 54510 this.handler.onUpgrade(statusCode, headers, socket) 54511 } 54512 } 54513 54514 onConnect (abort) { 54515 if (this.aborted) { 54516 abort(this.reason) 54517 } else { 54518 this.abort = abort 54519 } 54520 } 54521 54522 onBodySent (chunk) { 54523 if (this.handler.onBodySent) return this.handler.onBodySent(chunk) 54524 } 54525 54526 static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { 54527 const { statusCode, code, headers } = err 54528 const { method, retryOptions } = opts 54529 const { 54530 maxRetries, 54531 timeout, 54532 maxTimeout, 54533 timeoutFactor, 54534 statusCodes, 54535 errorCodes, 54536 methods 54537 } = retryOptions 54538 let { counter, currentTimeout } = state 54539 54540 currentTimeout = 54541 currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout 54542 54543 // Any code that is not a Undici's originated and allowed to retry 54544 if ( 54545 code && 54546 code !== 'UND_ERR_REQ_RETRY' && 54547 code !== 'UND_ERR_SOCKET' && 54548 !errorCodes.includes(code) 54549 ) { 54550 cb(err) 54551 return 54552 } 54553 54554 // If a set of method are provided and the current method is not in the list 54555 if (Array.isArray(methods) && !methods.includes(method)) { 54556 cb(err) 54557 return 54558 } 54559 54560 // If a set of status code are provided and the current status code is not in the list 54561 if ( 54562 statusCode != null && 54563 Array.isArray(statusCodes) && 54564 !statusCodes.includes(statusCode) 54565 ) { 54566 cb(err) 54567 return 54568 } 54569 54570 // If we reached the max number of retries 54571 if (counter > maxRetries) { 54572 cb(err) 54573 return 54574 } 54575 54576 let retryAfterHeader = headers != null && headers['retry-after'] 54577 if (retryAfterHeader) { 54578 retryAfterHeader = Number(retryAfterHeader) 54579 retryAfterHeader = isNaN(retryAfterHeader) 54580 ? calculateRetryAfterHeader(retryAfterHeader) 54581 : retryAfterHeader * 1e3 // Retry-After is in seconds 54582 } 54583 54584 const retryTimeout = 54585 retryAfterHeader > 0 54586 ? Math.min(retryAfterHeader, maxTimeout) 54587 : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) 54588 54589 state.currentTimeout = retryTimeout 54590 54591 setTimeout(() => cb(null), retryTimeout) 54592 } 54593 54594 onHeaders (statusCode, rawHeaders, resume, statusMessage) { 54595 const headers = parseHeaders(rawHeaders) 54596 54597 this.retryCount += 1 54598 54599 if (statusCode >= 300) { 54600 this.abort( 54601 new RequestRetryError('Request failed', statusCode, { 54602 headers, 54603 count: this.retryCount 54604 }) 54605 ) 54606 return false 54607 } 54608 54609 // Checkpoint for resume from where we left it 54610 if (this.resume != null) { 54611 this.resume = null 54612 54613 if (statusCode !== 206) { 54614 return true 54615 } 54616 54617 const contentRange = parseRangeHeader(headers['content-range']) 54618 // If no content range 54619 if (!contentRange) { 54620 this.abort( 54621 new RequestRetryError('Content-Range mismatch', statusCode, { 54622 headers, 54623 count: this.retryCount 54624 }) 54625 ) 54626 return false 54627 } 54628 54629 // Let's start with a weak etag check 54630 if (this.etag != null && this.etag !== headers.etag) { 54631 this.abort( 54632 new RequestRetryError('ETag mismatch', statusCode, { 54633 headers, 54634 count: this.retryCount 54635 }) 54636 ) 54637 return false 54638 } 54639 54640 const { start, size, end = size } = contentRange 54641 54642 assert(this.start === start, 'content-range mismatch') 54643 assert(this.end == null || this.end === end, 'content-range mismatch') 54644 54645 this.resume = resume 54646 return true 54647 } 54648 54649 if (this.end == null) { 54650 if (statusCode === 206) { 54651 // First time we receive 206 54652 const range = parseRangeHeader(headers['content-range']) 54653 54654 if (range == null) { 54655 return this.handler.onHeaders( 54656 statusCode, 54657 rawHeaders, 54658 resume, 54659 statusMessage 54660 ) 54661 } 54662 54663 const { start, size, end = size } = range 54664 54665 assert( 54666 start != null && Number.isFinite(start) && this.start !== start, 54667 'content-range mismatch' 54668 ) 54669 assert(Number.isFinite(start)) 54670 assert( 54671 end != null && Number.isFinite(end) && this.end !== end, 54672 'invalid content-length' 54673 ) 54674 54675 this.start = start 54676 this.end = end 54677 } 54678 54679 // We make our best to checkpoint the body for further range headers 54680 if (this.end == null) { 54681 const contentLength = headers['content-length'] 54682 this.end = contentLength != null ? Number(contentLength) : null 54683 } 54684 54685 assert(Number.isFinite(this.start)) 54686 assert( 54687 this.end == null || Number.isFinite(this.end), 54688 'invalid content-length' 54689 ) 54690 54691 this.resume = resume 54692 this.etag = headers.etag != null ? headers.etag : null 54693 54694 return this.handler.onHeaders( 54695 statusCode, 54696 rawHeaders, 54697 resume, 54698 statusMessage 54699 ) 54700 } 54701 54702 const err = new RequestRetryError('Request failed', statusCode, { 54703 headers, 54704 count: this.retryCount 54705 }) 54706 54707 this.abort(err) 54708 54709 return false 54710 } 54711 54712 onData (chunk) { 54713 this.start += chunk.length 54714 54715 return this.handler.onData(chunk) 54716 } 54717 54718 onComplete (rawTrailers) { 54719 this.retryCount = 0 54720 return this.handler.onComplete(rawTrailers) 54721 } 54722 54723 onError (err) { 54724 if (this.aborted || isDisturbed(this.opts.body)) { 54725 return this.handler.onError(err) 54726 } 54727 54728 this.retryOpts.retry( 54729 err, 54730 { 54731 state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, 54732 opts: { retryOptions: this.retryOpts, ...this.opts } 54733 }, 54734 onRetry.bind(this) 54735 ) 54736 54737 function onRetry (err) { 54738 if (err != null || this.aborted || isDisturbed(this.opts.body)) { 54739 return this.handler.onError(err) 54740 } 54741 54742 if (this.start !== 0) { 54743 this.opts = { 54744 ...this.opts, 54745 headers: { 54746 ...this.opts.headers, 54747 range: `bytes=${this.start}-${this.end ?? ''}` 54748 } 54749 } 54750 } 54751 54752 try { 54753 this.dispatch(this.opts, this) 54754 } catch (err) { 54755 this.handler.onError(err) 54756 } 54757 } 54758 } 54759 } 54760 54761 module.exports = RetryHandler 54762 54763 54764 /***/ }), 54765 54766 /***/ 8861: 54767 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 54768 54769 "use strict"; 54770 54771 54772 const RedirectHandler = __nccwpck_require__(2860) 54773 54774 function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { 54775 return (dispatch) => { 54776 return function Intercept (opts, handler) { 54777 const { maxRedirections = defaultMaxRedirections } = opts 54778 54779 if (!maxRedirections) { 54780 return dispatch(opts, handler) 54781 } 54782 54783 const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) 54784 opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. 54785 return dispatch(opts, redirectHandler) 54786 } 54787 } 54788 } 54789 54790 module.exports = createRedirectInterceptor 54791 54792 54793 /***/ }), 54794 54795 /***/ 953: 54796 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 54797 54798 "use strict"; 54799 54800 Object.defineProperty(exports, "__esModule", ({ value: true })); 54801 exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; 54802 const utils_1 = __nccwpck_require__(1891); 54803 // C headers 54804 var ERROR; 54805 (function (ERROR) { 54806 ERROR[ERROR["OK"] = 0] = "OK"; 54807 ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; 54808 ERROR[ERROR["STRICT"] = 2] = "STRICT"; 54809 ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; 54810 ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; 54811 ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; 54812 ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; 54813 ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; 54814 ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; 54815 ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; 54816 ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; 54817 ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; 54818 ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; 54819 ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; 54820 ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; 54821 ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; 54822 ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; 54823 ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; 54824 ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; 54825 ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; 54826 ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; 54827 ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; 54828 ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; 54829 ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; 54830 ERROR[ERROR["USER"] = 24] = "USER"; 54831 })(ERROR = exports.ERROR || (exports.ERROR = {})); 54832 var TYPE; 54833 (function (TYPE) { 54834 TYPE[TYPE["BOTH"] = 0] = "BOTH"; 54835 TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; 54836 TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; 54837 })(TYPE = exports.TYPE || (exports.TYPE = {})); 54838 var FLAGS; 54839 (function (FLAGS) { 54840 FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; 54841 FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; 54842 FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; 54843 FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; 54844 FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; 54845 FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; 54846 FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; 54847 FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; 54848 // 1 << 8 is unused 54849 FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; 54850 })(FLAGS = exports.FLAGS || (exports.FLAGS = {})); 54851 var LENIENT_FLAGS; 54852 (function (LENIENT_FLAGS) { 54853 LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; 54854 LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; 54855 LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; 54856 })(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); 54857 var METHODS; 54858 (function (METHODS) { 54859 METHODS[METHODS["DELETE"] = 0] = "DELETE"; 54860 METHODS[METHODS["GET"] = 1] = "GET"; 54861 METHODS[METHODS["HEAD"] = 2] = "HEAD"; 54862 METHODS[METHODS["POST"] = 3] = "POST"; 54863 METHODS[METHODS["PUT"] = 4] = "PUT"; 54864 /* pathological */ 54865 METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; 54866 METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; 54867 METHODS[METHODS["TRACE"] = 7] = "TRACE"; 54868 /* WebDAV */ 54869 METHODS[METHODS["COPY"] = 8] = "COPY"; 54870 METHODS[METHODS["LOCK"] = 9] = "LOCK"; 54871 METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; 54872 METHODS[METHODS["MOVE"] = 11] = "MOVE"; 54873 METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; 54874 METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; 54875 METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; 54876 METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; 54877 METHODS[METHODS["BIND"] = 16] = "BIND"; 54878 METHODS[METHODS["REBIND"] = 17] = "REBIND"; 54879 METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; 54880 METHODS[METHODS["ACL"] = 19] = "ACL"; 54881 /* subversion */ 54882 METHODS[METHODS["REPORT"] = 20] = "REPORT"; 54883 METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; 54884 METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; 54885 METHODS[METHODS["MERGE"] = 23] = "MERGE"; 54886 /* upnp */ 54887 METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; 54888 METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; 54889 METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; 54890 METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; 54891 /* RFC-5789 */ 54892 METHODS[METHODS["PATCH"] = 28] = "PATCH"; 54893 METHODS[METHODS["PURGE"] = 29] = "PURGE"; 54894 /* CalDAV */ 54895 METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; 54896 /* RFC-2068, section 19.6.1.2 */ 54897 METHODS[METHODS["LINK"] = 31] = "LINK"; 54898 METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; 54899 /* icecast */ 54900 METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; 54901 /* RFC-7540, section 11.6 */ 54902 METHODS[METHODS["PRI"] = 34] = "PRI"; 54903 /* RFC-2326 RTSP */ 54904 METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; 54905 METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; 54906 METHODS[METHODS["SETUP"] = 37] = "SETUP"; 54907 METHODS[METHODS["PLAY"] = 38] = "PLAY"; 54908 METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; 54909 METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; 54910 METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; 54911 METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; 54912 METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; 54913 METHODS[METHODS["RECORD"] = 44] = "RECORD"; 54914 /* RAOP */ 54915 METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; 54916 })(METHODS = exports.METHODS || (exports.METHODS = {})); 54917 exports.METHODS_HTTP = [ 54918 METHODS.DELETE, 54919 METHODS.GET, 54920 METHODS.HEAD, 54921 METHODS.POST, 54922 METHODS.PUT, 54923 METHODS.CONNECT, 54924 METHODS.OPTIONS, 54925 METHODS.TRACE, 54926 METHODS.COPY, 54927 METHODS.LOCK, 54928 METHODS.MKCOL, 54929 METHODS.MOVE, 54930 METHODS.PROPFIND, 54931 METHODS.PROPPATCH, 54932 METHODS.SEARCH, 54933 METHODS.UNLOCK, 54934 METHODS.BIND, 54935 METHODS.REBIND, 54936 METHODS.UNBIND, 54937 METHODS.ACL, 54938 METHODS.REPORT, 54939 METHODS.MKACTIVITY, 54940 METHODS.CHECKOUT, 54941 METHODS.MERGE, 54942 METHODS['M-SEARCH'], 54943 METHODS.NOTIFY, 54944 METHODS.SUBSCRIBE, 54945 METHODS.UNSUBSCRIBE, 54946 METHODS.PATCH, 54947 METHODS.PURGE, 54948 METHODS.MKCALENDAR, 54949 METHODS.LINK, 54950 METHODS.UNLINK, 54951 METHODS.PRI, 54952 // TODO(indutny): should we allow it with HTTP? 54953 METHODS.SOURCE, 54954 ]; 54955 exports.METHODS_ICE = [ 54956 METHODS.SOURCE, 54957 ]; 54958 exports.METHODS_RTSP = [ 54959 METHODS.OPTIONS, 54960 METHODS.DESCRIBE, 54961 METHODS.ANNOUNCE, 54962 METHODS.SETUP, 54963 METHODS.PLAY, 54964 METHODS.PAUSE, 54965 METHODS.TEARDOWN, 54966 METHODS.GET_PARAMETER, 54967 METHODS.SET_PARAMETER, 54968 METHODS.REDIRECT, 54969 METHODS.RECORD, 54970 METHODS.FLUSH, 54971 // For AirPlay 54972 METHODS.GET, 54973 METHODS.POST, 54974 ]; 54975 exports.METHOD_MAP = utils_1.enumToMap(METHODS); 54976 exports.H_METHOD_MAP = {}; 54977 Object.keys(exports.METHOD_MAP).forEach((key) => { 54978 if (/^H/.test(key)) { 54979 exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; 54980 } 54981 }); 54982 var FINISH; 54983 (function (FINISH) { 54984 FINISH[FINISH["SAFE"] = 0] = "SAFE"; 54985 FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; 54986 FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; 54987 })(FINISH = exports.FINISH || (exports.FINISH = {})); 54988 exports.ALPHA = []; 54989 for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { 54990 // Upper case 54991 exports.ALPHA.push(String.fromCharCode(i)); 54992 // Lower case 54993 exports.ALPHA.push(String.fromCharCode(i + 0x20)); 54994 } 54995 exports.NUM_MAP = { 54996 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 54997 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 54998 }; 54999 exports.HEX_MAP = { 55000 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 55001 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 55002 A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, 55003 a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, 55004 }; 55005 exports.NUM = [ 55006 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 55007 ]; 55008 exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); 55009 exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; 55010 exports.USERINFO_CHARS = exports.ALPHANUM 55011 .concat(exports.MARK) 55012 .concat(['%', ';', ':', '&', '=', '+', '$', ',']); 55013 // TODO(indutny): use RFC 55014 exports.STRICT_URL_CHAR = [ 55015 '!', '"', '$', '%', '&', '\'', 55016 '(', ')', '*', '+', ',', '-', '.', '/', 55017 ':', ';', '<', '=', '>', 55018 '@', '[', '\\', ']', '^', '_', 55019 '`', 55020 '{', '|', '}', '~', 55021 ].concat(exports.ALPHANUM); 55022 exports.URL_CHAR = exports.STRICT_URL_CHAR 55023 .concat(['\t', '\f']); 55024 // All characters with 0x80 bit set to 1 55025 for (let i = 0x80; i <= 0xff; i++) { 55026 exports.URL_CHAR.push(i); 55027 } 55028 exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); 55029 /* Tokens as defined by rfc 2616. Also lowercases them. 55030 * token = 1*<any CHAR except CTLs or separators> 55031 * separators = "(" | ")" | "<" | ">" | "@" 55032 * | "," | ";" | ":" | "\" | <"> 55033 * | "/" | "[" | "]" | "?" | "=" 55034 * | "{" | "}" | SP | HT 55035 */ 55036 exports.STRICT_TOKEN = [ 55037 '!', '#', '$', '%', '&', '\'', 55038 '*', '+', '-', '.', 55039 '^', '_', '`', 55040 '|', '~', 55041 ].concat(exports.ALPHANUM); 55042 exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); 55043 /* 55044 * Verify that a char is a valid visible (printable) US-ASCII 55045 * character or %x80-FF 55046 */ 55047 exports.HEADER_CHARS = ['\t']; 55048 for (let i = 32; i <= 255; i++) { 55049 if (i !== 127) { 55050 exports.HEADER_CHARS.push(i); 55051 } 55052 } 55053 // ',' = \x44 55054 exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); 55055 exports.MAJOR = exports.NUM_MAP; 55056 exports.MINOR = exports.MAJOR; 55057 var HEADER_STATE; 55058 (function (HEADER_STATE) { 55059 HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; 55060 HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; 55061 HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; 55062 HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; 55063 HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; 55064 HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; 55065 HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; 55066 HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; 55067 HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; 55068 })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); 55069 exports.SPECIAL_HEADERS = { 55070 'connection': HEADER_STATE.CONNECTION, 55071 'content-length': HEADER_STATE.CONTENT_LENGTH, 55072 'proxy-connection': HEADER_STATE.CONNECTION, 55073 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, 55074 'upgrade': HEADER_STATE.UPGRADE, 55075 }; 55076 //# sourceMappingURL=constants.js.map 55077 55078 /***/ }), 55079 55080 /***/ 1145: 55081 /***/ ((module) => { 55082 55083 module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3Vw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EQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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AoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs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ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGj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CQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgI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MDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' 55092 55093 55094 /***/ }), 55095 55096 /***/ 1891: 55097 /***/ ((__unused_webpack_module, exports) => { 55098 55099 "use strict"; 55100 55101 Object.defineProperty(exports, "__esModule", ({ value: true })); 55102 exports.enumToMap = void 0; 55103 function enumToMap(obj) { 55104 const res = {}; 55105 Object.keys(obj).forEach((key) => { 55106 const value = obj[key]; 55107 if (typeof value === 'number') { 55108 res[key] = value; 55109 } 55110 }); 55111 return res; 55112 } 55113 exports.enumToMap = enumToMap; 55114 //# sourceMappingURL=utils.js.map 55115 55116 /***/ }), 55117 55118 /***/ 6771: 55119 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55120 55121 "use strict"; 55122 55123 55124 const { kClients } = __nccwpck_require__(2785) 55125 const Agent = __nccwpck_require__(7890) 55126 const { 55127 kAgent, 55128 kMockAgentSet, 55129 kMockAgentGet, 55130 kDispatches, 55131 kIsMockActive, 55132 kNetConnect, 55133 kGetNetConnect, 55134 kOptions, 55135 kFactory 55136 } = __nccwpck_require__(4347) 55137 const MockClient = __nccwpck_require__(8687) 55138 const MockPool = __nccwpck_require__(6193) 55139 const { matchValue, buildMockOptions } = __nccwpck_require__(9323) 55140 const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8045) 55141 const Dispatcher = __nccwpck_require__(412) 55142 const Pluralizer = __nccwpck_require__(8891) 55143 const PendingInterceptorsFormatter = __nccwpck_require__(6823) 55144 55145 class FakeWeakRef { 55146 constructor (value) { 55147 this.value = value 55148 } 55149 55150 deref () { 55151 return this.value 55152 } 55153 } 55154 55155 class MockAgent extends Dispatcher { 55156 constructor (opts) { 55157 super(opts) 55158 55159 this[kNetConnect] = true 55160 this[kIsMockActive] = true 55161 55162 // Instantiate Agent and encapsulate 55163 if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { 55164 throw new InvalidArgumentError('Argument opts.agent must implement Agent') 55165 } 55166 const agent = opts && opts.agent ? opts.agent : new Agent(opts) 55167 this[kAgent] = agent 55168 55169 this[kClients] = agent[kClients] 55170 this[kOptions] = buildMockOptions(opts) 55171 } 55172 55173 get (origin) { 55174 let dispatcher = this[kMockAgentGet](origin) 55175 55176 if (!dispatcher) { 55177 dispatcher = this[kFactory](origin) 55178 this[kMockAgentSet](origin, dispatcher) 55179 } 55180 return dispatcher 55181 } 55182 55183 dispatch (opts, handler) { 55184 // Call MockAgent.get to perform additional setup before dispatching as normal 55185 this.get(opts.origin) 55186 return this[kAgent].dispatch(opts, handler) 55187 } 55188 55189 async close () { 55190 await this[kAgent].close() 55191 this[kClients].clear() 55192 } 55193 55194 deactivate () { 55195 this[kIsMockActive] = false 55196 } 55197 55198 activate () { 55199 this[kIsMockActive] = true 55200 } 55201 55202 enableNetConnect (matcher) { 55203 if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { 55204 if (Array.isArray(this[kNetConnect])) { 55205 this[kNetConnect].push(matcher) 55206 } else { 55207 this[kNetConnect] = [matcher] 55208 } 55209 } else if (typeof matcher === 'undefined') { 55210 this[kNetConnect] = true 55211 } else { 55212 throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') 55213 } 55214 } 55215 55216 disableNetConnect () { 55217 this[kNetConnect] = false 55218 } 55219 55220 // This is required to bypass issues caused by using global symbols - see: 55221 // https://github.com/nodejs/undici/issues/1447 55222 get isMockActive () { 55223 return this[kIsMockActive] 55224 } 55225 55226 [kMockAgentSet] (origin, dispatcher) { 55227 this[kClients].set(origin, new FakeWeakRef(dispatcher)) 55228 } 55229 55230 [kFactory] (origin) { 55231 const mockOptions = Object.assign({ agent: this }, this[kOptions]) 55232 return this[kOptions] && this[kOptions].connections === 1 55233 ? new MockClient(origin, mockOptions) 55234 : new MockPool(origin, mockOptions) 55235 } 55236 55237 [kMockAgentGet] (origin) { 55238 // First check if we can immediately find it 55239 const ref = this[kClients].get(origin) 55240 if (ref) { 55241 return ref.deref() 55242 } 55243 55244 // If the origin is not a string create a dummy parent pool and return to user 55245 if (typeof origin !== 'string') { 55246 const dispatcher = this[kFactory]('http://localhost:9999') 55247 this[kMockAgentSet](origin, dispatcher) 55248 return dispatcher 55249 } 55250 55251 // If we match, create a pool and assign the same dispatches 55252 for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { 55253 const nonExplicitDispatcher = nonExplicitRef.deref() 55254 if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { 55255 const dispatcher = this[kFactory](origin) 55256 this[kMockAgentSet](origin, dispatcher) 55257 dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] 55258 return dispatcher 55259 } 55260 } 55261 } 55262 55263 [kGetNetConnect] () { 55264 return this[kNetConnect] 55265 } 55266 55267 pendingInterceptors () { 55268 const mockAgentClients = this[kClients] 55269 55270 return Array.from(mockAgentClients.entries()) 55271 .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) 55272 .filter(({ pending }) => pending) 55273 } 55274 55275 assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { 55276 const pending = this.pendingInterceptors() 55277 55278 if (pending.length === 0) { 55279 return 55280 } 55281 55282 const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) 55283 55284 throw new UndiciError(` 55285 ${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: 55286 55287 ${pendingInterceptorsFormatter.format(pending)} 55288 `.trim()) 55289 } 55290 } 55291 55292 module.exports = MockAgent 55293 55294 55295 /***/ }), 55296 55297 /***/ 8687: 55298 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55299 55300 "use strict"; 55301 55302 55303 const { promisify } = __nccwpck_require__(3837) 55304 const Client = __nccwpck_require__(3598) 55305 const { buildMockDispatch } = __nccwpck_require__(9323) 55306 const { 55307 kDispatches, 55308 kMockAgent, 55309 kClose, 55310 kOriginalClose, 55311 kOrigin, 55312 kOriginalDispatch, 55313 kConnected 55314 } = __nccwpck_require__(4347) 55315 const { MockInterceptor } = __nccwpck_require__(410) 55316 const Symbols = __nccwpck_require__(2785) 55317 const { InvalidArgumentError } = __nccwpck_require__(8045) 55318 55319 /** 55320 * MockClient provides an API that extends the Client to influence the mockDispatches. 55321 */ 55322 class MockClient extends Client { 55323 constructor (origin, opts) { 55324 super(origin, opts) 55325 55326 if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { 55327 throw new InvalidArgumentError('Argument opts.agent must implement Agent') 55328 } 55329 55330 this[kMockAgent] = opts.agent 55331 this[kOrigin] = origin 55332 this[kDispatches] = [] 55333 this[kConnected] = 1 55334 this[kOriginalDispatch] = this.dispatch 55335 this[kOriginalClose] = this.close.bind(this) 55336 55337 this.dispatch = buildMockDispatch.call(this) 55338 this.close = this[kClose] 55339 } 55340 55341 get [Symbols.kConnected] () { 55342 return this[kConnected] 55343 } 55344 55345 /** 55346 * Sets up the base interceptor for mocking replies from undici. 55347 */ 55348 intercept (opts) { 55349 return new MockInterceptor(opts, this[kDispatches]) 55350 } 55351 55352 async [kClose] () { 55353 await promisify(this[kOriginalClose])() 55354 this[kConnected] = 0 55355 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) 55356 } 55357 } 55358 55359 module.exports = MockClient 55360 55361 55362 /***/ }), 55363 55364 /***/ 888: 55365 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55366 55367 "use strict"; 55368 55369 55370 const { UndiciError } = __nccwpck_require__(8045) 55371 55372 class MockNotMatchedError extends UndiciError { 55373 constructor (message) { 55374 super(message) 55375 Error.captureStackTrace(this, MockNotMatchedError) 55376 this.name = 'MockNotMatchedError' 55377 this.message = message || 'The request does not match any registered mock dispatches' 55378 this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' 55379 } 55380 } 55381 55382 module.exports = { 55383 MockNotMatchedError 55384 } 55385 55386 55387 /***/ }), 55388 55389 /***/ 410: 55390 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55391 55392 "use strict"; 55393 55394 55395 const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(9323) 55396 const { 55397 kDispatches, 55398 kDispatchKey, 55399 kDefaultHeaders, 55400 kDefaultTrailers, 55401 kContentLength, 55402 kMockDispatch 55403 } = __nccwpck_require__(4347) 55404 const { InvalidArgumentError } = __nccwpck_require__(8045) 55405 const { buildURL } = __nccwpck_require__(3983) 55406 55407 /** 55408 * Defines the scope API for an interceptor reply 55409 */ 55410 class MockScope { 55411 constructor (mockDispatch) { 55412 this[kMockDispatch] = mockDispatch 55413 } 55414 55415 /** 55416 * Delay a reply by a set amount in ms. 55417 */ 55418 delay (waitInMs) { 55419 if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { 55420 throw new InvalidArgumentError('waitInMs must be a valid integer > 0') 55421 } 55422 55423 this[kMockDispatch].delay = waitInMs 55424 return this 55425 } 55426 55427 /** 55428 * For a defined reply, never mark as consumed. 55429 */ 55430 persist () { 55431 this[kMockDispatch].persist = true 55432 return this 55433 } 55434 55435 /** 55436 * Allow one to define a reply for a set amount of matching requests. 55437 */ 55438 times (repeatTimes) { 55439 if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { 55440 throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') 55441 } 55442 55443 this[kMockDispatch].times = repeatTimes 55444 return this 55445 } 55446 } 55447 55448 /** 55449 * Defines an interceptor for a Mock 55450 */ 55451 class MockInterceptor { 55452 constructor (opts, mockDispatches) { 55453 if (typeof opts !== 'object') { 55454 throw new InvalidArgumentError('opts must be an object') 55455 } 55456 if (typeof opts.path === 'undefined') { 55457 throw new InvalidArgumentError('opts.path must be defined') 55458 } 55459 if (typeof opts.method === 'undefined') { 55460 opts.method = 'GET' 55461 } 55462 // See https://github.com/nodejs/undici/issues/1245 55463 // As per RFC 3986, clients are not supposed to send URI 55464 // fragments to servers when they retrieve a document, 55465 if (typeof opts.path === 'string') { 55466 if (opts.query) { 55467 opts.path = buildURL(opts.path, opts.query) 55468 } else { 55469 // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 55470 const parsedURL = new URL(opts.path, 'data://') 55471 opts.path = parsedURL.pathname + parsedURL.search 55472 } 55473 } 55474 if (typeof opts.method === 'string') { 55475 opts.method = opts.method.toUpperCase() 55476 } 55477 55478 this[kDispatchKey] = buildKey(opts) 55479 this[kDispatches] = mockDispatches 55480 this[kDefaultHeaders] = {} 55481 this[kDefaultTrailers] = {} 55482 this[kContentLength] = false 55483 } 55484 55485 createMockScopeDispatchData (statusCode, data, responseOptions = {}) { 55486 const responseData = getResponseData(data) 55487 const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} 55488 const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } 55489 const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } 55490 55491 return { statusCode, data, headers, trailers } 55492 } 55493 55494 validateReplyParameters (statusCode, data, responseOptions) { 55495 if (typeof statusCode === 'undefined') { 55496 throw new InvalidArgumentError('statusCode must be defined') 55497 } 55498 if (typeof data === 'undefined') { 55499 throw new InvalidArgumentError('data must be defined') 55500 } 55501 if (typeof responseOptions !== 'object') { 55502 throw new InvalidArgumentError('responseOptions must be an object') 55503 } 55504 } 55505 55506 /** 55507 * Mock an undici request with a defined reply. 55508 */ 55509 reply (replyData) { 55510 // Values of reply aren't available right now as they 55511 // can only be available when the reply callback is invoked. 55512 if (typeof replyData === 'function') { 55513 // We'll first wrap the provided callback in another function, 55514 // this function will properly resolve the data from the callback 55515 // when invoked. 55516 const wrappedDefaultsCallback = (opts) => { 55517 // Our reply options callback contains the parameter for statusCode, data and options. 55518 const resolvedData = replyData(opts) 55519 55520 // Check if it is in the right format 55521 if (typeof resolvedData !== 'object') { 55522 throw new InvalidArgumentError('reply options callback must return an object') 55523 } 55524 55525 const { statusCode, data = '', responseOptions = {} } = resolvedData 55526 this.validateReplyParameters(statusCode, data, responseOptions) 55527 // Since the values can be obtained immediately we return them 55528 // from this higher order function that will be resolved later. 55529 return { 55530 ...this.createMockScopeDispatchData(statusCode, data, responseOptions) 55531 } 55532 } 55533 55534 // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. 55535 const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) 55536 return new MockScope(newMockDispatch) 55537 } 55538 55539 // We can have either one or three parameters, if we get here, 55540 // we should have 1-3 parameters. So we spread the arguments of 55541 // this function to obtain the parameters, since replyData will always 55542 // just be the statusCode. 55543 const [statusCode, data = '', responseOptions = {}] = [...arguments] 55544 this.validateReplyParameters(statusCode, data, responseOptions) 55545 55546 // Send in-already provided data like usual 55547 const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) 55548 const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) 55549 return new MockScope(newMockDispatch) 55550 } 55551 55552 /** 55553 * Mock an undici request with a defined error. 55554 */ 55555 replyWithError (error) { 55556 if (typeof error === 'undefined') { 55557 throw new InvalidArgumentError('error must be defined') 55558 } 55559 55560 const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) 55561 return new MockScope(newMockDispatch) 55562 } 55563 55564 /** 55565 * Set default reply headers on the interceptor for subsequent replies 55566 */ 55567 defaultReplyHeaders (headers) { 55568 if (typeof headers === 'undefined') { 55569 throw new InvalidArgumentError('headers must be defined') 55570 } 55571 55572 this[kDefaultHeaders] = headers 55573 return this 55574 } 55575 55576 /** 55577 * Set default reply trailers on the interceptor for subsequent replies 55578 */ 55579 defaultReplyTrailers (trailers) { 55580 if (typeof trailers === 'undefined') { 55581 throw new InvalidArgumentError('trailers must be defined') 55582 } 55583 55584 this[kDefaultTrailers] = trailers 55585 return this 55586 } 55587 55588 /** 55589 * Set reply content length header for replies on the interceptor 55590 */ 55591 replyContentLength () { 55592 this[kContentLength] = true 55593 return this 55594 } 55595 } 55596 55597 module.exports.MockInterceptor = MockInterceptor 55598 module.exports.MockScope = MockScope 55599 55600 55601 /***/ }), 55602 55603 /***/ 6193: 55604 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55605 55606 "use strict"; 55607 55608 55609 const { promisify } = __nccwpck_require__(3837) 55610 const Pool = __nccwpck_require__(4634) 55611 const { buildMockDispatch } = __nccwpck_require__(9323) 55612 const { 55613 kDispatches, 55614 kMockAgent, 55615 kClose, 55616 kOriginalClose, 55617 kOrigin, 55618 kOriginalDispatch, 55619 kConnected 55620 } = __nccwpck_require__(4347) 55621 const { MockInterceptor } = __nccwpck_require__(410) 55622 const Symbols = __nccwpck_require__(2785) 55623 const { InvalidArgumentError } = __nccwpck_require__(8045) 55624 55625 /** 55626 * MockPool provides an API that extends the Pool to influence the mockDispatches. 55627 */ 55628 class MockPool extends Pool { 55629 constructor (origin, opts) { 55630 super(origin, opts) 55631 55632 if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { 55633 throw new InvalidArgumentError('Argument opts.agent must implement Agent') 55634 } 55635 55636 this[kMockAgent] = opts.agent 55637 this[kOrigin] = origin 55638 this[kDispatches] = [] 55639 this[kConnected] = 1 55640 this[kOriginalDispatch] = this.dispatch 55641 this[kOriginalClose] = this.close.bind(this) 55642 55643 this.dispatch = buildMockDispatch.call(this) 55644 this.close = this[kClose] 55645 } 55646 55647 get [Symbols.kConnected] () { 55648 return this[kConnected] 55649 } 55650 55651 /** 55652 * Sets up the base interceptor for mocking replies from undici. 55653 */ 55654 intercept (opts) { 55655 return new MockInterceptor(opts, this[kDispatches]) 55656 } 55657 55658 async [kClose] () { 55659 await promisify(this[kOriginalClose])() 55660 this[kConnected] = 0 55661 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) 55662 } 55663 } 55664 55665 module.exports = MockPool 55666 55667 55668 /***/ }), 55669 55670 /***/ 4347: 55671 /***/ ((module) => { 55672 55673 "use strict"; 55674 55675 55676 module.exports = { 55677 kAgent: Symbol('agent'), 55678 kOptions: Symbol('options'), 55679 kFactory: Symbol('factory'), 55680 kDispatches: Symbol('dispatches'), 55681 kDispatchKey: Symbol('dispatch key'), 55682 kDefaultHeaders: Symbol('default headers'), 55683 kDefaultTrailers: Symbol('default trailers'), 55684 kContentLength: Symbol('content length'), 55685 kMockAgent: Symbol('mock agent'), 55686 kMockAgentSet: Symbol('mock agent set'), 55687 kMockAgentGet: Symbol('mock agent get'), 55688 kMockDispatch: Symbol('mock dispatch'), 55689 kClose: Symbol('close'), 55690 kOriginalClose: Symbol('original agent close'), 55691 kOrigin: Symbol('origin'), 55692 kIsMockActive: Symbol('is mock active'), 55693 kNetConnect: Symbol('net connect'), 55694 kGetNetConnect: Symbol('get net connect'), 55695 kConnected: Symbol('connected') 55696 } 55697 55698 55699 /***/ }), 55700 55701 /***/ 9323: 55702 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 55703 55704 "use strict"; 55705 55706 55707 const { MockNotMatchedError } = __nccwpck_require__(888) 55708 const { 55709 kDispatches, 55710 kMockAgent, 55711 kOriginalDispatch, 55712 kOrigin, 55713 kGetNetConnect 55714 } = __nccwpck_require__(4347) 55715 const { buildURL, nop } = __nccwpck_require__(3983) 55716 const { STATUS_CODES } = __nccwpck_require__(3685) 55717 const { 55718 types: { 55719 isPromise 55720 } 55721 } = __nccwpck_require__(3837) 55722 55723 function matchValue (match, value) { 55724 if (typeof match === 'string') { 55725 return match === value 55726 } 55727 if (match instanceof RegExp) { 55728 return match.test(value) 55729 } 55730 if (typeof match === 'function') { 55731 return match(value) === true 55732 } 55733 return false 55734 } 55735 55736 function lowerCaseEntries (headers) { 55737 return Object.fromEntries( 55738 Object.entries(headers).map(([headerName, headerValue]) => { 55739 return [headerName.toLocaleLowerCase(), headerValue] 55740 }) 55741 ) 55742 } 55743 55744 /** 55745 * @param {import('../../index').Headers|string[]|Record<string, string>} headers 55746 * @param {string} key 55747 */ 55748 function getHeaderByName (headers, key) { 55749 if (Array.isArray(headers)) { 55750 for (let i = 0; i < headers.length; i += 2) { 55751 if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { 55752 return headers[i + 1] 55753 } 55754 } 55755 55756 return undefined 55757 } else if (typeof headers.get === 'function') { 55758 return headers.get(key) 55759 } else { 55760 return lowerCaseEntries(headers)[key.toLocaleLowerCase()] 55761 } 55762 } 55763 55764 /** @param {string[]} headers */ 55765 function buildHeadersFromArray (headers) { // fetch HeadersList 55766 const clone = headers.slice() 55767 const entries = [] 55768 for (let index = 0; index < clone.length; index += 2) { 55769 entries.push([clone[index], clone[index + 1]]) 55770 } 55771 return Object.fromEntries(entries) 55772 } 55773 55774 function matchHeaders (mockDispatch, headers) { 55775 if (typeof mockDispatch.headers === 'function') { 55776 if (Array.isArray(headers)) { // fetch HeadersList 55777 headers = buildHeadersFromArray(headers) 55778 } 55779 return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) 55780 } 55781 if (typeof mockDispatch.headers === 'undefined') { 55782 return true 55783 } 55784 if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { 55785 return false 55786 } 55787 55788 for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { 55789 const headerValue = getHeaderByName(headers, matchHeaderName) 55790 55791 if (!matchValue(matchHeaderValue, headerValue)) { 55792 return false 55793 } 55794 } 55795 return true 55796 } 55797 55798 function safeUrl (path) { 55799 if (typeof path !== 'string') { 55800 return path 55801 } 55802 55803 const pathSegments = path.split('?') 55804 55805 if (pathSegments.length !== 2) { 55806 return path 55807 } 55808 55809 const qp = new URLSearchParams(pathSegments.pop()) 55810 qp.sort() 55811 return [...pathSegments, qp.toString()].join('?') 55812 } 55813 55814 function matchKey (mockDispatch, { path, method, body, headers }) { 55815 const pathMatch = matchValue(mockDispatch.path, path) 55816 const methodMatch = matchValue(mockDispatch.method, method) 55817 const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true 55818 const headersMatch = matchHeaders(mockDispatch, headers) 55819 return pathMatch && methodMatch && bodyMatch && headersMatch 55820 } 55821 55822 function getResponseData (data) { 55823 if (Buffer.isBuffer(data)) { 55824 return data 55825 } else if (typeof data === 'object') { 55826 return JSON.stringify(data) 55827 } else { 55828 return data.toString() 55829 } 55830 } 55831 55832 function getMockDispatch (mockDispatches, key) { 55833 const basePath = key.query ? buildURL(key.path, key.query) : key.path 55834 const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath 55835 55836 // Match path 55837 let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) 55838 if (matchedMockDispatches.length === 0) { 55839 throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) 55840 } 55841 55842 // Match method 55843 matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) 55844 if (matchedMockDispatches.length === 0) { 55845 throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) 55846 } 55847 55848 // Match body 55849 matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) 55850 if (matchedMockDispatches.length === 0) { 55851 throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) 55852 } 55853 55854 // Match headers 55855 matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) 55856 if (matchedMockDispatches.length === 0) { 55857 throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) 55858 } 55859 55860 return matchedMockDispatches[0] 55861 } 55862 55863 function addMockDispatch (mockDispatches, key, data) { 55864 const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } 55865 const replyData = typeof data === 'function' ? { callback: data } : { ...data } 55866 const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } 55867 mockDispatches.push(newMockDispatch) 55868 return newMockDispatch 55869 } 55870 55871 function deleteMockDispatch (mockDispatches, key) { 55872 const index = mockDispatches.findIndex(dispatch => { 55873 if (!dispatch.consumed) { 55874 return false 55875 } 55876 return matchKey(dispatch, key) 55877 }) 55878 if (index !== -1) { 55879 mockDispatches.splice(index, 1) 55880 } 55881 } 55882 55883 function buildKey (opts) { 55884 const { path, method, body, headers, query } = opts 55885 return { 55886 path, 55887 method, 55888 body, 55889 headers, 55890 query 55891 } 55892 } 55893 55894 function generateKeyValues (data) { 55895 return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ 55896 ...keyValuePairs, 55897 Buffer.from(`${key}`), 55898 Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) 55899 ], []) 55900 } 55901 55902 /** 55903 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status 55904 * @param {number} statusCode 55905 */ 55906 function getStatusText (statusCode) { 55907 return STATUS_CODES[statusCode] || 'unknown' 55908 } 55909 55910 async function getResponse (body) { 55911 const buffers = [] 55912 for await (const data of body) { 55913 buffers.push(data) 55914 } 55915 return Buffer.concat(buffers).toString('utf8') 55916 } 55917 55918 /** 55919 * Mock dispatch function used to simulate undici dispatches 55920 */ 55921 function mockDispatch (opts, handler) { 55922 // Get mock dispatch from built key 55923 const key = buildKey(opts) 55924 const mockDispatch = getMockDispatch(this[kDispatches], key) 55925 55926 mockDispatch.timesInvoked++ 55927 55928 // Here's where we resolve a callback if a callback is present for the dispatch data. 55929 if (mockDispatch.data.callback) { 55930 mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } 55931 } 55932 55933 // Parse mockDispatch data 55934 const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch 55935 const { timesInvoked, times } = mockDispatch 55936 55937 // If it's used up and not persistent, mark as consumed 55938 mockDispatch.consumed = !persist && timesInvoked >= times 55939 mockDispatch.pending = timesInvoked < times 55940 55941 // If specified, trigger dispatch error 55942 if (error !== null) { 55943 deleteMockDispatch(this[kDispatches], key) 55944 handler.onError(error) 55945 return true 55946 } 55947 55948 // Handle the request with a delay if necessary 55949 if (typeof delay === 'number' && delay > 0) { 55950 setTimeout(() => { 55951 handleReply(this[kDispatches]) 55952 }, delay) 55953 } else { 55954 handleReply(this[kDispatches]) 55955 } 55956 55957 function handleReply (mockDispatches, _data = data) { 55958 // fetch's HeadersList is a 1D string array 55959 const optsHeaders = Array.isArray(opts.headers) 55960 ? buildHeadersFromArray(opts.headers) 55961 : opts.headers 55962 const body = typeof _data === 'function' 55963 ? _data({ ...opts, headers: optsHeaders }) 55964 : _data 55965 55966 // util.types.isPromise is likely needed for jest. 55967 if (isPromise(body)) { 55968 // If handleReply is asynchronous, throwing an error 55969 // in the callback will reject the promise, rather than 55970 // synchronously throw the error, which breaks some tests. 55971 // Rather, we wait for the callback to resolve if it is a 55972 // promise, and then re-run handleReply with the new body. 55973 body.then((newData) => handleReply(mockDispatches, newData)) 55974 return 55975 } 55976 55977 const responseData = getResponseData(body) 55978 const responseHeaders = generateKeyValues(headers) 55979 const responseTrailers = generateKeyValues(trailers) 55980 55981 handler.abort = nop 55982 handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) 55983 handler.onData(Buffer.from(responseData)) 55984 handler.onComplete(responseTrailers) 55985 deleteMockDispatch(mockDispatches, key) 55986 } 55987 55988 function resume () {} 55989 55990 return true 55991 } 55992 55993 function buildMockDispatch () { 55994 const agent = this[kMockAgent] 55995 const origin = this[kOrigin] 55996 const originalDispatch = this[kOriginalDispatch] 55997 55998 return function dispatch (opts, handler) { 55999 if (agent.isMockActive) { 56000 try { 56001 mockDispatch.call(this, opts, handler) 56002 } catch (error) { 56003 if (error instanceof MockNotMatchedError) { 56004 const netConnect = agent[kGetNetConnect]() 56005 if (netConnect === false) { 56006 throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) 56007 } 56008 if (checkNetConnect(netConnect, origin)) { 56009 originalDispatch.call(this, opts, handler) 56010 } else { 56011 throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) 56012 } 56013 } else { 56014 throw error 56015 } 56016 } 56017 } else { 56018 originalDispatch.call(this, opts, handler) 56019 } 56020 } 56021 } 56022 56023 function checkNetConnect (netConnect, origin) { 56024 const url = new URL(origin) 56025 if (netConnect === true) { 56026 return true 56027 } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { 56028 return true 56029 } 56030 return false 56031 } 56032 56033 function buildMockOptions (opts) { 56034 if (opts) { 56035 const { agent, ...mockOptions } = opts 56036 return mockOptions 56037 } 56038 } 56039 56040 module.exports = { 56041 getResponseData, 56042 getMockDispatch, 56043 addMockDispatch, 56044 deleteMockDispatch, 56045 buildKey, 56046 generateKeyValues, 56047 matchValue, 56048 getResponse, 56049 getStatusText, 56050 mockDispatch, 56051 buildMockDispatch, 56052 checkNetConnect, 56053 buildMockOptions, 56054 getHeaderByName 56055 } 56056 56057 56058 /***/ }), 56059 56060 /***/ 6823: 56061 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56062 56063 "use strict"; 56064 56065 56066 const { Transform } = __nccwpck_require__(2781) 56067 const { Console } = __nccwpck_require__(6206) 56068 56069 /** 56070 * Gets the output of `console.table(…)` as a string. 56071 */ 56072 module.exports = class PendingInterceptorsFormatter { 56073 constructor ({ disableColors } = {}) { 56074 this.transform = new Transform({ 56075 transform (chunk, _enc, cb) { 56076 cb(null, chunk) 56077 } 56078 }) 56079 56080 this.logger = new Console({ 56081 stdout: this.transform, 56082 inspectOptions: { 56083 colors: !disableColors && !process.env.CI 56084 } 56085 }) 56086 } 56087 56088 format (pendingInterceptors) { 56089 const withPrettyHeaders = pendingInterceptors.map( 56090 ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ 56091 Method: method, 56092 Origin: origin, 56093 Path: path, 56094 'Status code': statusCode, 56095 Persistent: persist ? '✅' : '❌', 56096 Invocations: timesInvoked, 56097 Remaining: persist ? Infinity : times - timesInvoked 56098 })) 56099 56100 this.logger.table(withPrettyHeaders) 56101 return this.transform.read().toString() 56102 } 56103 } 56104 56105 56106 /***/ }), 56107 56108 /***/ 8891: 56109 /***/ ((module) => { 56110 56111 "use strict"; 56112 56113 56114 const singulars = { 56115 pronoun: 'it', 56116 is: 'is', 56117 was: 'was', 56118 this: 'this' 56119 } 56120 56121 const plurals = { 56122 pronoun: 'they', 56123 is: 'are', 56124 was: 'were', 56125 this: 'these' 56126 } 56127 56128 module.exports = class Pluralizer { 56129 constructor (singular, plural) { 56130 this.singular = singular 56131 this.plural = plural 56132 } 56133 56134 pluralize (count) { 56135 const one = count === 1 56136 const keys = one ? singulars : plurals 56137 const noun = one ? this.singular : this.plural 56138 return { ...keys, count, noun } 56139 } 56140 } 56141 56142 56143 /***/ }), 56144 56145 /***/ 8266: 56146 /***/ ((module) => { 56147 56148 "use strict"; 56149 /* eslint-disable */ 56150 56151 56152 56153 // Extracted from node/lib/internal/fixed_queue.js 56154 56155 // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. 56156 const kSize = 2048; 56157 const kMask = kSize - 1; 56158 56159 // The FixedQueue is implemented as a singly-linked list of fixed-size 56160 // circular buffers. It looks something like this: 56161 // 56162 // head tail 56163 // | | 56164 // v v 56165 // +-----------+ <-----\ +-----------+ <------\ +-----------+ 56166 // | [null] | \----- | next | \------- | next | 56167 // +-----------+ +-----------+ +-----------+ 56168 // | item | <-- bottom | item | <-- bottom | [empty] | 56169 // | item | | item | | [empty] | 56170 // | item | | item | | [empty] | 56171 // | item | | item | | [empty] | 56172 // | item | | item | bottom --> | item | 56173 // | item | | item | | item | 56174 // | ... | | ... | | ... | 56175 // | item | | item | | item | 56176 // | item | | item | | item | 56177 // | [empty] | <-- top | item | | item | 56178 // | [empty] | | item | | item | 56179 // | [empty] | | [empty] | <-- top top --> | [empty] | 56180 // +-----------+ +-----------+ +-----------+ 56181 // 56182 // Or, if there is only one circular buffer, it looks something 56183 // like either of these: 56184 // 56185 // head tail head tail 56186 // | | | | 56187 // v v v v 56188 // +-----------+ +-----------+ 56189 // | [null] | | [null] | 56190 // +-----------+ +-----------+ 56191 // | [empty] | | item | 56192 // | [empty] | | item | 56193 // | item | <-- bottom top --> | [empty] | 56194 // | item | | [empty] | 56195 // | [empty] | <-- top bottom --> | item | 56196 // | [empty] | | item | 56197 // +-----------+ +-----------+ 56198 // 56199 // Adding a value means moving `top` forward by one, removing means 56200 // moving `bottom` forward by one. After reaching the end, the queue 56201 // wraps around. 56202 // 56203 // When `top === bottom` the current queue is empty and when 56204 // `top + 1 === bottom` it's full. This wastes a single space of storage 56205 // but allows much quicker checks. 56206 56207 class FixedCircularBuffer { 56208 constructor() { 56209 this.bottom = 0; 56210 this.top = 0; 56211 this.list = new Array(kSize); 56212 this.next = null; 56213 } 56214 56215 isEmpty() { 56216 return this.top === this.bottom; 56217 } 56218 56219 isFull() { 56220 return ((this.top + 1) & kMask) === this.bottom; 56221 } 56222 56223 push(data) { 56224 this.list[this.top] = data; 56225 this.top = (this.top + 1) & kMask; 56226 } 56227 56228 shift() { 56229 const nextItem = this.list[this.bottom]; 56230 if (nextItem === undefined) 56231 return null; 56232 this.list[this.bottom] = undefined; 56233 this.bottom = (this.bottom + 1) & kMask; 56234 return nextItem; 56235 } 56236 } 56237 56238 module.exports = class FixedQueue { 56239 constructor() { 56240 this.head = this.tail = new FixedCircularBuffer(); 56241 } 56242 56243 isEmpty() { 56244 return this.head.isEmpty(); 56245 } 56246 56247 push(data) { 56248 if (this.head.isFull()) { 56249 // Head is full: Creates a new queue, sets the old queue's `.next` to it, 56250 // and sets it as the new main queue. 56251 this.head = this.head.next = new FixedCircularBuffer(); 56252 } 56253 this.head.push(data); 56254 } 56255 56256 shift() { 56257 const tail = this.tail; 56258 const next = tail.shift(); 56259 if (tail.isEmpty() && tail.next !== null) { 56260 // If there is another queue, it forms the new tail. 56261 this.tail = tail.next; 56262 } 56263 return next; 56264 } 56265 }; 56266 56267 56268 /***/ }), 56269 56270 /***/ 3198: 56271 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56272 56273 "use strict"; 56274 56275 56276 const DispatcherBase = __nccwpck_require__(4839) 56277 const FixedQueue = __nccwpck_require__(8266) 56278 const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(2785) 56279 const PoolStats = __nccwpck_require__(9689) 56280 56281 const kClients = Symbol('clients') 56282 const kNeedDrain = Symbol('needDrain') 56283 const kQueue = Symbol('queue') 56284 const kClosedResolve = Symbol('closed resolve') 56285 const kOnDrain = Symbol('onDrain') 56286 const kOnConnect = Symbol('onConnect') 56287 const kOnDisconnect = Symbol('onDisconnect') 56288 const kOnConnectionError = Symbol('onConnectionError') 56289 const kGetDispatcher = Symbol('get dispatcher') 56290 const kAddClient = Symbol('add client') 56291 const kRemoveClient = Symbol('remove client') 56292 const kStats = Symbol('stats') 56293 56294 class PoolBase extends DispatcherBase { 56295 constructor () { 56296 super() 56297 56298 this[kQueue] = new FixedQueue() 56299 this[kClients] = [] 56300 this[kQueued] = 0 56301 56302 const pool = this 56303 56304 this[kOnDrain] = function onDrain (origin, targets) { 56305 const queue = pool[kQueue] 56306 56307 let needDrain = false 56308 56309 while (!needDrain) { 56310 const item = queue.shift() 56311 if (!item) { 56312 break 56313 } 56314 pool[kQueued]-- 56315 needDrain = !this.dispatch(item.opts, item.handler) 56316 } 56317 56318 this[kNeedDrain] = needDrain 56319 56320 if (!this[kNeedDrain] && pool[kNeedDrain]) { 56321 pool[kNeedDrain] = false 56322 pool.emit('drain', origin, [pool, ...targets]) 56323 } 56324 56325 if (pool[kClosedResolve] && queue.isEmpty()) { 56326 Promise 56327 .all(pool[kClients].map(c => c.close())) 56328 .then(pool[kClosedResolve]) 56329 } 56330 } 56331 56332 this[kOnConnect] = (origin, targets) => { 56333 pool.emit('connect', origin, [pool, ...targets]) 56334 } 56335 56336 this[kOnDisconnect] = (origin, targets, err) => { 56337 pool.emit('disconnect', origin, [pool, ...targets], err) 56338 } 56339 56340 this[kOnConnectionError] = (origin, targets, err) => { 56341 pool.emit('connectionError', origin, [pool, ...targets], err) 56342 } 56343 56344 this[kStats] = new PoolStats(this) 56345 } 56346 56347 get [kBusy] () { 56348 return this[kNeedDrain] 56349 } 56350 56351 get [kConnected] () { 56352 return this[kClients].filter(client => client[kConnected]).length 56353 } 56354 56355 get [kFree] () { 56356 return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length 56357 } 56358 56359 get [kPending] () { 56360 let ret = this[kQueued] 56361 for (const { [kPending]: pending } of this[kClients]) { 56362 ret += pending 56363 } 56364 return ret 56365 } 56366 56367 get [kRunning] () { 56368 let ret = 0 56369 for (const { [kRunning]: running } of this[kClients]) { 56370 ret += running 56371 } 56372 return ret 56373 } 56374 56375 get [kSize] () { 56376 let ret = this[kQueued] 56377 for (const { [kSize]: size } of this[kClients]) { 56378 ret += size 56379 } 56380 return ret 56381 } 56382 56383 get stats () { 56384 return this[kStats] 56385 } 56386 56387 async [kClose] () { 56388 if (this[kQueue].isEmpty()) { 56389 return Promise.all(this[kClients].map(c => c.close())) 56390 } else { 56391 return new Promise((resolve) => { 56392 this[kClosedResolve] = resolve 56393 }) 56394 } 56395 } 56396 56397 async [kDestroy] (err) { 56398 while (true) { 56399 const item = this[kQueue].shift() 56400 if (!item) { 56401 break 56402 } 56403 item.handler.onError(err) 56404 } 56405 56406 return Promise.all(this[kClients].map(c => c.destroy(err))) 56407 } 56408 56409 [kDispatch] (opts, handler) { 56410 const dispatcher = this[kGetDispatcher]() 56411 56412 if (!dispatcher) { 56413 this[kNeedDrain] = true 56414 this[kQueue].push({ opts, handler }) 56415 this[kQueued]++ 56416 } else if (!dispatcher.dispatch(opts, handler)) { 56417 dispatcher[kNeedDrain] = true 56418 this[kNeedDrain] = !this[kGetDispatcher]() 56419 } 56420 56421 return !this[kNeedDrain] 56422 } 56423 56424 [kAddClient] (client) { 56425 client 56426 .on('drain', this[kOnDrain]) 56427 .on('connect', this[kOnConnect]) 56428 .on('disconnect', this[kOnDisconnect]) 56429 .on('connectionError', this[kOnConnectionError]) 56430 56431 this[kClients].push(client) 56432 56433 if (this[kNeedDrain]) { 56434 process.nextTick(() => { 56435 if (this[kNeedDrain]) { 56436 this[kOnDrain](client[kUrl], [this, client]) 56437 } 56438 }) 56439 } 56440 56441 return this 56442 } 56443 56444 [kRemoveClient] (client) { 56445 client.close(() => { 56446 const idx = this[kClients].indexOf(client) 56447 if (idx !== -1) { 56448 this[kClients].splice(idx, 1) 56449 } 56450 }) 56451 56452 this[kNeedDrain] = this[kClients].some(dispatcher => ( 56453 !dispatcher[kNeedDrain] && 56454 dispatcher.closed !== true && 56455 dispatcher.destroyed !== true 56456 )) 56457 } 56458 } 56459 56460 module.exports = { 56461 PoolBase, 56462 kClients, 56463 kNeedDrain, 56464 kAddClient, 56465 kRemoveClient, 56466 kGetDispatcher 56467 } 56468 56469 56470 /***/ }), 56471 56472 /***/ 9689: 56473 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56474 56475 const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(2785) 56476 const kPool = Symbol('pool') 56477 56478 class PoolStats { 56479 constructor (pool) { 56480 this[kPool] = pool 56481 } 56482 56483 get connected () { 56484 return this[kPool][kConnected] 56485 } 56486 56487 get free () { 56488 return this[kPool][kFree] 56489 } 56490 56491 get pending () { 56492 return this[kPool][kPending] 56493 } 56494 56495 get queued () { 56496 return this[kPool][kQueued] 56497 } 56498 56499 get running () { 56500 return this[kPool][kRunning] 56501 } 56502 56503 get size () { 56504 return this[kPool][kSize] 56505 } 56506 } 56507 56508 module.exports = PoolStats 56509 56510 56511 /***/ }), 56512 56513 /***/ 4634: 56514 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56515 56516 "use strict"; 56517 56518 56519 const { 56520 PoolBase, 56521 kClients, 56522 kNeedDrain, 56523 kAddClient, 56524 kGetDispatcher 56525 } = __nccwpck_require__(3198) 56526 const Client = __nccwpck_require__(3598) 56527 const { 56528 InvalidArgumentError 56529 } = __nccwpck_require__(8045) 56530 const util = __nccwpck_require__(3983) 56531 const { kUrl, kInterceptors } = __nccwpck_require__(2785) 56532 const buildConnector = __nccwpck_require__(2067) 56533 56534 const kOptions = Symbol('options') 56535 const kConnections = Symbol('connections') 56536 const kFactory = Symbol('factory') 56537 56538 function defaultFactory (origin, opts) { 56539 return new Client(origin, opts) 56540 } 56541 56542 class Pool extends PoolBase { 56543 constructor (origin, { 56544 connections, 56545 factory = defaultFactory, 56546 connect, 56547 connectTimeout, 56548 tls, 56549 maxCachedSessions, 56550 socketPath, 56551 autoSelectFamily, 56552 autoSelectFamilyAttemptTimeout, 56553 allowH2, 56554 ...options 56555 } = {}) { 56556 super() 56557 56558 if (connections != null && (!Number.isFinite(connections) || connections < 0)) { 56559 throw new InvalidArgumentError('invalid connections') 56560 } 56561 56562 if (typeof factory !== 'function') { 56563 throw new InvalidArgumentError('factory must be a function.') 56564 } 56565 56566 if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { 56567 throw new InvalidArgumentError('connect must be a function or an object') 56568 } 56569 56570 if (typeof connect !== 'function') { 56571 connect = buildConnector({ 56572 ...tls, 56573 maxCachedSessions, 56574 allowH2, 56575 socketPath, 56576 timeout: connectTimeout, 56577 ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), 56578 ...connect 56579 }) 56580 } 56581 56582 this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) 56583 ? options.interceptors.Pool 56584 : [] 56585 this[kConnections] = connections || null 56586 this[kUrl] = util.parseOrigin(origin) 56587 this[kOptions] = { ...util.deepClone(options), connect, allowH2 } 56588 this[kOptions].interceptors = options.interceptors 56589 ? { ...options.interceptors } 56590 : undefined 56591 this[kFactory] = factory 56592 } 56593 56594 [kGetDispatcher] () { 56595 let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) 56596 56597 if (dispatcher) { 56598 return dispatcher 56599 } 56600 56601 if (!this[kConnections] || this[kClients].length < this[kConnections]) { 56602 dispatcher = this[kFactory](this[kUrl], this[kOptions]) 56603 this[kAddClient](dispatcher) 56604 } 56605 56606 return dispatcher 56607 } 56608 } 56609 56610 module.exports = Pool 56611 56612 56613 /***/ }), 56614 56615 /***/ 7858: 56616 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56617 56618 "use strict"; 56619 56620 56621 const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(2785) 56622 const { URL } = __nccwpck_require__(7310) 56623 const Agent = __nccwpck_require__(7890) 56624 const Pool = __nccwpck_require__(4634) 56625 const DispatcherBase = __nccwpck_require__(4839) 56626 const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8045) 56627 const buildConnector = __nccwpck_require__(2067) 56628 56629 const kAgent = Symbol('proxy agent') 56630 const kClient = Symbol('proxy client') 56631 const kProxyHeaders = Symbol('proxy headers') 56632 const kRequestTls = Symbol('request tls settings') 56633 const kProxyTls = Symbol('proxy tls settings') 56634 const kConnectEndpoint = Symbol('connect endpoint function') 56635 56636 function defaultProtocolPort (protocol) { 56637 return protocol === 'https:' ? 443 : 80 56638 } 56639 56640 function buildProxyOptions (opts) { 56641 if (typeof opts === 'string') { 56642 opts = { uri: opts } 56643 } 56644 56645 if (!opts || !opts.uri) { 56646 throw new InvalidArgumentError('Proxy opts.uri is mandatory') 56647 } 56648 56649 return { 56650 uri: opts.uri, 56651 protocol: opts.protocol || 'https' 56652 } 56653 } 56654 56655 function defaultFactory (origin, opts) { 56656 return new Pool(origin, opts) 56657 } 56658 56659 class ProxyAgent extends DispatcherBase { 56660 constructor (opts) { 56661 super(opts) 56662 this[kProxy] = buildProxyOptions(opts) 56663 this[kAgent] = new Agent(opts) 56664 this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) 56665 ? opts.interceptors.ProxyAgent 56666 : [] 56667 56668 if (typeof opts === 'string') { 56669 opts = { uri: opts } 56670 } 56671 56672 if (!opts || !opts.uri) { 56673 throw new InvalidArgumentError('Proxy opts.uri is mandatory') 56674 } 56675 56676 const { clientFactory = defaultFactory } = opts 56677 56678 if (typeof clientFactory !== 'function') { 56679 throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') 56680 } 56681 56682 this[kRequestTls] = opts.requestTls 56683 this[kProxyTls] = opts.proxyTls 56684 this[kProxyHeaders] = opts.headers || {} 56685 56686 const resolvedUrl = new URL(opts.uri) 56687 const { origin, port, host, username, password } = resolvedUrl 56688 56689 if (opts.auth && opts.token) { 56690 throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') 56691 } else if (opts.auth) { 56692 /* @deprecated in favour of opts.token */ 56693 this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` 56694 } else if (opts.token) { 56695 this[kProxyHeaders]['proxy-authorization'] = opts.token 56696 } else if (username && password) { 56697 this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` 56698 } 56699 56700 const connect = buildConnector({ ...opts.proxyTls }) 56701 this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) 56702 this[kClient] = clientFactory(resolvedUrl, { connect }) 56703 this[kAgent] = new Agent({ 56704 ...opts, 56705 connect: async (opts, callback) => { 56706 let requestedHost = opts.host 56707 if (!opts.port) { 56708 requestedHost += `:${defaultProtocolPort(opts.protocol)}` 56709 } 56710 try { 56711 const { socket, statusCode } = await this[kClient].connect({ 56712 origin, 56713 port, 56714 path: requestedHost, 56715 signal: opts.signal, 56716 headers: { 56717 ...this[kProxyHeaders], 56718 host 56719 } 56720 }) 56721 if (statusCode !== 200) { 56722 socket.on('error', () => {}).destroy() 56723 callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) 56724 } 56725 if (opts.protocol !== 'https:') { 56726 callback(null, socket) 56727 return 56728 } 56729 let servername 56730 if (this[kRequestTls]) { 56731 servername = this[kRequestTls].servername 56732 } else { 56733 servername = opts.servername 56734 } 56735 this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) 56736 } catch (err) { 56737 callback(err) 56738 } 56739 } 56740 }) 56741 } 56742 56743 dispatch (opts, handler) { 56744 const { host } = new URL(opts.origin) 56745 const headers = buildHeaders(opts.headers) 56746 throwIfProxyAuthIsSent(headers) 56747 return this[kAgent].dispatch( 56748 { 56749 ...opts, 56750 headers: { 56751 ...headers, 56752 host 56753 } 56754 }, 56755 handler 56756 ) 56757 } 56758 56759 async [kClose] () { 56760 await this[kAgent].close() 56761 await this[kClient].close() 56762 } 56763 56764 async [kDestroy] () { 56765 await this[kAgent].destroy() 56766 await this[kClient].destroy() 56767 } 56768 } 56769 56770 /** 56771 * @param {string[] | Record<string, string>} headers 56772 * @returns {Record<string, string>} 56773 */ 56774 function buildHeaders (headers) { 56775 // When using undici.fetch, the headers list is stored 56776 // as an array. 56777 if (Array.isArray(headers)) { 56778 /** @type {Record<string, string>} */ 56779 const headersPair = {} 56780 56781 for (let i = 0; i < headers.length; i += 2) { 56782 headersPair[headers[i]] = headers[i + 1] 56783 } 56784 56785 return headersPair 56786 } 56787 56788 return headers 56789 } 56790 56791 /** 56792 * @param {Record<string, string>} headers 56793 * 56794 * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers 56795 * Nevertheless, it was changed and to avoid a security vulnerability by end users 56796 * this check was created. 56797 * It should be removed in the next major version for performance reasons 56798 */ 56799 function throwIfProxyAuthIsSent (headers) { 56800 const existProxyAuth = headers && Object.keys(headers) 56801 .find((key) => key.toLowerCase() === 'proxy-authorization') 56802 if (existProxyAuth) { 56803 throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') 56804 } 56805 } 56806 56807 module.exports = ProxyAgent 56808 56809 56810 /***/ }), 56811 56812 /***/ 9459: 56813 /***/ ((module) => { 56814 56815 "use strict"; 56816 56817 56818 let fastNow = Date.now() 56819 let fastNowTimeout 56820 56821 const fastTimers = [] 56822 56823 function onTimeout () { 56824 fastNow = Date.now() 56825 56826 let len = fastTimers.length 56827 let idx = 0 56828 while (idx < len) { 56829 const timer = fastTimers[idx] 56830 56831 if (timer.state === 0) { 56832 timer.state = fastNow + timer.delay 56833 } else if (timer.state > 0 && fastNow >= timer.state) { 56834 timer.state = -1 56835 timer.callback(timer.opaque) 56836 } 56837 56838 if (timer.state === -1) { 56839 timer.state = -2 56840 if (idx !== len - 1) { 56841 fastTimers[idx] = fastTimers.pop() 56842 } else { 56843 fastTimers.pop() 56844 } 56845 len -= 1 56846 } else { 56847 idx += 1 56848 } 56849 } 56850 56851 if (fastTimers.length > 0) { 56852 refreshTimeout() 56853 } 56854 } 56855 56856 function refreshTimeout () { 56857 if (fastNowTimeout && fastNowTimeout.refresh) { 56858 fastNowTimeout.refresh() 56859 } else { 56860 clearTimeout(fastNowTimeout) 56861 fastNowTimeout = setTimeout(onTimeout, 1e3) 56862 if (fastNowTimeout.unref) { 56863 fastNowTimeout.unref() 56864 } 56865 } 56866 } 56867 56868 class Timeout { 56869 constructor (callback, delay, opaque) { 56870 this.callback = callback 56871 this.delay = delay 56872 this.opaque = opaque 56873 56874 // -2 not in timer list 56875 // -1 in timer list but inactive 56876 // 0 in timer list waiting for time 56877 // > 0 in timer list waiting for time to expire 56878 this.state = -2 56879 56880 this.refresh() 56881 } 56882 56883 refresh () { 56884 if (this.state === -2) { 56885 fastTimers.push(this) 56886 if (!fastNowTimeout || fastTimers.length === 1) { 56887 refreshTimeout() 56888 } 56889 } 56890 56891 this.state = 0 56892 } 56893 56894 clear () { 56895 this.state = -1 56896 } 56897 } 56898 56899 module.exports = { 56900 setTimeout (callback, delay, opaque) { 56901 return delay < 1e3 56902 ? setTimeout(callback, delay, opaque) 56903 : new Timeout(callback, delay, opaque) 56904 }, 56905 clearTimeout (timeout) { 56906 if (timeout instanceof Timeout) { 56907 timeout.clear() 56908 } else { 56909 clearTimeout(timeout) 56910 } 56911 } 56912 } 56913 56914 56915 /***/ }), 56916 56917 /***/ 5354: 56918 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 56919 56920 "use strict"; 56921 56922 56923 const diagnosticsChannel = __nccwpck_require__(7643) 56924 const { uid, states } = __nccwpck_require__(9188) 56925 const { 56926 kReadyState, 56927 kSentClose, 56928 kByteParser, 56929 kReceivedClose 56930 } = __nccwpck_require__(7578) 56931 const { fireEvent, failWebsocketConnection } = __nccwpck_require__(5515) 56932 const { CloseEvent } = __nccwpck_require__(2611) 56933 const { makeRequest } = __nccwpck_require__(8359) 56934 const { fetching } = __nccwpck_require__(4881) 56935 const { Headers } = __nccwpck_require__(554) 56936 const { getGlobalDispatcher } = __nccwpck_require__(1892) 56937 const { kHeadersList } = __nccwpck_require__(2785) 56938 56939 const channels = {} 56940 channels.open = diagnosticsChannel.channel('undici:websocket:open') 56941 channels.close = diagnosticsChannel.channel('undici:websocket:close') 56942 channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') 56943 56944 /** @type {import('crypto')} */ 56945 let crypto 56946 try { 56947 crypto = __nccwpck_require__(6113) 56948 } catch { 56949 56950 } 56951 56952 /** 56953 * @see https://websockets.spec.whatwg.org/#concept-websocket-establish 56954 * @param {URL} url 56955 * @param {string|string[]} protocols 56956 * @param {import('./websocket').WebSocket} ws 56957 * @param {(response: any) => void} onEstablish 56958 * @param {Partial<import('../../types/websocket').WebSocketInit>} options 56959 */ 56960 function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { 56961 // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s 56962 // scheme is "ws", and to "https" otherwise. 56963 const requestURL = url 56964 56965 requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' 56966 56967 // 2. Let request be a new request, whose URL is requestURL, client is client, 56968 // service-workers mode is "none", referrer is "no-referrer", mode is 56969 // "websocket", credentials mode is "include", cache mode is "no-store" , 56970 // and redirect mode is "error". 56971 const request = makeRequest({ 56972 urlList: [requestURL], 56973 serviceWorkers: 'none', 56974 referrer: 'no-referrer', 56975 mode: 'websocket', 56976 credentials: 'include', 56977 cache: 'no-store', 56978 redirect: 'error' 56979 }) 56980 56981 // Note: undici extension, allow setting custom headers. 56982 if (options.headers) { 56983 const headersList = new Headers(options.headers)[kHeadersList] 56984 56985 request.headersList = headersList 56986 } 56987 56988 // 3. Append (`Upgrade`, `websocket`) to request’s header list. 56989 // 4. Append (`Connection`, `Upgrade`) to request’s header list. 56990 // Note: both of these are handled by undici currently. 56991 // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 56992 56993 // 5. Let keyValue be a nonce consisting of a randomly selected 56994 // 16-byte value that has been forgiving-base64-encoded and 56995 // isomorphic encoded. 56996 const keyValue = crypto.randomBytes(16).toString('base64') 56997 56998 // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s 56999 // header list. 57000 request.headersList.append('sec-websocket-key', keyValue) 57001 57002 // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s 57003 // header list. 57004 request.headersList.append('sec-websocket-version', '13') 57005 57006 // 8. For each protocol in protocols, combine 57007 // (`Sec-WebSocket-Protocol`, protocol) in request’s header 57008 // list. 57009 for (const protocol of protocols) { 57010 request.headersList.append('sec-websocket-protocol', protocol) 57011 } 57012 57013 // 9. Let permessageDeflate be a user-agent defined 57014 // "permessage-deflate" extension header value. 57015 // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 57016 // TODO: enable once permessage-deflate is supported 57017 const permessageDeflate = '' // 'permessage-deflate; 15' 57018 57019 // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to 57020 // request’s header list. 57021 // request.headersList.append('sec-websocket-extensions', permessageDeflate) 57022 57023 // 11. Fetch request with useParallelQueue set to true, and 57024 // processResponse given response being these steps: 57025 const controller = fetching({ 57026 request, 57027 useParallelQueue: true, 57028 dispatcher: options.dispatcher ?? getGlobalDispatcher(), 57029 processResponse (response) { 57030 // 1. If response is a network error or its status is not 101, 57031 // fail the WebSocket connection. 57032 if (response.type === 'error' || response.status !== 101) { 57033 failWebsocketConnection(ws, 'Received network error or non-101 status code.') 57034 return 57035 } 57036 57037 // 2. If protocols is not the empty list and extracting header 57038 // list values given `Sec-WebSocket-Protocol` and response’s 57039 // header list results in null, failure, or the empty byte 57040 // sequence, then fail the WebSocket connection. 57041 if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { 57042 failWebsocketConnection(ws, 'Server did not respond with sent protocols.') 57043 return 57044 } 57045 57046 // 3. Follow the requirements stated step 2 to step 6, inclusive, 57047 // of the last set of steps in section 4.1 of The WebSocket 57048 // Protocol to validate response. This either results in fail 57049 // the WebSocket connection or the WebSocket connection is 57050 // established. 57051 57052 // 2. If the response lacks an |Upgrade| header field or the |Upgrade| 57053 // header field contains a value that is not an ASCII case- 57054 // insensitive match for the value "websocket", the client MUST 57055 // _Fail the WebSocket Connection_. 57056 if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { 57057 failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') 57058 return 57059 } 57060 57061 // 3. If the response lacks a |Connection| header field or the 57062 // |Connection| header field doesn't contain a token that is an 57063 // ASCII case-insensitive match for the value "Upgrade", the client 57064 // MUST _Fail the WebSocket Connection_. 57065 if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { 57066 failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') 57067 return 57068 } 57069 57070 // 4. If the response lacks a |Sec-WebSocket-Accept| header field or 57071 // the |Sec-WebSocket-Accept| contains a value other than the 57072 // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- 57073 // Key| (as a string, not base64-decoded) with the string "258EAFA5- 57074 // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and 57075 // trailing whitespace, the client MUST _Fail the WebSocket 57076 // Connection_. 57077 const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') 57078 const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') 57079 if (secWSAccept !== digest) { 57080 failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') 57081 return 57082 } 57083 57084 // 5. If the response includes a |Sec-WebSocket-Extensions| header 57085 // field and this header field indicates the use of an extension 57086 // that was not present in the client's handshake (the server has 57087 // indicated an extension not requested by the client), the client 57088 // MUST _Fail the WebSocket Connection_. (The parsing of this 57089 // header field to determine which extensions are requested is 57090 // discussed in Section 9.1.) 57091 const secExtension = response.headersList.get('Sec-WebSocket-Extensions') 57092 57093 if (secExtension !== null && secExtension !== permessageDeflate) { 57094 failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') 57095 return 57096 } 57097 57098 // 6. If the response includes a |Sec-WebSocket-Protocol| header field 57099 // and this header field indicates the use of a subprotocol that was 57100 // not present in the client's handshake (the server has indicated a 57101 // subprotocol not requested by the client), the client MUST _Fail 57102 // the WebSocket Connection_. 57103 const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') 57104 57105 if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { 57106 failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') 57107 return 57108 } 57109 57110 response.socket.on('data', onSocketData) 57111 response.socket.on('close', onSocketClose) 57112 response.socket.on('error', onSocketError) 57113 57114 if (channels.open.hasSubscribers) { 57115 channels.open.publish({ 57116 address: response.socket.address(), 57117 protocol: secProtocol, 57118 extensions: secExtension 57119 }) 57120 } 57121 57122 onEstablish(response) 57123 } 57124 }) 57125 57126 return controller 57127 } 57128 57129 /** 57130 * @param {Buffer} chunk 57131 */ 57132 function onSocketData (chunk) { 57133 if (!this.ws[kByteParser].write(chunk)) { 57134 this.pause() 57135 } 57136 } 57137 57138 /** 57139 * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol 57140 * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 57141 */ 57142 function onSocketClose () { 57143 const { ws } = this 57144 57145 // If the TCP connection was closed after the 57146 // WebSocket closing handshake was completed, the WebSocket connection 57147 // is said to have been closed _cleanly_. 57148 const wasClean = ws[kSentClose] && ws[kReceivedClose] 57149 57150 let code = 1005 57151 let reason = '' 57152 57153 const result = ws[kByteParser].closingInfo 57154 57155 if (result) { 57156 code = result.code ?? 1005 57157 reason = result.reason 57158 } else if (!ws[kSentClose]) { 57159 // If _The WebSocket 57160 // Connection is Closed_ and no Close control frame was received by the 57161 // endpoint (such as could occur if the underlying transport connection 57162 // is lost), _The WebSocket Connection Close Code_ is considered to be 57163 // 1006. 57164 code = 1006 57165 } 57166 57167 // 1. Change the ready state to CLOSED (3). 57168 ws[kReadyState] = states.CLOSED 57169 57170 // 2. If the user agent was required to fail the WebSocket 57171 // connection, or if the WebSocket connection was closed 57172 // after being flagged as full, fire an event named error 57173 // at the WebSocket object. 57174 // TODO 57175 57176 // 3. Fire an event named close at the WebSocket object, 57177 // using CloseEvent, with the wasClean attribute 57178 // initialized to true if the connection closed cleanly 57179 // and false otherwise, the code attribute initialized to 57180 // the WebSocket connection close code, and the reason 57181 // attribute initialized to the result of applying UTF-8 57182 // decode without BOM to the WebSocket connection close 57183 // reason. 57184 fireEvent('close', ws, CloseEvent, { 57185 wasClean, code, reason 57186 }) 57187 57188 if (channels.close.hasSubscribers) { 57189 channels.close.publish({ 57190 websocket: ws, 57191 code, 57192 reason 57193 }) 57194 } 57195 } 57196 57197 function onSocketError (error) { 57198 const { ws } = this 57199 57200 ws[kReadyState] = states.CLOSING 57201 57202 if (channels.socketError.hasSubscribers) { 57203 channels.socketError.publish(error) 57204 } 57205 57206 this.destroy() 57207 } 57208 57209 module.exports = { 57210 establishWebSocketConnection 57211 } 57212 57213 57214 /***/ }), 57215 57216 /***/ 9188: 57217 /***/ ((module) => { 57218 57219 "use strict"; 57220 57221 57222 // This is a Globally Unique Identifier unique used 57223 // to validate that the endpoint accepts websocket 57224 // connections. 57225 // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 57226 const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' 57227 57228 /** @type {PropertyDescriptor} */ 57229 const staticPropertyDescriptors = { 57230 enumerable: true, 57231 writable: false, 57232 configurable: false 57233 } 57234 57235 const states = { 57236 CONNECTING: 0, 57237 OPEN: 1, 57238 CLOSING: 2, 57239 CLOSED: 3 57240 } 57241 57242 const opcodes = { 57243 CONTINUATION: 0x0, 57244 TEXT: 0x1, 57245 BINARY: 0x2, 57246 CLOSE: 0x8, 57247 PING: 0x9, 57248 PONG: 0xA 57249 } 57250 57251 const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 57252 57253 const parserStates = { 57254 INFO: 0, 57255 PAYLOADLENGTH_16: 2, 57256 PAYLOADLENGTH_64: 3, 57257 READ_DATA: 4 57258 } 57259 57260 const emptyBuffer = Buffer.allocUnsafe(0) 57261 57262 module.exports = { 57263 uid, 57264 staticPropertyDescriptors, 57265 states, 57266 opcodes, 57267 maxUnsigned16Bit, 57268 parserStates, 57269 emptyBuffer 57270 } 57271 57272 57273 /***/ }), 57274 57275 /***/ 2611: 57276 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 57277 57278 "use strict"; 57279 57280 57281 const { webidl } = __nccwpck_require__(1744) 57282 const { kEnumerableProperty } = __nccwpck_require__(3983) 57283 const { MessagePort } = __nccwpck_require__(1267) 57284 57285 /** 57286 * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent 57287 */ 57288 class MessageEvent extends Event { 57289 #eventInit 57290 57291 constructor (type, eventInitDict = {}) { 57292 webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) 57293 57294 type = webidl.converters.DOMString(type) 57295 eventInitDict = webidl.converters.MessageEventInit(eventInitDict) 57296 57297 super(type, eventInitDict) 57298 57299 this.#eventInit = eventInitDict 57300 } 57301 57302 get data () { 57303 webidl.brandCheck(this, MessageEvent) 57304 57305 return this.#eventInit.data 57306 } 57307 57308 get origin () { 57309 webidl.brandCheck(this, MessageEvent) 57310 57311 return this.#eventInit.origin 57312 } 57313 57314 get lastEventId () { 57315 webidl.brandCheck(this, MessageEvent) 57316 57317 return this.#eventInit.lastEventId 57318 } 57319 57320 get source () { 57321 webidl.brandCheck(this, MessageEvent) 57322 57323 return this.#eventInit.source 57324 } 57325 57326 get ports () { 57327 webidl.brandCheck(this, MessageEvent) 57328 57329 if (!Object.isFrozen(this.#eventInit.ports)) { 57330 Object.freeze(this.#eventInit.ports) 57331 } 57332 57333 return this.#eventInit.ports 57334 } 57335 57336 initMessageEvent ( 57337 type, 57338 bubbles = false, 57339 cancelable = false, 57340 data = null, 57341 origin = '', 57342 lastEventId = '', 57343 source = null, 57344 ports = [] 57345 ) { 57346 webidl.brandCheck(this, MessageEvent) 57347 57348 webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) 57349 57350 return new MessageEvent(type, { 57351 bubbles, cancelable, data, origin, lastEventId, source, ports 57352 }) 57353 } 57354 } 57355 57356 /** 57357 * @see https://websockets.spec.whatwg.org/#the-closeevent-interface 57358 */ 57359 class CloseEvent extends Event { 57360 #eventInit 57361 57362 constructor (type, eventInitDict = {}) { 57363 webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) 57364 57365 type = webidl.converters.DOMString(type) 57366 eventInitDict = webidl.converters.CloseEventInit(eventInitDict) 57367 57368 super(type, eventInitDict) 57369 57370 this.#eventInit = eventInitDict 57371 } 57372 57373 get wasClean () { 57374 webidl.brandCheck(this, CloseEvent) 57375 57376 return this.#eventInit.wasClean 57377 } 57378 57379 get code () { 57380 webidl.brandCheck(this, CloseEvent) 57381 57382 return this.#eventInit.code 57383 } 57384 57385 get reason () { 57386 webidl.brandCheck(this, CloseEvent) 57387 57388 return this.#eventInit.reason 57389 } 57390 } 57391 57392 // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface 57393 class ErrorEvent extends Event { 57394 #eventInit 57395 57396 constructor (type, eventInitDict) { 57397 webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) 57398 57399 super(type, eventInitDict) 57400 57401 type = webidl.converters.DOMString(type) 57402 eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) 57403 57404 this.#eventInit = eventInitDict 57405 } 57406 57407 get message () { 57408 webidl.brandCheck(this, ErrorEvent) 57409 57410 return this.#eventInit.message 57411 } 57412 57413 get filename () { 57414 webidl.brandCheck(this, ErrorEvent) 57415 57416 return this.#eventInit.filename 57417 } 57418 57419 get lineno () { 57420 webidl.brandCheck(this, ErrorEvent) 57421 57422 return this.#eventInit.lineno 57423 } 57424 57425 get colno () { 57426 webidl.brandCheck(this, ErrorEvent) 57427 57428 return this.#eventInit.colno 57429 } 57430 57431 get error () { 57432 webidl.brandCheck(this, ErrorEvent) 57433 57434 return this.#eventInit.error 57435 } 57436 } 57437 57438 Object.defineProperties(MessageEvent.prototype, { 57439 [Symbol.toStringTag]: { 57440 value: 'MessageEvent', 57441 configurable: true 57442 }, 57443 data: kEnumerableProperty, 57444 origin: kEnumerableProperty, 57445 lastEventId: kEnumerableProperty, 57446 source: kEnumerableProperty, 57447 ports: kEnumerableProperty, 57448 initMessageEvent: kEnumerableProperty 57449 }) 57450 57451 Object.defineProperties(CloseEvent.prototype, { 57452 [Symbol.toStringTag]: { 57453 value: 'CloseEvent', 57454 configurable: true 57455 }, 57456 reason: kEnumerableProperty, 57457 code: kEnumerableProperty, 57458 wasClean: kEnumerableProperty 57459 }) 57460 57461 Object.defineProperties(ErrorEvent.prototype, { 57462 [Symbol.toStringTag]: { 57463 value: 'ErrorEvent', 57464 configurable: true 57465 }, 57466 message: kEnumerableProperty, 57467 filename: kEnumerableProperty, 57468 lineno: kEnumerableProperty, 57469 colno: kEnumerableProperty, 57470 error: kEnumerableProperty 57471 }) 57472 57473 webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) 57474 57475 webidl.converters['sequence<MessagePort>'] = webidl.sequenceConverter( 57476 webidl.converters.MessagePort 57477 ) 57478 57479 const eventInit = [ 57480 { 57481 key: 'bubbles', 57482 converter: webidl.converters.boolean, 57483 defaultValue: false 57484 }, 57485 { 57486 key: 'cancelable', 57487 converter: webidl.converters.boolean, 57488 defaultValue: false 57489 }, 57490 { 57491 key: 'composed', 57492 converter: webidl.converters.boolean, 57493 defaultValue: false 57494 } 57495 ] 57496 57497 webidl.converters.MessageEventInit = webidl.dictionaryConverter([ 57498 ...eventInit, 57499 { 57500 key: 'data', 57501 converter: webidl.converters.any, 57502 defaultValue: null 57503 }, 57504 { 57505 key: 'origin', 57506 converter: webidl.converters.USVString, 57507 defaultValue: '' 57508 }, 57509 { 57510 key: 'lastEventId', 57511 converter: webidl.converters.DOMString, 57512 defaultValue: '' 57513 }, 57514 { 57515 key: 'source', 57516 // Node doesn't implement WindowProxy or ServiceWorker, so the only 57517 // valid value for source is a MessagePort. 57518 converter: webidl.nullableConverter(webidl.converters.MessagePort), 57519 defaultValue: null 57520 }, 57521 { 57522 key: 'ports', 57523 converter: webidl.converters['sequence<MessagePort>'], 57524 get defaultValue () { 57525 return [] 57526 } 57527 } 57528 ]) 57529 57530 webidl.converters.CloseEventInit = webidl.dictionaryConverter([ 57531 ...eventInit, 57532 { 57533 key: 'wasClean', 57534 converter: webidl.converters.boolean, 57535 defaultValue: false 57536 }, 57537 { 57538 key: 'code', 57539 converter: webidl.converters['unsigned short'], 57540 defaultValue: 0 57541 }, 57542 { 57543 key: 'reason', 57544 converter: webidl.converters.USVString, 57545 defaultValue: '' 57546 } 57547 ]) 57548 57549 webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ 57550 ...eventInit, 57551 { 57552 key: 'message', 57553 converter: webidl.converters.DOMString, 57554 defaultValue: '' 57555 }, 57556 { 57557 key: 'filename', 57558 converter: webidl.converters.USVString, 57559 defaultValue: '' 57560 }, 57561 { 57562 key: 'lineno', 57563 converter: webidl.converters['unsigned long'], 57564 defaultValue: 0 57565 }, 57566 { 57567 key: 'colno', 57568 converter: webidl.converters['unsigned long'], 57569 defaultValue: 0 57570 }, 57571 { 57572 key: 'error', 57573 converter: webidl.converters.any 57574 } 57575 ]) 57576 57577 module.exports = { 57578 MessageEvent, 57579 CloseEvent, 57580 ErrorEvent 57581 } 57582 57583 57584 /***/ }), 57585 57586 /***/ 5444: 57587 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 57588 57589 "use strict"; 57590 57591 57592 const { maxUnsigned16Bit } = __nccwpck_require__(9188) 57593 57594 /** @type {import('crypto')} */ 57595 let crypto 57596 try { 57597 crypto = __nccwpck_require__(6113) 57598 } catch { 57599 57600 } 57601 57602 class WebsocketFrameSend { 57603 /** 57604 * @param {Buffer|undefined} data 57605 */ 57606 constructor (data) { 57607 this.frameData = data 57608 this.maskKey = crypto.randomBytes(4) 57609 } 57610 57611 createFrame (opcode) { 57612 const bodyLength = this.frameData?.byteLength ?? 0 57613 57614 /** @type {number} */ 57615 let payloadLength = bodyLength // 0-125 57616 let offset = 6 57617 57618 if (bodyLength > maxUnsigned16Bit) { 57619 offset += 8 // payload length is next 8 bytes 57620 payloadLength = 127 57621 } else if (bodyLength > 125) { 57622 offset += 2 // payload length is next 2 bytes 57623 payloadLength = 126 57624 } 57625 57626 const buffer = Buffer.allocUnsafe(bodyLength + offset) 57627 57628 // Clear first 2 bytes, everything else is overwritten 57629 buffer[0] = buffer[1] = 0 57630 buffer[0] |= 0x80 // FIN 57631 buffer[0] = (buffer[0] & 0xF0) + opcode // opcode 57632 57633 /*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */ 57634 buffer[offset - 4] = this.maskKey[0] 57635 buffer[offset - 3] = this.maskKey[1] 57636 buffer[offset - 2] = this.maskKey[2] 57637 buffer[offset - 1] = this.maskKey[3] 57638 57639 buffer[1] = payloadLength 57640 57641 if (payloadLength === 126) { 57642 buffer.writeUInt16BE(bodyLength, 2) 57643 } else if (payloadLength === 127) { 57644 // Clear extended payload length 57645 buffer[2] = buffer[3] = 0 57646 buffer.writeUIntBE(bodyLength, 4, 6) 57647 } 57648 57649 buffer[1] |= 0x80 // MASK 57650 57651 // mask body 57652 for (let i = 0; i < bodyLength; i++) { 57653 buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] 57654 } 57655 57656 return buffer 57657 } 57658 } 57659 57660 module.exports = { 57661 WebsocketFrameSend 57662 } 57663 57664 57665 /***/ }), 57666 57667 /***/ 1688: 57668 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 57669 57670 "use strict"; 57671 57672 57673 const { Writable } = __nccwpck_require__(2781) 57674 const diagnosticsChannel = __nccwpck_require__(7643) 57675 const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(9188) 57676 const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(7578) 57677 const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(5515) 57678 const { WebsocketFrameSend } = __nccwpck_require__(5444) 57679 57680 // This code was influenced by ws released under the MIT license. 57681 // Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com> 57682 // Copyright (c) 2013 Arnout Kazemier and contributors 57683 // Copyright (c) 2016 Luigi Pinca and contributors 57684 57685 const channels = {} 57686 channels.ping = diagnosticsChannel.channel('undici:websocket:ping') 57687 channels.pong = diagnosticsChannel.channel('undici:websocket:pong') 57688 57689 class ByteParser extends Writable { 57690 #buffers = [] 57691 #byteOffset = 0 57692 57693 #state = parserStates.INFO 57694 57695 #info = {} 57696 #fragments = [] 57697 57698 constructor (ws) { 57699 super() 57700 57701 this.ws = ws 57702 } 57703 57704 /** 57705 * @param {Buffer} chunk 57706 * @param {() => void} callback 57707 */ 57708 _write (chunk, _, callback) { 57709 this.#buffers.push(chunk) 57710 this.#byteOffset += chunk.length 57711 57712 this.run(callback) 57713 } 57714 57715 /** 57716 * Runs whenever a new chunk is received. 57717 * Callback is called whenever there are no more chunks buffering, 57718 * or not enough bytes are buffered to parse. 57719 */ 57720 run (callback) { 57721 while (true) { 57722 if (this.#state === parserStates.INFO) { 57723 // If there aren't enough bytes to parse the payload length, etc. 57724 if (this.#byteOffset < 2) { 57725 return callback() 57726 } 57727 57728 const buffer = this.consume(2) 57729 57730 this.#info.fin = (buffer[0] & 0x80) !== 0 57731 this.#info.opcode = buffer[0] & 0x0F 57732 57733 // If we receive a fragmented message, we use the type of the first 57734 // frame to parse the full message as binary/text, when it's terminated 57735 this.#info.originalOpcode ??= this.#info.opcode 57736 57737 this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION 57738 57739 if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { 57740 // Only text and binary frames can be fragmented 57741 failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') 57742 return 57743 } 57744 57745 const payloadLength = buffer[1] & 0x7F 57746 57747 if (payloadLength <= 125) { 57748 this.#info.payloadLength = payloadLength 57749 this.#state = parserStates.READ_DATA 57750 } else if (payloadLength === 126) { 57751 this.#state = parserStates.PAYLOADLENGTH_16 57752 } else if (payloadLength === 127) { 57753 this.#state = parserStates.PAYLOADLENGTH_64 57754 } 57755 57756 if (this.#info.fragmented && payloadLength > 125) { 57757 // A fragmented frame can't be fragmented itself 57758 failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') 57759 return 57760 } else if ( 57761 (this.#info.opcode === opcodes.PING || 57762 this.#info.opcode === opcodes.PONG || 57763 this.#info.opcode === opcodes.CLOSE) && 57764 payloadLength > 125 57765 ) { 57766 // Control frames can have a payload length of 125 bytes MAX 57767 failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') 57768 return 57769 } else if (this.#info.opcode === opcodes.CLOSE) { 57770 if (payloadLength === 1) { 57771 failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') 57772 return 57773 } 57774 57775 const body = this.consume(payloadLength) 57776 57777 this.#info.closeInfo = this.parseCloseBody(false, body) 57778 57779 if (!this.ws[kSentClose]) { 57780 // If an endpoint receives a Close frame and did not previously send a 57781 // Close frame, the endpoint MUST send a Close frame in response. (When 57782 // sending a Close frame in response, the endpoint typically echos the 57783 // status code it received.) 57784 const body = Buffer.allocUnsafe(2) 57785 body.writeUInt16BE(this.#info.closeInfo.code, 0) 57786 const closeFrame = new WebsocketFrameSend(body) 57787 57788 this.ws[kResponse].socket.write( 57789 closeFrame.createFrame(opcodes.CLOSE), 57790 (err) => { 57791 if (!err) { 57792 this.ws[kSentClose] = true 57793 } 57794 } 57795 ) 57796 } 57797 57798 // Upon either sending or receiving a Close control frame, it is said 57799 // that _The WebSocket Closing Handshake is Started_ and that the 57800 // WebSocket connection is in the CLOSING state. 57801 this.ws[kReadyState] = states.CLOSING 57802 this.ws[kReceivedClose] = true 57803 57804 this.end() 57805 57806 return 57807 } else if (this.#info.opcode === opcodes.PING) { 57808 // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in 57809 // response, unless it already received a Close frame. 57810 // A Pong frame sent in response to a Ping frame must have identical 57811 // "Application data" 57812 57813 const body = this.consume(payloadLength) 57814 57815 if (!this.ws[kReceivedClose]) { 57816 const frame = new WebsocketFrameSend(body) 57817 57818 this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) 57819 57820 if (channels.ping.hasSubscribers) { 57821 channels.ping.publish({ 57822 payload: body 57823 }) 57824 } 57825 } 57826 57827 this.#state = parserStates.INFO 57828 57829 if (this.#byteOffset > 0) { 57830 continue 57831 } else { 57832 callback() 57833 return 57834 } 57835 } else if (this.#info.opcode === opcodes.PONG) { 57836 // A Pong frame MAY be sent unsolicited. This serves as a 57837 // unidirectional heartbeat. A response to an unsolicited Pong frame is 57838 // not expected. 57839 57840 const body = this.consume(payloadLength) 57841 57842 if (channels.pong.hasSubscribers) { 57843 channels.pong.publish({ 57844 payload: body 57845 }) 57846 } 57847 57848 if (this.#byteOffset > 0) { 57849 continue 57850 } else { 57851 callback() 57852 return 57853 } 57854 } 57855 } else if (this.#state === parserStates.PAYLOADLENGTH_16) { 57856 if (this.#byteOffset < 2) { 57857 return callback() 57858 } 57859 57860 const buffer = this.consume(2) 57861 57862 this.#info.payloadLength = buffer.readUInt16BE(0) 57863 this.#state = parserStates.READ_DATA 57864 } else if (this.#state === parserStates.PAYLOADLENGTH_64) { 57865 if (this.#byteOffset < 8) { 57866 return callback() 57867 } 57868 57869 const buffer = this.consume(8) 57870 const upper = buffer.readUInt32BE(0) 57871 57872 // 2^31 is the maxinimum bytes an arraybuffer can contain 57873 // on 32-bit systems. Although, on 64-bit systems, this is 57874 // 2^53-1 bytes. 57875 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length 57876 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 57877 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e 57878 if (upper > 2 ** 31 - 1) { 57879 failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') 57880 return 57881 } 57882 57883 const lower = buffer.readUInt32BE(4) 57884 57885 this.#info.payloadLength = (upper << 8) + lower 57886 this.#state = parserStates.READ_DATA 57887 } else if (this.#state === parserStates.READ_DATA) { 57888 if (this.#byteOffset < this.#info.payloadLength) { 57889 // If there is still more data in this chunk that needs to be read 57890 return callback() 57891 } else if (this.#byteOffset >= this.#info.payloadLength) { 57892 // If the server sent multiple frames in a single chunk 57893 57894 const body = this.consume(this.#info.payloadLength) 57895 57896 this.#fragments.push(body) 57897 57898 // If the frame is unfragmented, or a fragmented frame was terminated, 57899 // a message was received 57900 if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { 57901 const fullMessage = Buffer.concat(this.#fragments) 57902 57903 websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) 57904 57905 this.#info = {} 57906 this.#fragments.length = 0 57907 } 57908 57909 this.#state = parserStates.INFO 57910 } 57911 } 57912 57913 if (this.#byteOffset > 0) { 57914 continue 57915 } else { 57916 callback() 57917 break 57918 } 57919 } 57920 } 57921 57922 /** 57923 * Take n bytes from the buffered Buffers 57924 * @param {number} n 57925 * @returns {Buffer|null} 57926 */ 57927 consume (n) { 57928 if (n > this.#byteOffset) { 57929 return null 57930 } else if (n === 0) { 57931 return emptyBuffer 57932 } 57933 57934 if (this.#buffers[0].length === n) { 57935 this.#byteOffset -= this.#buffers[0].length 57936 return this.#buffers.shift() 57937 } 57938 57939 const buffer = Buffer.allocUnsafe(n) 57940 let offset = 0 57941 57942 while (offset !== n) { 57943 const next = this.#buffers[0] 57944 const { length } = next 57945 57946 if (length + offset === n) { 57947 buffer.set(this.#buffers.shift(), offset) 57948 break 57949 } else if (length + offset > n) { 57950 buffer.set(next.subarray(0, n - offset), offset) 57951 this.#buffers[0] = next.subarray(n - offset) 57952 break 57953 } else { 57954 buffer.set(this.#buffers.shift(), offset) 57955 offset += next.length 57956 } 57957 } 57958 57959 this.#byteOffset -= n 57960 57961 return buffer 57962 } 57963 57964 parseCloseBody (onlyCode, data) { 57965 // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 57966 /** @type {number|undefined} */ 57967 let code 57968 57969 if (data.length >= 2) { 57970 // _The WebSocket Connection Close Code_ is 57971 // defined as the status code (Section 7.4) contained in the first Close 57972 // control frame received by the application 57973 code = data.readUInt16BE(0) 57974 } 57975 57976 if (onlyCode) { 57977 if (!isValidStatusCode(code)) { 57978 return null 57979 } 57980 57981 return { code } 57982 } 57983 57984 // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 57985 /** @type {Buffer} */ 57986 let reason = data.subarray(2) 57987 57988 // Remove BOM 57989 if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { 57990 reason = reason.subarray(3) 57991 } 57992 57993 if (code !== undefined && !isValidStatusCode(code)) { 57994 return null 57995 } 57996 57997 try { 57998 // TODO: optimize this 57999 reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) 58000 } catch { 58001 return null 58002 } 58003 58004 return { code, reason } 58005 } 58006 58007 get closingInfo () { 58008 return this.#info.closeInfo 58009 } 58010 } 58011 58012 module.exports = { 58013 ByteParser 58014 } 58015 58016 58017 /***/ }), 58018 58019 /***/ 7578: 58020 /***/ ((module) => { 58021 58022 "use strict"; 58023 58024 58025 module.exports = { 58026 kWebSocketURL: Symbol('url'), 58027 kReadyState: Symbol('ready state'), 58028 kController: Symbol('controller'), 58029 kResponse: Symbol('response'), 58030 kBinaryType: Symbol('binary type'), 58031 kSentClose: Symbol('sent close'), 58032 kReceivedClose: Symbol('received close'), 58033 kByteParser: Symbol('byte parser') 58034 } 58035 58036 58037 /***/ }), 58038 58039 /***/ 5515: 58040 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 58041 58042 "use strict"; 58043 58044 58045 const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(7578) 58046 const { states, opcodes } = __nccwpck_require__(9188) 58047 const { MessageEvent, ErrorEvent } = __nccwpck_require__(2611) 58048 58049 /* globals Blob */ 58050 58051 /** 58052 * @param {import('./websocket').WebSocket} ws 58053 */ 58054 function isEstablished (ws) { 58055 // If the server's response is validated as provided for above, it is 58056 // said that _The WebSocket Connection is Established_ and that the 58057 // WebSocket Connection is in the OPEN state. 58058 return ws[kReadyState] === states.OPEN 58059 } 58060 58061 /** 58062 * @param {import('./websocket').WebSocket} ws 58063 */ 58064 function isClosing (ws) { 58065 // Upon either sending or receiving a Close control frame, it is said 58066 // that _The WebSocket Closing Handshake is Started_ and that the 58067 // WebSocket connection is in the CLOSING state. 58068 return ws[kReadyState] === states.CLOSING 58069 } 58070 58071 /** 58072 * @param {import('./websocket').WebSocket} ws 58073 */ 58074 function isClosed (ws) { 58075 return ws[kReadyState] === states.CLOSED 58076 } 58077 58078 /** 58079 * @see https://dom.spec.whatwg.org/#concept-event-fire 58080 * @param {string} e 58081 * @param {EventTarget} target 58082 * @param {EventInit | undefined} eventInitDict 58083 */ 58084 function fireEvent (e, target, eventConstructor = Event, eventInitDict) { 58085 // 1. If eventConstructor is not given, then let eventConstructor be Event. 58086 58087 // 2. Let event be the result of creating an event given eventConstructor, 58088 // in the relevant realm of target. 58089 // 3. Initialize event’s type attribute to e. 58090 const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap 58091 58092 // 4. Initialize any other IDL attributes of event as described in the 58093 // invocation of this algorithm. 58094 58095 // 5. Return the result of dispatching event at target, with legacy target 58096 // override flag set if set. 58097 target.dispatchEvent(event) 58098 } 58099 58100 /** 58101 * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol 58102 * @param {import('./websocket').WebSocket} ws 58103 * @param {number} type Opcode 58104 * @param {Buffer} data application data 58105 */ 58106 function websocketMessageReceived (ws, type, data) { 58107 // 1. If ready state is not OPEN (1), then return. 58108 if (ws[kReadyState] !== states.OPEN) { 58109 return 58110 } 58111 58112 // 2. Let dataForEvent be determined by switching on type and binary type: 58113 let dataForEvent 58114 58115 if (type === opcodes.TEXT) { 58116 // -> type indicates that the data is Text 58117 // a new DOMString containing data 58118 try { 58119 dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) 58120 } catch { 58121 failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') 58122 return 58123 } 58124 } else if (type === opcodes.BINARY) { 58125 if (ws[kBinaryType] === 'blob') { 58126 // -> type indicates that the data is Binary and binary type is "blob" 58127 // a new Blob object, created in the relevant Realm of the WebSocket 58128 // object, that represents data as its raw data 58129 dataForEvent = new Blob([data]) 58130 } else { 58131 // -> type indicates that the data is Binary and binary type is "arraybuffer" 58132 // a new ArrayBuffer object, created in the relevant Realm of the 58133 // WebSocket object, whose contents are data 58134 dataForEvent = new Uint8Array(data).buffer 58135 } 58136 } 58137 58138 // 3. Fire an event named message at the WebSocket object, using MessageEvent, 58139 // with the origin attribute initialized to the serialization of the WebSocket 58140 // object’s url's origin, and the data attribute initialized to dataForEvent. 58141 fireEvent('message', ws, MessageEvent, { 58142 origin: ws[kWebSocketURL].origin, 58143 data: dataForEvent 58144 }) 58145 } 58146 58147 /** 58148 * @see https://datatracker.ietf.org/doc/html/rfc6455 58149 * @see https://datatracker.ietf.org/doc/html/rfc2616 58150 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 58151 * @param {string} protocol 58152 */ 58153 function isValidSubprotocol (protocol) { 58154 // If present, this value indicates one 58155 // or more comma-separated subprotocol the client wishes to speak, 58156 // ordered by preference. The elements that comprise this value 58157 // MUST be non-empty strings with characters in the range U+0021 to 58158 // U+007E not including separator characters as defined in 58159 // [RFC2616] and MUST all be unique strings. 58160 if (protocol.length === 0) { 58161 return false 58162 } 58163 58164 for (const char of protocol) { 58165 const code = char.charCodeAt(0) 58166 58167 if ( 58168 code < 0x21 || 58169 code > 0x7E || 58170 char === '(' || 58171 char === ')' || 58172 char === '<' || 58173 char === '>' || 58174 char === '@' || 58175 char === ',' || 58176 char === ';' || 58177 char === ':' || 58178 char === '\\' || 58179 char === '"' || 58180 char === '/' || 58181 char === '[' || 58182 char === ']' || 58183 char === '?' || 58184 char === '=' || 58185 char === '{' || 58186 char === '}' || 58187 code === 32 || // SP 58188 code === 9 // HT 58189 ) { 58190 return false 58191 } 58192 } 58193 58194 return true 58195 } 58196 58197 /** 58198 * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 58199 * @param {number} code 58200 */ 58201 function isValidStatusCode (code) { 58202 if (code >= 1000 && code < 1015) { 58203 return ( 58204 code !== 1004 && // reserved 58205 code !== 1005 && // "MUST NOT be set as a status code" 58206 code !== 1006 // "MUST NOT be set as a status code" 58207 ) 58208 } 58209 58210 return code >= 3000 && code <= 4999 58211 } 58212 58213 /** 58214 * @param {import('./websocket').WebSocket} ws 58215 * @param {string|undefined} reason 58216 */ 58217 function failWebsocketConnection (ws, reason) { 58218 const { [kController]: controller, [kResponse]: response } = ws 58219 58220 controller.abort() 58221 58222 if (response?.socket && !response.socket.destroyed) { 58223 response.socket.destroy() 58224 } 58225 58226 if (reason) { 58227 fireEvent('error', ws, ErrorEvent, { 58228 error: new Error(reason) 58229 }) 58230 } 58231 } 58232 58233 module.exports = { 58234 isEstablished, 58235 isClosing, 58236 isClosed, 58237 fireEvent, 58238 isValidSubprotocol, 58239 isValidStatusCode, 58240 failWebsocketConnection, 58241 websocketMessageReceived 58242 } 58243 58244 58245 /***/ }), 58246 58247 /***/ 4284: 58248 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 58249 58250 "use strict"; 58251 58252 58253 const { webidl } = __nccwpck_require__(1744) 58254 const { DOMException } = __nccwpck_require__(1037) 58255 const { URLSerializer } = __nccwpck_require__(685) 58256 const { getGlobalOrigin } = __nccwpck_require__(1246) 58257 const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(9188) 58258 const { 58259 kWebSocketURL, 58260 kReadyState, 58261 kController, 58262 kBinaryType, 58263 kResponse, 58264 kSentClose, 58265 kByteParser 58266 } = __nccwpck_require__(7578) 58267 const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(5515) 58268 const { establishWebSocketConnection } = __nccwpck_require__(5354) 58269 const { WebsocketFrameSend } = __nccwpck_require__(5444) 58270 const { ByteParser } = __nccwpck_require__(1688) 58271 const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3983) 58272 const { getGlobalDispatcher } = __nccwpck_require__(1892) 58273 const { types } = __nccwpck_require__(3837) 58274 58275 let experimentalWarned = false 58276 58277 // https://websockets.spec.whatwg.org/#interface-definition 58278 class WebSocket extends EventTarget { 58279 #events = { 58280 open: null, 58281 error: null, 58282 close: null, 58283 message: null 58284 } 58285 58286 #bufferedAmount = 0 58287 #protocol = '' 58288 #extensions = '' 58289 58290 /** 58291 * @param {string} url 58292 * @param {string|string[]} protocols 58293 */ 58294 constructor (url, protocols = []) { 58295 super() 58296 58297 webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) 58298 58299 if (!experimentalWarned) { 58300 experimentalWarned = true 58301 process.emitWarning('WebSockets are experimental, expect them to change at any time.', { 58302 code: 'UNDICI-WS' 58303 }) 58304 } 58305 58306 const options = webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'](protocols) 58307 58308 url = webidl.converters.USVString(url) 58309 protocols = options.protocols 58310 58311 // 1. Let baseURL be this's relevant settings object's API base URL. 58312 const baseURL = getGlobalOrigin() 58313 58314 // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. 58315 let urlRecord 58316 58317 try { 58318 urlRecord = new URL(url, baseURL) 58319 } catch (e) { 58320 // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. 58321 throw new DOMException(e, 'SyntaxError') 58322 } 58323 58324 // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". 58325 if (urlRecord.protocol === 'http:') { 58326 urlRecord.protocol = 'ws:' 58327 } else if (urlRecord.protocol === 'https:') { 58328 // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". 58329 urlRecord.protocol = 'wss:' 58330 } 58331 58332 // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. 58333 if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { 58334 throw new DOMException( 58335 `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, 58336 'SyntaxError' 58337 ) 58338 } 58339 58340 // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" 58341 // DOMException. 58342 if (urlRecord.hash || urlRecord.href.endsWith('#')) { 58343 throw new DOMException('Got fragment', 'SyntaxError') 58344 } 58345 58346 // 8. If protocols is a string, set protocols to a sequence consisting 58347 // of just that string. 58348 if (typeof protocols === 'string') { 58349 protocols = [protocols] 58350 } 58351 58352 // 9. If any of the values in protocols occur more than once or otherwise 58353 // fail to match the requirements for elements that comprise the value 58354 // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket 58355 // protocol, then throw a "SyntaxError" DOMException. 58356 if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { 58357 throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') 58358 } 58359 58360 if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { 58361 throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') 58362 } 58363 58364 // 10. Set this's url to urlRecord. 58365 this[kWebSocketURL] = new URL(urlRecord.href) 58366 58367 // 11. Let client be this's relevant settings object. 58368 58369 // 12. Run this step in parallel: 58370 58371 // 1. Establish a WebSocket connection given urlRecord, protocols, 58372 // and client. 58373 this[kController] = establishWebSocketConnection( 58374 urlRecord, 58375 protocols, 58376 this, 58377 (response) => this.#onConnectionEstablished(response), 58378 options 58379 ) 58380 58381 // Each WebSocket object has an associated ready state, which is a 58382 // number representing the state of the connection. Initially it must 58383 // be CONNECTING (0). 58384 this[kReadyState] = WebSocket.CONNECTING 58385 58386 // The extensions attribute must initially return the empty string. 58387 58388 // The protocol attribute must initially return the empty string. 58389 58390 // Each WebSocket object has an associated binary type, which is a 58391 // BinaryType. Initially it must be "blob". 58392 this[kBinaryType] = 'blob' 58393 } 58394 58395 /** 58396 * @see https://websockets.spec.whatwg.org/#dom-websocket-close 58397 * @param {number|undefined} code 58398 * @param {string|undefined} reason 58399 */ 58400 close (code = undefined, reason = undefined) { 58401 webidl.brandCheck(this, WebSocket) 58402 58403 if (code !== undefined) { 58404 code = webidl.converters['unsigned short'](code, { clamp: true }) 58405 } 58406 58407 if (reason !== undefined) { 58408 reason = webidl.converters.USVString(reason) 58409 } 58410 58411 // 1. If code is present, but is neither an integer equal to 1000 nor an 58412 // integer in the range 3000 to 4999, inclusive, throw an 58413 // "InvalidAccessError" DOMException. 58414 if (code !== undefined) { 58415 if (code !== 1000 && (code < 3000 || code > 4999)) { 58416 throw new DOMException('invalid code', 'InvalidAccessError') 58417 } 58418 } 58419 58420 let reasonByteLength = 0 58421 58422 // 2. If reason is present, then run these substeps: 58423 if (reason !== undefined) { 58424 // 1. Let reasonBytes be the result of encoding reason. 58425 // 2. If reasonBytes is longer than 123 bytes, then throw a 58426 // "SyntaxError" DOMException. 58427 reasonByteLength = Buffer.byteLength(reason) 58428 58429 if (reasonByteLength > 123) { 58430 throw new DOMException( 58431 `Reason must be less than 123 bytes; received ${reasonByteLength}`, 58432 'SyntaxError' 58433 ) 58434 } 58435 } 58436 58437 // 3. Run the first matching steps from the following list: 58438 if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { 58439 // If this's ready state is CLOSING (2) or CLOSED (3) 58440 // Do nothing. 58441 } else if (!isEstablished(this)) { 58442 // If the WebSocket connection is not yet established 58443 // Fail the WebSocket connection and set this's ready state 58444 // to CLOSING (2). 58445 failWebsocketConnection(this, 'Connection was closed before it was established.') 58446 this[kReadyState] = WebSocket.CLOSING 58447 } else if (!isClosing(this)) { 58448 // If the WebSocket closing handshake has not yet been started 58449 // Start the WebSocket closing handshake and set this's ready 58450 // state to CLOSING (2). 58451 // - If neither code nor reason is present, the WebSocket Close 58452 // message must not have a body. 58453 // - If code is present, then the status code to use in the 58454 // WebSocket Close message must be the integer given by code. 58455 // - If reason is also present, then reasonBytes must be 58456 // provided in the Close message after the status code. 58457 58458 const frame = new WebsocketFrameSend() 58459 58460 // If neither code nor reason is present, the WebSocket Close 58461 // message must not have a body. 58462 58463 // If code is present, then the status code to use in the 58464 // WebSocket Close message must be the integer given by code. 58465 if (code !== undefined && reason === undefined) { 58466 frame.frameData = Buffer.allocUnsafe(2) 58467 frame.frameData.writeUInt16BE(code, 0) 58468 } else if (code !== undefined && reason !== undefined) { 58469 // If reason is also present, then reasonBytes must be 58470 // provided in the Close message after the status code. 58471 frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) 58472 frame.frameData.writeUInt16BE(code, 0) 58473 // the body MAY contain UTF-8-encoded data with value /reason/ 58474 frame.frameData.write(reason, 2, 'utf-8') 58475 } else { 58476 frame.frameData = emptyBuffer 58477 } 58478 58479 /** @type {import('stream').Duplex} */ 58480 const socket = this[kResponse].socket 58481 58482 socket.write(frame.createFrame(opcodes.CLOSE), (err) => { 58483 if (!err) { 58484 this[kSentClose] = true 58485 } 58486 }) 58487 58488 // Upon either sending or receiving a Close control frame, it is said 58489 // that _The WebSocket Closing Handshake is Started_ and that the 58490 // WebSocket connection is in the CLOSING state. 58491 this[kReadyState] = states.CLOSING 58492 } else { 58493 // Otherwise 58494 // Set this's ready state to CLOSING (2). 58495 this[kReadyState] = WebSocket.CLOSING 58496 } 58497 } 58498 58499 /** 58500 * @see https://websockets.spec.whatwg.org/#dom-websocket-send 58501 * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data 58502 */ 58503 send (data) { 58504 webidl.brandCheck(this, WebSocket) 58505 58506 webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) 58507 58508 data = webidl.converters.WebSocketSendData(data) 58509 58510 // 1. If this's ready state is CONNECTING, then throw an 58511 // "InvalidStateError" DOMException. 58512 if (this[kReadyState] === WebSocket.CONNECTING) { 58513 throw new DOMException('Sent before connected.', 'InvalidStateError') 58514 } 58515 58516 // 2. Run the appropriate set of steps from the following list: 58517 // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 58518 // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 58519 58520 if (!isEstablished(this) || isClosing(this)) { 58521 return 58522 } 58523 58524 /** @type {import('stream').Duplex} */ 58525 const socket = this[kResponse].socket 58526 58527 // If data is a string 58528 if (typeof data === 'string') { 58529 // If the WebSocket connection is established and the WebSocket 58530 // closing handshake has not yet started, then the user agent 58531 // must send a WebSocket Message comprised of the data argument 58532 // using a text frame opcode; if the data cannot be sent, e.g. 58533 // because it would need to be buffered but the buffer is full, 58534 // the user agent must flag the WebSocket as full and then close 58535 // the WebSocket connection. Any invocation of this method with a 58536 // string argument that does not throw an exception must increase 58537 // the bufferedAmount attribute by the number of bytes needed to 58538 // express the argument as UTF-8. 58539 58540 const value = Buffer.from(data) 58541 const frame = new WebsocketFrameSend(value) 58542 const buffer = frame.createFrame(opcodes.TEXT) 58543 58544 this.#bufferedAmount += value.byteLength 58545 socket.write(buffer, () => { 58546 this.#bufferedAmount -= value.byteLength 58547 }) 58548 } else if (types.isArrayBuffer(data)) { 58549 // If the WebSocket connection is established, and the WebSocket 58550 // closing handshake has not yet started, then the user agent must 58551 // send a WebSocket Message comprised of data using a binary frame 58552 // opcode; if the data cannot be sent, e.g. because it would need 58553 // to be buffered but the buffer is full, the user agent must flag 58554 // the WebSocket as full and then close the WebSocket connection. 58555 // The data to be sent is the data stored in the buffer described 58556 // by the ArrayBuffer object. Any invocation of this method with an 58557 // ArrayBuffer argument that does not throw an exception must 58558 // increase the bufferedAmount attribute by the length of the 58559 // ArrayBuffer in bytes. 58560 58561 const value = Buffer.from(data) 58562 const frame = new WebsocketFrameSend(value) 58563 const buffer = frame.createFrame(opcodes.BINARY) 58564 58565 this.#bufferedAmount += value.byteLength 58566 socket.write(buffer, () => { 58567 this.#bufferedAmount -= value.byteLength 58568 }) 58569 } else if (ArrayBuffer.isView(data)) { 58570 // If the WebSocket connection is established, and the WebSocket 58571 // closing handshake has not yet started, then the user agent must 58572 // send a WebSocket Message comprised of data using a binary frame 58573 // opcode; if the data cannot be sent, e.g. because it would need to 58574 // be buffered but the buffer is full, the user agent must flag the 58575 // WebSocket as full and then close the WebSocket connection. The 58576 // data to be sent is the data stored in the section of the buffer 58577 // described by the ArrayBuffer object that data references. Any 58578 // invocation of this method with this kind of argument that does 58579 // not throw an exception must increase the bufferedAmount attribute 58580 // by the length of data’s buffer in bytes. 58581 58582 const ab = Buffer.from(data, data.byteOffset, data.byteLength) 58583 58584 const frame = new WebsocketFrameSend(ab) 58585 const buffer = frame.createFrame(opcodes.BINARY) 58586 58587 this.#bufferedAmount += ab.byteLength 58588 socket.write(buffer, () => { 58589 this.#bufferedAmount -= ab.byteLength 58590 }) 58591 } else if (isBlobLike(data)) { 58592 // If the WebSocket connection is established, and the WebSocket 58593 // closing handshake has not yet started, then the user agent must 58594 // send a WebSocket Message comprised of data using a binary frame 58595 // opcode; if the data cannot be sent, e.g. because it would need to 58596 // be buffered but the buffer is full, the user agent must flag the 58597 // WebSocket as full and then close the WebSocket connection. The data 58598 // to be sent is the raw data represented by the Blob object. Any 58599 // invocation of this method with a Blob argument that does not throw 58600 // an exception must increase the bufferedAmount attribute by the size 58601 // of the Blob object’s raw data, in bytes. 58602 58603 const frame = new WebsocketFrameSend() 58604 58605 data.arrayBuffer().then((ab) => { 58606 const value = Buffer.from(ab) 58607 frame.frameData = value 58608 const buffer = frame.createFrame(opcodes.BINARY) 58609 58610 this.#bufferedAmount += value.byteLength 58611 socket.write(buffer, () => { 58612 this.#bufferedAmount -= value.byteLength 58613 }) 58614 }) 58615 } 58616 } 58617 58618 get readyState () { 58619 webidl.brandCheck(this, WebSocket) 58620 58621 // The readyState getter steps are to return this's ready state. 58622 return this[kReadyState] 58623 } 58624 58625 get bufferedAmount () { 58626 webidl.brandCheck(this, WebSocket) 58627 58628 return this.#bufferedAmount 58629 } 58630 58631 get url () { 58632 webidl.brandCheck(this, WebSocket) 58633 58634 // The url getter steps are to return this's url, serialized. 58635 return URLSerializer(this[kWebSocketURL]) 58636 } 58637 58638 get extensions () { 58639 webidl.brandCheck(this, WebSocket) 58640 58641 return this.#extensions 58642 } 58643 58644 get protocol () { 58645 webidl.brandCheck(this, WebSocket) 58646 58647 return this.#protocol 58648 } 58649 58650 get onopen () { 58651 webidl.brandCheck(this, WebSocket) 58652 58653 return this.#events.open 58654 } 58655 58656 set onopen (fn) { 58657 webidl.brandCheck(this, WebSocket) 58658 58659 if (this.#events.open) { 58660 this.removeEventListener('open', this.#events.open) 58661 } 58662 58663 if (typeof fn === 'function') { 58664 this.#events.open = fn 58665 this.addEventListener('open', fn) 58666 } else { 58667 this.#events.open = null 58668 } 58669 } 58670 58671 get onerror () { 58672 webidl.brandCheck(this, WebSocket) 58673 58674 return this.#events.error 58675 } 58676 58677 set onerror (fn) { 58678 webidl.brandCheck(this, WebSocket) 58679 58680 if (this.#events.error) { 58681 this.removeEventListener('error', this.#events.error) 58682 } 58683 58684 if (typeof fn === 'function') { 58685 this.#events.error = fn 58686 this.addEventListener('error', fn) 58687 } else { 58688 this.#events.error = null 58689 } 58690 } 58691 58692 get onclose () { 58693 webidl.brandCheck(this, WebSocket) 58694 58695 return this.#events.close 58696 } 58697 58698 set onclose (fn) { 58699 webidl.brandCheck(this, WebSocket) 58700 58701 if (this.#events.close) { 58702 this.removeEventListener('close', this.#events.close) 58703 } 58704 58705 if (typeof fn === 'function') { 58706 this.#events.close = fn 58707 this.addEventListener('close', fn) 58708 } else { 58709 this.#events.close = null 58710 } 58711 } 58712 58713 get onmessage () { 58714 webidl.brandCheck(this, WebSocket) 58715 58716 return this.#events.message 58717 } 58718 58719 set onmessage (fn) { 58720 webidl.brandCheck(this, WebSocket) 58721 58722 if (this.#events.message) { 58723 this.removeEventListener('message', this.#events.message) 58724 } 58725 58726 if (typeof fn === 'function') { 58727 this.#events.message = fn 58728 this.addEventListener('message', fn) 58729 } else { 58730 this.#events.message = null 58731 } 58732 } 58733 58734 get binaryType () { 58735 webidl.brandCheck(this, WebSocket) 58736 58737 return this[kBinaryType] 58738 } 58739 58740 set binaryType (type) { 58741 webidl.brandCheck(this, WebSocket) 58742 58743 if (type !== 'blob' && type !== 'arraybuffer') { 58744 this[kBinaryType] = 'blob' 58745 } else { 58746 this[kBinaryType] = type 58747 } 58748 } 58749 58750 /** 58751 * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol 58752 */ 58753 #onConnectionEstablished (response) { 58754 // processResponse is called when the "response’s header list has been received and initialized." 58755 // once this happens, the connection is open 58756 this[kResponse] = response 58757 58758 const parser = new ByteParser(this) 58759 parser.on('drain', function onParserDrain () { 58760 this.ws[kResponse].socket.resume() 58761 }) 58762 58763 response.socket.ws = this 58764 this[kByteParser] = parser 58765 58766 // 1. Change the ready state to OPEN (1). 58767 this[kReadyState] = states.OPEN 58768 58769 // 2. Change the extensions attribute’s value to the extensions in use, if 58770 // it is not the null value. 58771 // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 58772 const extensions = response.headersList.get('sec-websocket-extensions') 58773 58774 if (extensions !== null) { 58775 this.#extensions = extensions 58776 } 58777 58778 // 3. Change the protocol attribute’s value to the subprotocol in use, if 58779 // it is not the null value. 58780 // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 58781 const protocol = response.headersList.get('sec-websocket-protocol') 58782 58783 if (protocol !== null) { 58784 this.#protocol = protocol 58785 } 58786 58787 // 4. Fire an event named open at the WebSocket object. 58788 fireEvent('open', this) 58789 } 58790 } 58791 58792 // https://websockets.spec.whatwg.org/#dom-websocket-connecting 58793 WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING 58794 // https://websockets.spec.whatwg.org/#dom-websocket-open 58795 WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN 58796 // https://websockets.spec.whatwg.org/#dom-websocket-closing 58797 WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING 58798 // https://websockets.spec.whatwg.org/#dom-websocket-closed 58799 WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED 58800 58801 Object.defineProperties(WebSocket.prototype, { 58802 CONNECTING: staticPropertyDescriptors, 58803 OPEN: staticPropertyDescriptors, 58804 CLOSING: staticPropertyDescriptors, 58805 CLOSED: staticPropertyDescriptors, 58806 url: kEnumerableProperty, 58807 readyState: kEnumerableProperty, 58808 bufferedAmount: kEnumerableProperty, 58809 onopen: kEnumerableProperty, 58810 onerror: kEnumerableProperty, 58811 onclose: kEnumerableProperty, 58812 close: kEnumerableProperty, 58813 onmessage: kEnumerableProperty, 58814 binaryType: kEnumerableProperty, 58815 send: kEnumerableProperty, 58816 extensions: kEnumerableProperty, 58817 protocol: kEnumerableProperty, 58818 [Symbol.toStringTag]: { 58819 value: 'WebSocket', 58820 writable: false, 58821 enumerable: false, 58822 configurable: true 58823 } 58824 }) 58825 58826 Object.defineProperties(WebSocket, { 58827 CONNECTING: staticPropertyDescriptors, 58828 OPEN: staticPropertyDescriptors, 58829 CLOSING: staticPropertyDescriptors, 58830 CLOSED: staticPropertyDescriptors 58831 }) 58832 58833 webidl.converters['sequence<DOMString>'] = webidl.sequenceConverter( 58834 webidl.converters.DOMString 58835 ) 58836 58837 webidl.converters['DOMString or sequence<DOMString>'] = function (V) { 58838 if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { 58839 return webidl.converters['sequence<DOMString>'](V) 58840 } 58841 58842 return webidl.converters.DOMString(V) 58843 } 58844 58845 // This implements the propsal made in https://github.com/whatwg/websockets/issues/42 58846 webidl.converters.WebSocketInit = webidl.dictionaryConverter([ 58847 { 58848 key: 'protocols', 58849 converter: webidl.converters['DOMString or sequence<DOMString>'], 58850 get defaultValue () { 58851 return [] 58852 } 58853 }, 58854 { 58855 key: 'dispatcher', 58856 converter: (V) => V, 58857 get defaultValue () { 58858 return getGlobalDispatcher() 58859 } 58860 }, 58861 { 58862 key: 'headers', 58863 converter: webidl.nullableConverter(webidl.converters.HeadersInit) 58864 } 58865 ]) 58866 58867 webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'] = function (V) { 58868 if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { 58869 return webidl.converters.WebSocketInit(V) 58870 } 58871 58872 return { protocols: webidl.converters['DOMString or sequence<DOMString>'](V) } 58873 } 58874 58875 webidl.converters.WebSocketSendData = function (V) { 58876 if (webidl.util.Type(V) === 'Object') { 58877 if (isBlobLike(V)) { 58878 return webidl.converters.Blob(V, { strict: false }) 58879 } 58880 58881 if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { 58882 return webidl.converters.BufferSource(V) 58883 } 58884 } 58885 58886 return webidl.converters.USVString(V) 58887 } 58888 58889 module.exports = { 58890 WebSocket 58891 } 58892 58893 58894 /***/ }), 58895 58896 /***/ 1747: 58897 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 58898 58899 var path = __nccwpck_require__(1017) 58900 58901 var uniqueSlug = __nccwpck_require__(7848) 58902 58903 module.exports = function (filepath, prefix, uniq) { 58904 return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq)) 58905 } 58906 58907 58908 /***/ }), 58909 58910 /***/ 7848: 58911 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 58912 58913 "use strict"; 58914 58915 var MurmurHash3 = __nccwpck_require__(2527) 58916 58917 module.exports = function (uniq) { 58918 if (uniq) { 58919 var hash = new MurmurHash3(uniq) 58920 return ('00000000' + hash.result().toString(16)).slice(-8) 58921 } else { 58922 return (Math.random().toString(16) + '0000000').slice(2, 10) 58923 } 58924 } 58925 58926 58927 /***/ }), 58928 58929 /***/ 5840: 58930 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 58931 58932 "use strict"; 58933 58934 58935 Object.defineProperty(exports, "__esModule", ({ 58936 value: true 58937 })); 58938 Object.defineProperty(exports, "v1", ({ 58939 enumerable: true, 58940 get: function () { 58941 return _v.default; 58942 } 58943 })); 58944 Object.defineProperty(exports, "v3", ({ 58945 enumerable: true, 58946 get: function () { 58947 return _v2.default; 58948 } 58949 })); 58950 Object.defineProperty(exports, "v4", ({ 58951 enumerable: true, 58952 get: function () { 58953 return _v3.default; 58954 } 58955 })); 58956 Object.defineProperty(exports, "v5", ({ 58957 enumerable: true, 58958 get: function () { 58959 return _v4.default; 58960 } 58961 })); 58962 Object.defineProperty(exports, "NIL", ({ 58963 enumerable: true, 58964 get: function () { 58965 return _nil.default; 58966 } 58967 })); 58968 Object.defineProperty(exports, "version", ({ 58969 enumerable: true, 58970 get: function () { 58971 return _version.default; 58972 } 58973 })); 58974 Object.defineProperty(exports, "validate", ({ 58975 enumerable: true, 58976 get: function () { 58977 return _validate.default; 58978 } 58979 })); 58980 Object.defineProperty(exports, "stringify", ({ 58981 enumerable: true, 58982 get: function () { 58983 return _stringify.default; 58984 } 58985 })); 58986 Object.defineProperty(exports, "parse", ({ 58987 enumerable: true, 58988 get: function () { 58989 return _parse.default; 58990 } 58991 })); 58992 58993 var _v = _interopRequireDefault(__nccwpck_require__(8628)); 58994 58995 var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); 58996 58997 var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); 58998 58999 var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); 59000 59001 var _nil = _interopRequireDefault(__nccwpck_require__(5332)); 59002 59003 var _version = _interopRequireDefault(__nccwpck_require__(1595)); 59004 59005 var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 59006 59007 var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 59008 59009 var _parse = _interopRequireDefault(__nccwpck_require__(2746)); 59010 59011 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59012 59013 /***/ }), 59014 59015 /***/ 4569: 59016 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59017 59018 "use strict"; 59019 59020 59021 Object.defineProperty(exports, "__esModule", ({ 59022 value: true 59023 })); 59024 exports["default"] = void 0; 59025 59026 var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); 59027 59028 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59029 59030 function md5(bytes) { 59031 if (Array.isArray(bytes)) { 59032 bytes = Buffer.from(bytes); 59033 } else if (typeof bytes === 'string') { 59034 bytes = Buffer.from(bytes, 'utf8'); 59035 } 59036 59037 return _crypto.default.createHash('md5').update(bytes).digest(); 59038 } 59039 59040 var _default = md5; 59041 exports["default"] = _default; 59042 59043 /***/ }), 59044 59045 /***/ 5332: 59046 /***/ ((__unused_webpack_module, exports) => { 59047 59048 "use strict"; 59049 59050 59051 Object.defineProperty(exports, "__esModule", ({ 59052 value: true 59053 })); 59054 exports["default"] = void 0; 59055 var _default = '00000000-0000-0000-0000-000000000000'; 59056 exports["default"] = _default; 59057 59058 /***/ }), 59059 59060 /***/ 2746: 59061 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59062 59063 "use strict"; 59064 59065 59066 Object.defineProperty(exports, "__esModule", ({ 59067 value: true 59068 })); 59069 exports["default"] = void 0; 59070 59071 var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 59072 59073 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59074 59075 function parse(uuid) { 59076 if (!(0, _validate.default)(uuid)) { 59077 throw TypeError('Invalid UUID'); 59078 } 59079 59080 let v; 59081 const arr = new Uint8Array(16); // Parse ########-....-....-....-............ 59082 59083 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; 59084 arr[1] = v >>> 16 & 0xff; 59085 arr[2] = v >>> 8 & 0xff; 59086 arr[3] = v & 0xff; // Parse ........-####-....-....-............ 59087 59088 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; 59089 arr[5] = v & 0xff; // Parse ........-....-####-....-............ 59090 59091 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; 59092 arr[7] = v & 0xff; // Parse ........-....-....-####-............ 59093 59094 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; 59095 arr[9] = v & 0xff; // Parse ........-....-....-....-############ 59096 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) 59097 59098 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; 59099 arr[11] = v / 0x100000000 & 0xff; 59100 arr[12] = v >>> 24 & 0xff; 59101 arr[13] = v >>> 16 & 0xff; 59102 arr[14] = v >>> 8 & 0xff; 59103 arr[15] = v & 0xff; 59104 return arr; 59105 } 59106 59107 var _default = parse; 59108 exports["default"] = _default; 59109 59110 /***/ }), 59111 59112 /***/ 814: 59113 /***/ ((__unused_webpack_module, exports) => { 59114 59115 "use strict"; 59116 59117 59118 Object.defineProperty(exports, "__esModule", ({ 59119 value: true 59120 })); 59121 exports["default"] = void 0; 59122 var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; 59123 exports["default"] = _default; 59124 59125 /***/ }), 59126 59127 /***/ 807: 59128 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59129 59130 "use strict"; 59131 59132 59133 Object.defineProperty(exports, "__esModule", ({ 59134 value: true 59135 })); 59136 exports["default"] = rng; 59137 59138 var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); 59139 59140 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59141 59142 const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate 59143 59144 let poolPtr = rnds8Pool.length; 59145 59146 function rng() { 59147 if (poolPtr > rnds8Pool.length - 16) { 59148 _crypto.default.randomFillSync(rnds8Pool); 59149 59150 poolPtr = 0; 59151 } 59152 59153 return rnds8Pool.slice(poolPtr, poolPtr += 16); 59154 } 59155 59156 /***/ }), 59157 59158 /***/ 5274: 59159 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59160 59161 "use strict"; 59162 59163 59164 Object.defineProperty(exports, "__esModule", ({ 59165 value: true 59166 })); 59167 exports["default"] = void 0; 59168 59169 var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); 59170 59171 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59172 59173 function sha1(bytes) { 59174 if (Array.isArray(bytes)) { 59175 bytes = Buffer.from(bytes); 59176 } else if (typeof bytes === 'string') { 59177 bytes = Buffer.from(bytes, 'utf8'); 59178 } 59179 59180 return _crypto.default.createHash('sha1').update(bytes).digest(); 59181 } 59182 59183 var _default = sha1; 59184 exports["default"] = _default; 59185 59186 /***/ }), 59187 59188 /***/ 8950: 59189 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59190 59191 "use strict"; 59192 59193 59194 Object.defineProperty(exports, "__esModule", ({ 59195 value: true 59196 })); 59197 exports["default"] = void 0; 59198 59199 var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 59200 59201 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59202 59203 /** 59204 * Convert array of 16 byte values to UUID string format of the form: 59205 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX 59206 */ 59207 const byteToHex = []; 59208 59209 for (let i = 0; i < 256; ++i) { 59210 byteToHex.push((i + 0x100).toString(16).substr(1)); 59211 } 59212 59213 function stringify(arr, offset = 0) { 59214 // Note: Be careful editing this code! It's been tuned for performance 59215 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 59216 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one 59217 // of the following: 59218 // - One or more input array values don't map to a hex octet (leading to 59219 // "undefined" in the uuid) 59220 // - Invalid input values for the RFC `version` or `variant` fields 59221 59222 if (!(0, _validate.default)(uuid)) { 59223 throw TypeError('Stringified UUID is invalid'); 59224 } 59225 59226 return uuid; 59227 } 59228 59229 var _default = stringify; 59230 exports["default"] = _default; 59231 59232 /***/ }), 59233 59234 /***/ 8628: 59235 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59236 59237 "use strict"; 59238 59239 59240 Object.defineProperty(exports, "__esModule", ({ 59241 value: true 59242 })); 59243 exports["default"] = void 0; 59244 59245 var _rng = _interopRequireDefault(__nccwpck_require__(807)); 59246 59247 var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 59248 59249 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59250 59251 // **`v1()` - Generate time-based UUID** 59252 // 59253 // Inspired by https://github.com/LiosK/UUID.js 59254 // and http://docs.python.org/library/uuid.html 59255 let _nodeId; 59256 59257 let _clockseq; // Previous uuid creation time 59258 59259 59260 let _lastMSecs = 0; 59261 let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details 59262 59263 function v1(options, buf, offset) { 59264 let i = buf && offset || 0; 59265 const b = buf || new Array(16); 59266 options = options || {}; 59267 let node = options.node || _nodeId; 59268 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not 59269 // specified. We do this lazily to minimize issues related to insufficient 59270 // system entropy. See #189 59271 59272 if (node == null || clockseq == null) { 59273 const seedBytes = options.random || (options.rng || _rng.default)(); 59274 59275 if (node == null) { 59276 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) 59277 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; 59278 } 59279 59280 if (clockseq == null) { 59281 // Per 4.2.2, randomize (14 bit) clockseq 59282 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; 59283 } 59284 } // UUID timestamps are 100 nano-second units since the Gregorian epoch, 59285 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so 59286 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' 59287 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. 59288 59289 59290 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock 59291 // cycle to simulate higher resolution clock 59292 59293 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) 59294 59295 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression 59296 59297 if (dt < 0 && options.clockseq === undefined) { 59298 clockseq = clockseq + 1 & 0x3fff; 59299 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new 59300 // time interval 59301 59302 59303 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { 59304 nsecs = 0; 59305 } // Per 4.2.1.2 Throw error if too many uuids are requested 59306 59307 59308 if (nsecs >= 10000) { 59309 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); 59310 } 59311 59312 _lastMSecs = msecs; 59313 _lastNSecs = nsecs; 59314 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch 59315 59316 msecs += 12219292800000; // `time_low` 59317 59318 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; 59319 b[i++] = tl >>> 24 & 0xff; 59320 b[i++] = tl >>> 16 & 0xff; 59321 b[i++] = tl >>> 8 & 0xff; 59322 b[i++] = tl & 0xff; // `time_mid` 59323 59324 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; 59325 b[i++] = tmh >>> 8 & 0xff; 59326 b[i++] = tmh & 0xff; // `time_high_and_version` 59327 59328 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version 59329 59330 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) 59331 59332 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` 59333 59334 b[i++] = clockseq & 0xff; // `node` 59335 59336 for (let n = 0; n < 6; ++n) { 59337 b[i + n] = node[n]; 59338 } 59339 59340 return buf || (0, _stringify.default)(b); 59341 } 59342 59343 var _default = v1; 59344 exports["default"] = _default; 59345 59346 /***/ }), 59347 59348 /***/ 6409: 59349 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59350 59351 "use strict"; 59352 59353 59354 Object.defineProperty(exports, "__esModule", ({ 59355 value: true 59356 })); 59357 exports["default"] = void 0; 59358 59359 var _v = _interopRequireDefault(__nccwpck_require__(5998)); 59360 59361 var _md = _interopRequireDefault(__nccwpck_require__(4569)); 59362 59363 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59364 59365 const v3 = (0, _v.default)('v3', 0x30, _md.default); 59366 var _default = v3; 59367 exports["default"] = _default; 59368 59369 /***/ }), 59370 59371 /***/ 5998: 59372 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59373 59374 "use strict"; 59375 59376 59377 Object.defineProperty(exports, "__esModule", ({ 59378 value: true 59379 })); 59380 exports["default"] = _default; 59381 exports.URL = exports.DNS = void 0; 59382 59383 var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 59384 59385 var _parse = _interopRequireDefault(__nccwpck_require__(2746)); 59386 59387 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59388 59389 function stringToBytes(str) { 59390 str = unescape(encodeURIComponent(str)); // UTF8 escape 59391 59392 const bytes = []; 59393 59394 for (let i = 0; i < str.length; ++i) { 59395 bytes.push(str.charCodeAt(i)); 59396 } 59397 59398 return bytes; 59399 } 59400 59401 const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; 59402 exports.DNS = DNS; 59403 const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; 59404 exports.URL = URL; 59405 59406 function _default(name, version, hashfunc) { 59407 function generateUUID(value, namespace, buf, offset) { 59408 if (typeof value === 'string') { 59409 value = stringToBytes(value); 59410 } 59411 59412 if (typeof namespace === 'string') { 59413 namespace = (0, _parse.default)(namespace); 59414 } 59415 59416 if (namespace.length !== 16) { 59417 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); 59418 } // Compute hash of namespace and value, Per 4.3 59419 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = 59420 // hashfunc([...namespace, ... value])` 59421 59422 59423 let bytes = new Uint8Array(16 + value.length); 59424 bytes.set(namespace); 59425 bytes.set(value, namespace.length); 59426 bytes = hashfunc(bytes); 59427 bytes[6] = bytes[6] & 0x0f | version; 59428 bytes[8] = bytes[8] & 0x3f | 0x80; 59429 59430 if (buf) { 59431 offset = offset || 0; 59432 59433 for (let i = 0; i < 16; ++i) { 59434 buf[offset + i] = bytes[i]; 59435 } 59436 59437 return buf; 59438 } 59439 59440 return (0, _stringify.default)(bytes); 59441 } // Function#name is not settable on some platforms (#270) 59442 59443 59444 try { 59445 generateUUID.name = name; // eslint-disable-next-line no-empty 59446 } catch (err) {} // For CommonJS default export support 59447 59448 59449 generateUUID.DNS = DNS; 59450 generateUUID.URL = URL; 59451 return generateUUID; 59452 } 59453 59454 /***/ }), 59455 59456 /***/ 5122: 59457 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59458 59459 "use strict"; 59460 59461 59462 Object.defineProperty(exports, "__esModule", ({ 59463 value: true 59464 })); 59465 exports["default"] = void 0; 59466 59467 var _rng = _interopRequireDefault(__nccwpck_require__(807)); 59468 59469 var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); 59470 59471 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59472 59473 function v4(options, buf, offset) { 59474 options = options || {}; 59475 59476 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` 59477 59478 59479 rnds[6] = rnds[6] & 0x0f | 0x40; 59480 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided 59481 59482 if (buf) { 59483 offset = offset || 0; 59484 59485 for (let i = 0; i < 16; ++i) { 59486 buf[offset + i] = rnds[i]; 59487 } 59488 59489 return buf; 59490 } 59491 59492 return (0, _stringify.default)(rnds); 59493 } 59494 59495 var _default = v4; 59496 exports["default"] = _default; 59497 59498 /***/ }), 59499 59500 /***/ 9120: 59501 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59502 59503 "use strict"; 59504 59505 59506 Object.defineProperty(exports, "__esModule", ({ 59507 value: true 59508 })); 59509 exports["default"] = void 0; 59510 59511 var _v = _interopRequireDefault(__nccwpck_require__(5998)); 59512 59513 var _sha = _interopRequireDefault(__nccwpck_require__(5274)); 59514 59515 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59516 59517 const v5 = (0, _v.default)('v5', 0x50, _sha.default); 59518 var _default = v5; 59519 exports["default"] = _default; 59520 59521 /***/ }), 59522 59523 /***/ 6900: 59524 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59525 59526 "use strict"; 59527 59528 59529 Object.defineProperty(exports, "__esModule", ({ 59530 value: true 59531 })); 59532 exports["default"] = void 0; 59533 59534 var _regex = _interopRequireDefault(__nccwpck_require__(814)); 59535 59536 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59537 59538 function validate(uuid) { 59539 return typeof uuid === 'string' && _regex.default.test(uuid); 59540 } 59541 59542 var _default = validate; 59543 exports["default"] = _default; 59544 59545 /***/ }), 59546 59547 /***/ 1595: 59548 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 59549 59550 "use strict"; 59551 59552 59553 Object.defineProperty(exports, "__esModule", ({ 59554 value: true 59555 })); 59556 exports["default"] = void 0; 59557 59558 var _validate = _interopRequireDefault(__nccwpck_require__(6900)); 59559 59560 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 59561 59562 function version(uuid) { 59563 if (!(0, _validate.default)(uuid)) { 59564 throw TypeError('Invalid UUID'); 59565 } 59566 59567 return parseInt(uuid.substr(14, 1), 16); 59568 } 59569 59570 var _default = version; 59571 exports["default"] = _default; 59572 59573 /***/ }), 59574 59575 /***/ 4091: 59576 /***/ ((module) => { 59577 59578 "use strict"; 59579 59580 module.exports = function (Yallist) { 59581 Yallist.prototype[Symbol.iterator] = function* () { 59582 for (let walker = this.head; walker; walker = walker.next) { 59583 yield walker.value 59584 } 59585 } 59586 } 59587 59588 59589 /***/ }), 59590 59591 /***/ 665: 59592 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 59593 59594 "use strict"; 59595 59596 module.exports = Yallist 59597 59598 Yallist.Node = Node 59599 Yallist.create = Yallist 59600 59601 function Yallist (list) { 59602 var self = this 59603 if (!(self instanceof Yallist)) { 59604 self = new Yallist() 59605 } 59606 59607 self.tail = null 59608 self.head = null 59609 self.length = 0 59610 59611 if (list && typeof list.forEach === 'function') { 59612 list.forEach(function (item) { 59613 self.push(item) 59614 }) 59615 } else if (arguments.length > 0) { 59616 for (var i = 0, l = arguments.length; i < l; i++) { 59617 self.push(arguments[i]) 59618 } 59619 } 59620 59621 return self 59622 } 59623 59624 Yallist.prototype.removeNode = function (node) { 59625 if (node.list !== this) { 59626 throw new Error('removing node which does not belong to this list') 59627 } 59628 59629 var next = node.next 59630 var prev = node.prev 59631 59632 if (next) { 59633 next.prev = prev 59634 } 59635 59636 if (prev) { 59637 prev.next = next 59638 } 59639 59640 if (node === this.head) { 59641 this.head = next 59642 } 59643 if (node === this.tail) { 59644 this.tail = prev 59645 } 59646 59647 node.list.length-- 59648 node.next = null 59649 node.prev = null 59650 node.list = null 59651 59652 return next 59653 } 59654 59655 Yallist.prototype.unshiftNode = function (node) { 59656 if (node === this.head) { 59657 return 59658 } 59659 59660 if (node.list) { 59661 node.list.removeNode(node) 59662 } 59663 59664 var head = this.head 59665 node.list = this 59666 node.next = head 59667 if (head) { 59668 head.prev = node 59669 } 59670 59671 this.head = node 59672 if (!this.tail) { 59673 this.tail = node 59674 } 59675 this.length++ 59676 } 59677 59678 Yallist.prototype.pushNode = function (node) { 59679 if (node === this.tail) { 59680 return 59681 } 59682 59683 if (node.list) { 59684 node.list.removeNode(node) 59685 } 59686 59687 var tail = this.tail 59688 node.list = this 59689 node.prev = tail 59690 if (tail) { 59691 tail.next = node 59692 } 59693 59694 this.tail = node 59695 if (!this.head) { 59696 this.head = node 59697 } 59698 this.length++ 59699 } 59700 59701 Yallist.prototype.push = function () { 59702 for (var i = 0, l = arguments.length; i < l; i++) { 59703 push(this, arguments[i]) 59704 } 59705 return this.length 59706 } 59707 59708 Yallist.prototype.unshift = function () { 59709 for (var i = 0, l = arguments.length; i < l; i++) { 59710 unshift(this, arguments[i]) 59711 } 59712 return this.length 59713 } 59714 59715 Yallist.prototype.pop = function () { 59716 if (!this.tail) { 59717 return undefined 59718 } 59719 59720 var res = this.tail.value 59721 this.tail = this.tail.prev 59722 if (this.tail) { 59723 this.tail.next = null 59724 } else { 59725 this.head = null 59726 } 59727 this.length-- 59728 return res 59729 } 59730 59731 Yallist.prototype.shift = function () { 59732 if (!this.head) { 59733 return undefined 59734 } 59735 59736 var res = this.head.value 59737 this.head = this.head.next 59738 if (this.head) { 59739 this.head.prev = null 59740 } else { 59741 this.tail = null 59742 } 59743 this.length-- 59744 return res 59745 } 59746 59747 Yallist.prototype.forEach = function (fn, thisp) { 59748 thisp = thisp || this 59749 for (var walker = this.head, i = 0; walker !== null; i++) { 59750 fn.call(thisp, walker.value, i, this) 59751 walker = walker.next 59752 } 59753 } 59754 59755 Yallist.prototype.forEachReverse = function (fn, thisp) { 59756 thisp = thisp || this 59757 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { 59758 fn.call(thisp, walker.value, i, this) 59759 walker = walker.prev 59760 } 59761 } 59762 59763 Yallist.prototype.get = function (n) { 59764 for (var i = 0, walker = this.head; walker !== null && i < n; i++) { 59765 // abort out of the list early if we hit a cycle 59766 walker = walker.next 59767 } 59768 if (i === n && walker !== null) { 59769 return walker.value 59770 } 59771 } 59772 59773 Yallist.prototype.getReverse = function (n) { 59774 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { 59775 // abort out of the list early if we hit a cycle 59776 walker = walker.prev 59777 } 59778 if (i === n && walker !== null) { 59779 return walker.value 59780 } 59781 } 59782 59783 Yallist.prototype.map = function (fn, thisp) { 59784 thisp = thisp || this 59785 var res = new Yallist() 59786 for (var walker = this.head; walker !== null;) { 59787 res.push(fn.call(thisp, walker.value, this)) 59788 walker = walker.next 59789 } 59790 return res 59791 } 59792 59793 Yallist.prototype.mapReverse = function (fn, thisp) { 59794 thisp = thisp || this 59795 var res = new Yallist() 59796 for (var walker = this.tail; walker !== null;) { 59797 res.push(fn.call(thisp, walker.value, this)) 59798 walker = walker.prev 59799 } 59800 return res 59801 } 59802 59803 Yallist.prototype.reduce = function (fn, initial) { 59804 var acc 59805 var walker = this.head 59806 if (arguments.length > 1) { 59807 acc = initial 59808 } else if (this.head) { 59809 walker = this.head.next 59810 acc = this.head.value 59811 } else { 59812 throw new TypeError('Reduce of empty list with no initial value') 59813 } 59814 59815 for (var i = 0; walker !== null; i++) { 59816 acc = fn(acc, walker.value, i) 59817 walker = walker.next 59818 } 59819 59820 return acc 59821 } 59822 59823 Yallist.prototype.reduceReverse = function (fn, initial) { 59824 var acc 59825 var walker = this.tail 59826 if (arguments.length > 1) { 59827 acc = initial 59828 } else if (this.tail) { 59829 walker = this.tail.prev 59830 acc = this.tail.value 59831 } else { 59832 throw new TypeError('Reduce of empty list with no initial value') 59833 } 59834 59835 for (var i = this.length - 1; walker !== null; i--) { 59836 acc = fn(acc, walker.value, i) 59837 walker = walker.prev 59838 } 59839 59840 return acc 59841 } 59842 59843 Yallist.prototype.toArray = function () { 59844 var arr = new Array(this.length) 59845 for (var i = 0, walker = this.head; walker !== null; i++) { 59846 arr[i] = walker.value 59847 walker = walker.next 59848 } 59849 return arr 59850 } 59851 59852 Yallist.prototype.toArrayReverse = function () { 59853 var arr = new Array(this.length) 59854 for (var i = 0, walker = this.tail; walker !== null; i++) { 59855 arr[i] = walker.value 59856 walker = walker.prev 59857 } 59858 return arr 59859 } 59860 59861 Yallist.prototype.slice = function (from, to) { 59862 to = to || this.length 59863 if (to < 0) { 59864 to += this.length 59865 } 59866 from = from || 0 59867 if (from < 0) { 59868 from += this.length 59869 } 59870 var ret = new Yallist() 59871 if (to < from || to < 0) { 59872 return ret 59873 } 59874 if (from < 0) { 59875 from = 0 59876 } 59877 if (to > this.length) { 59878 to = this.length 59879 } 59880 for (var i = 0, walker = this.head; walker !== null && i < from; i++) { 59881 walker = walker.next 59882 } 59883 for (; walker !== null && i < to; i++, walker = walker.next) { 59884 ret.push(walker.value) 59885 } 59886 return ret 59887 } 59888 59889 Yallist.prototype.sliceReverse = function (from, to) { 59890 to = to || this.length 59891 if (to < 0) { 59892 to += this.length 59893 } 59894 from = from || 0 59895 if (from < 0) { 59896 from += this.length 59897 } 59898 var ret = new Yallist() 59899 if (to < from || to < 0) { 59900 return ret 59901 } 59902 if (from < 0) { 59903 from = 0 59904 } 59905 if (to > this.length) { 59906 to = this.length 59907 } 59908 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { 59909 walker = walker.prev 59910 } 59911 for (; walker !== null && i > from; i--, walker = walker.prev) { 59912 ret.push(walker.value) 59913 } 59914 return ret 59915 } 59916 59917 Yallist.prototype.splice = function (start, deleteCount, ...nodes) { 59918 if (start > this.length) { 59919 start = this.length - 1 59920 } 59921 if (start < 0) { 59922 start = this.length + start; 59923 } 59924 59925 for (var i = 0, walker = this.head; walker !== null && i < start; i++) { 59926 walker = walker.next 59927 } 59928 59929 var ret = [] 59930 for (var i = 0; walker && i < deleteCount; i++) { 59931 ret.push(walker.value) 59932 walker = this.removeNode(walker) 59933 } 59934 if (walker === null) { 59935 walker = this.tail 59936 } 59937 59938 if (walker !== this.head && walker !== this.tail) { 59939 walker = walker.prev 59940 } 59941 59942 for (var i = 0; i < nodes.length; i++) { 59943 walker = insert(this, walker, nodes[i]) 59944 } 59945 return ret; 59946 } 59947 59948 Yallist.prototype.reverse = function () { 59949 var head = this.head 59950 var tail = this.tail 59951 for (var walker = head; walker !== null; walker = walker.prev) { 59952 var p = walker.prev 59953 walker.prev = walker.next 59954 walker.next = p 59955 } 59956 this.head = tail 59957 this.tail = head 59958 return this 59959 } 59960 59961 function insert (self, node, value) { 59962 var inserted = node === self.head ? 59963 new Node(value, null, node, self) : 59964 new Node(value, node, node.next, self) 59965 59966 if (inserted.next === null) { 59967 self.tail = inserted 59968 } 59969 if (inserted.prev === null) { 59970 self.head = inserted 59971 } 59972 59973 self.length++ 59974 59975 return inserted 59976 } 59977 59978 function push (self, item) { 59979 self.tail = new Node(item, self.tail, null, self) 59980 if (!self.head) { 59981 self.head = self.tail 59982 } 59983 self.length++ 59984 } 59985 59986 function unshift (self, item) { 59987 self.head = new Node(item, null, self.head, self) 59988 if (!self.tail) { 59989 self.tail = self.head 59990 } 59991 self.length++ 59992 } 59993 59994 function Node (value, prev, next, list) { 59995 if (!(this instanceof Node)) { 59996 return new Node(value, prev, next, list) 59997 } 59998 59999 this.list = list 60000 this.value = value 60001 60002 if (prev) { 60003 prev.next = this 60004 this.prev = prev 60005 } else { 60006 this.prev = null 60007 } 60008 60009 if (next) { 60010 next.prev = this 60011 this.next = next 60012 } else { 60013 this.next = null 60014 } 60015 } 60016 60017 try { 60018 // add if support for Symbol.iterator is present 60019 __nccwpck_require__(4091)(Yallist) 60020 } catch (er) {} 60021 60022 60023 /***/ }), 60024 60025 /***/ 9491: 60026 /***/ ((module) => { 60027 60028 "use strict"; 60029 module.exports = require("assert"); 60030 60031 /***/ }), 60032 60033 /***/ 852: 60034 /***/ ((module) => { 60035 60036 "use strict"; 60037 module.exports = require("async_hooks"); 60038 60039 /***/ }), 60040 60041 /***/ 4300: 60042 /***/ ((module) => { 60043 60044 "use strict"; 60045 module.exports = require("buffer"); 60046 60047 /***/ }), 60048 60049 /***/ 6206: 60050 /***/ ((module) => { 60051 60052 "use strict"; 60053 module.exports = require("console"); 60054 60055 /***/ }), 60056 60057 /***/ 6113: 60058 /***/ ((module) => { 60059 60060 "use strict"; 60061 module.exports = require("crypto"); 60062 60063 /***/ }), 60064 60065 /***/ 7643: 60066 /***/ ((module) => { 60067 60068 "use strict"; 60069 module.exports = require("diagnostics_channel"); 60070 60071 /***/ }), 60072 60073 /***/ 9523: 60074 /***/ ((module) => { 60075 60076 "use strict"; 60077 module.exports = require("dns"); 60078 60079 /***/ }), 60080 60081 /***/ 3975: 60082 /***/ ((module) => { 60083 60084 "use strict"; 60085 module.exports = require("encoding"); 60086 60087 /***/ }), 60088 60089 /***/ 2361: 60090 /***/ ((module) => { 60091 60092 "use strict"; 60093 module.exports = require("events"); 60094 60095 /***/ }), 60096 60097 /***/ 7147: 60098 /***/ ((module) => { 60099 60100 "use strict"; 60101 module.exports = require("fs"); 60102 60103 /***/ }), 60104 60105 /***/ 3292: 60106 /***/ ((module) => { 60107 60108 "use strict"; 60109 module.exports = require("fs/promises"); 60110 60111 /***/ }), 60112 60113 /***/ 3685: 60114 /***/ ((module) => { 60115 60116 "use strict"; 60117 module.exports = require("http"); 60118 60119 /***/ }), 60120 60121 /***/ 5158: 60122 /***/ ((module) => { 60123 60124 "use strict"; 60125 module.exports = require("http2"); 60126 60127 /***/ }), 60128 60129 /***/ 5687: 60130 /***/ ((module) => { 60131 60132 "use strict"; 60133 module.exports = require("https"); 60134 60135 /***/ }), 60136 60137 /***/ 1808: 60138 /***/ ((module) => { 60139 60140 "use strict"; 60141 module.exports = require("net"); 60142 60143 /***/ }), 60144 60145 /***/ 5673: 60146 /***/ ((module) => { 60147 60148 "use strict"; 60149 module.exports = require("node:events"); 60150 60151 /***/ }), 60152 60153 /***/ 4492: 60154 /***/ ((module) => { 60155 60156 "use strict"; 60157 module.exports = require("node:stream"); 60158 60159 /***/ }), 60160 60161 /***/ 7261: 60162 /***/ ((module) => { 60163 60164 "use strict"; 60165 module.exports = require("node:util"); 60166 60167 /***/ }), 60168 60169 /***/ 2037: 60170 /***/ ((module) => { 60171 60172 "use strict"; 60173 module.exports = require("os"); 60174 60175 /***/ }), 60176 60177 /***/ 1017: 60178 /***/ ((module) => { 60179 60180 "use strict"; 60181 module.exports = require("path"); 60182 60183 /***/ }), 60184 60185 /***/ 4074: 60186 /***/ ((module) => { 60187 60188 "use strict"; 60189 module.exports = require("perf_hooks"); 60190 60191 /***/ }), 60192 60193 /***/ 7282: 60194 /***/ ((module) => { 60195 60196 "use strict"; 60197 module.exports = require("process"); 60198 60199 /***/ }), 60200 60201 /***/ 3477: 60202 /***/ ((module) => { 60203 60204 "use strict"; 60205 module.exports = require("querystring"); 60206 60207 /***/ }), 60208 60209 /***/ 2781: 60210 /***/ ((module) => { 60211 60212 "use strict"; 60213 module.exports = require("stream"); 60214 60215 /***/ }), 60216 60217 /***/ 5356: 60218 /***/ ((module) => { 60219 60220 "use strict"; 60221 module.exports = require("stream/web"); 60222 60223 /***/ }), 60224 60225 /***/ 1576: 60226 /***/ ((module) => { 60227 60228 "use strict"; 60229 module.exports = require("string_decoder"); 60230 60231 /***/ }), 60232 60233 /***/ 8670: 60234 /***/ ((module) => { 60235 60236 "use strict"; 60237 module.exports = require("timers/promises"); 60238 60239 /***/ }), 60240 60241 /***/ 4404: 60242 /***/ ((module) => { 60243 60244 "use strict"; 60245 module.exports = require("tls"); 60246 60247 /***/ }), 60248 60249 /***/ 6224: 60250 /***/ ((module) => { 60251 60252 "use strict"; 60253 module.exports = require("tty"); 60254 60255 /***/ }), 60256 60257 /***/ 7310: 60258 /***/ ((module) => { 60259 60260 "use strict"; 60261 module.exports = require("url"); 60262 60263 /***/ }), 60264 60265 /***/ 3837: 60266 /***/ ((module) => { 60267 60268 "use strict"; 60269 module.exports = require("util"); 60270 60271 /***/ }), 60272 60273 /***/ 9830: 60274 /***/ ((module) => { 60275 60276 "use strict"; 60277 module.exports = require("util/types"); 60278 60279 /***/ }), 60280 60281 /***/ 1267: 60282 /***/ ((module) => { 60283 60284 "use strict"; 60285 module.exports = require("worker_threads"); 60286 60287 /***/ }), 60288 60289 /***/ 9796: 60290 /***/ ((module) => { 60291 60292 "use strict"; 60293 module.exports = require("zlib"); 60294 60295 /***/ }), 60296 60297 /***/ 2960: 60298 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60299 60300 "use strict"; 60301 60302 60303 const WritableStream = (__nccwpck_require__(4492).Writable) 60304 const inherits = (__nccwpck_require__(7261).inherits) 60305 60306 const StreamSearch = __nccwpck_require__(1142) 60307 60308 const PartStream = __nccwpck_require__(1620) 60309 const HeaderParser = __nccwpck_require__(2032) 60310 60311 const DASH = 45 60312 const B_ONEDASH = Buffer.from('-') 60313 const B_CRLF = Buffer.from('\r\n') 60314 const EMPTY_FN = function () {} 60315 60316 function Dicer (cfg) { 60317 if (!(this instanceof Dicer)) { return new Dicer(cfg) } 60318 WritableStream.call(this, cfg) 60319 60320 if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } 60321 60322 if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } 60323 60324 this._headerFirst = cfg.headerFirst 60325 60326 this._dashes = 0 60327 this._parts = 0 60328 this._finished = false 60329 this._realFinish = false 60330 this._isPreamble = true 60331 this._justMatched = false 60332 this._firstWrite = true 60333 this._inHeader = true 60334 this._part = undefined 60335 this._cb = undefined 60336 this._ignoreData = false 60337 this._partOpts = { highWaterMark: cfg.partHwm } 60338 this._pause = false 60339 60340 const self = this 60341 this._hparser = new HeaderParser(cfg) 60342 this._hparser.on('header', function (header) { 60343 self._inHeader = false 60344 self._part.emit('header', header) 60345 }) 60346 } 60347 inherits(Dicer, WritableStream) 60348 60349 Dicer.prototype.emit = function (ev) { 60350 if (ev === 'finish' && !this._realFinish) { 60351 if (!this._finished) { 60352 const self = this 60353 process.nextTick(function () { 60354 self.emit('error', new Error('Unexpected end of multipart data')) 60355 if (self._part && !self._ignoreData) { 60356 const type = (self._isPreamble ? 'Preamble' : 'Part') 60357 self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) 60358 self._part.push(null) 60359 process.nextTick(function () { 60360 self._realFinish = true 60361 self.emit('finish') 60362 self._realFinish = false 60363 }) 60364 return 60365 } 60366 self._realFinish = true 60367 self.emit('finish') 60368 self._realFinish = false 60369 }) 60370 } 60371 } else { WritableStream.prototype.emit.apply(this, arguments) } 60372 } 60373 60374 Dicer.prototype._write = function (data, encoding, cb) { 60375 // ignore unexpected data (e.g. extra trailer data after finished) 60376 if (!this._hparser && !this._bparser) { return cb() } 60377 60378 if (this._headerFirst && this._isPreamble) { 60379 if (!this._part) { 60380 this._part = new PartStream(this._partOpts) 60381 if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } 60382 } 60383 const r = this._hparser.push(data) 60384 if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } 60385 } 60386 60387 // allows for "easier" testing 60388 if (this._firstWrite) { 60389 this._bparser.push(B_CRLF) 60390 this._firstWrite = false 60391 } 60392 60393 this._bparser.push(data) 60394 60395 if (this._pause) { this._cb = cb } else { cb() } 60396 } 60397 60398 Dicer.prototype.reset = function () { 60399 this._part = undefined 60400 this._bparser = undefined 60401 this._hparser = undefined 60402 } 60403 60404 Dicer.prototype.setBoundary = function (boundary) { 60405 const self = this 60406 this._bparser = new StreamSearch('\r\n--' + boundary) 60407 this._bparser.on('info', function (isMatch, data, start, end) { 60408 self._oninfo(isMatch, data, start, end) 60409 }) 60410 } 60411 60412 Dicer.prototype._ignore = function () { 60413 if (this._part && !this._ignoreData) { 60414 this._ignoreData = true 60415 this._part.on('error', EMPTY_FN) 60416 // we must perform some kind of read on the stream even though we are 60417 // ignoring the data, otherwise node's Readable stream will not emit 'end' 60418 // after pushing null to the stream 60419 this._part.resume() 60420 } 60421 } 60422 60423 Dicer.prototype._oninfo = function (isMatch, data, start, end) { 60424 let buf; const self = this; let i = 0; let r; let shouldWriteMore = true 60425 60426 if (!this._part && this._justMatched && data) { 60427 while (this._dashes < 2 && (start + i) < end) { 60428 if (data[start + i] === DASH) { 60429 ++i 60430 ++this._dashes 60431 } else { 60432 if (this._dashes) { buf = B_ONEDASH } 60433 this._dashes = 0 60434 break 60435 } 60436 } 60437 if (this._dashes === 2) { 60438 if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } 60439 this.reset() 60440 this._finished = true 60441 // no more parts will be added 60442 if (self._parts === 0) { 60443 self._realFinish = true 60444 self.emit('finish') 60445 self._realFinish = false 60446 } 60447 } 60448 if (this._dashes) { return } 60449 } 60450 if (this._justMatched) { this._justMatched = false } 60451 if (!this._part) { 60452 this._part = new PartStream(this._partOpts) 60453 this._part._read = function (n) { 60454 self._unpause() 60455 } 60456 if (this._isPreamble && this.listenerCount('preamble') !== 0) { 60457 this.emit('preamble', this._part) 60458 } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { 60459 this.emit('part', this._part) 60460 } else { 60461 this._ignore() 60462 } 60463 if (!this._isPreamble) { this._inHeader = true } 60464 } 60465 if (data && start < end && !this._ignoreData) { 60466 if (this._isPreamble || !this._inHeader) { 60467 if (buf) { shouldWriteMore = this._part.push(buf) } 60468 shouldWriteMore = this._part.push(data.slice(start, end)) 60469 if (!shouldWriteMore) { this._pause = true } 60470 } else if (!this._isPreamble && this._inHeader) { 60471 if (buf) { this._hparser.push(buf) } 60472 r = this._hparser.push(data.slice(start, end)) 60473 if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } 60474 } 60475 } 60476 if (isMatch) { 60477 this._hparser.reset() 60478 if (this._isPreamble) { this._isPreamble = false } else { 60479 if (start !== end) { 60480 ++this._parts 60481 this._part.on('end', function () { 60482 if (--self._parts === 0) { 60483 if (self._finished) { 60484 self._realFinish = true 60485 self.emit('finish') 60486 self._realFinish = false 60487 } else { 60488 self._unpause() 60489 } 60490 } 60491 }) 60492 } 60493 } 60494 this._part.push(null) 60495 this._part = undefined 60496 this._ignoreData = false 60497 this._justMatched = true 60498 this._dashes = 0 60499 } 60500 } 60501 60502 Dicer.prototype._unpause = function () { 60503 if (!this._pause) { return } 60504 60505 this._pause = false 60506 if (this._cb) { 60507 const cb = this._cb 60508 this._cb = undefined 60509 cb() 60510 } 60511 } 60512 60513 module.exports = Dicer 60514 60515 60516 /***/ }), 60517 60518 /***/ 2032: 60519 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60520 60521 "use strict"; 60522 60523 60524 const EventEmitter = (__nccwpck_require__(5673).EventEmitter) 60525 const inherits = (__nccwpck_require__(7261).inherits) 60526 const getLimit = __nccwpck_require__(1467) 60527 60528 const StreamSearch = __nccwpck_require__(1142) 60529 60530 const B_DCRLF = Buffer.from('\r\n\r\n') 60531 const RE_CRLF = /\r\n/g 60532 const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex 60533 60534 function HeaderParser (cfg) { 60535 EventEmitter.call(this) 60536 60537 cfg = cfg || {} 60538 const self = this 60539 this.nread = 0 60540 this.maxed = false 60541 this.npairs = 0 60542 this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) 60543 this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) 60544 this.buffer = '' 60545 this.header = {} 60546 this.finished = false 60547 this.ss = new StreamSearch(B_DCRLF) 60548 this.ss.on('info', function (isMatch, data, start, end) { 60549 if (data && !self.maxed) { 60550 if (self.nread + end - start >= self.maxHeaderSize) { 60551 end = self.maxHeaderSize - self.nread + start 60552 self.nread = self.maxHeaderSize 60553 self.maxed = true 60554 } else { self.nread += (end - start) } 60555 60556 self.buffer += data.toString('binary', start, end) 60557 } 60558 if (isMatch) { self._finish() } 60559 }) 60560 } 60561 inherits(HeaderParser, EventEmitter) 60562 60563 HeaderParser.prototype.push = function (data) { 60564 const r = this.ss.push(data) 60565 if (this.finished) { return r } 60566 } 60567 60568 HeaderParser.prototype.reset = function () { 60569 this.finished = false 60570 this.buffer = '' 60571 this.header = {} 60572 this.ss.reset() 60573 } 60574 60575 HeaderParser.prototype._finish = function () { 60576 if (this.buffer) { this._parseHeader() } 60577 this.ss.matches = this.ss.maxMatches 60578 const header = this.header 60579 this.header = {} 60580 this.buffer = '' 60581 this.finished = true 60582 this.nread = this.npairs = 0 60583 this.maxed = false 60584 this.emit('header', header) 60585 } 60586 60587 HeaderParser.prototype._parseHeader = function () { 60588 if (this.npairs === this.maxHeaderPairs) { return } 60589 60590 const lines = this.buffer.split(RE_CRLF) 60591 const len = lines.length 60592 let m, h 60593 60594 for (var i = 0; i < len; ++i) { // eslint-disable-line no-var 60595 if (lines[i].length === 0) { continue } 60596 if (lines[i][0] === '\t' || lines[i][0] === ' ') { 60597 // folded header content 60598 // RFC2822 says to just remove the CRLF and not the whitespace following 60599 // it, so we follow the RFC and include the leading whitespace ... 60600 if (h) { 60601 this.header[h][this.header[h].length - 1] += lines[i] 60602 continue 60603 } 60604 } 60605 60606 const posColon = lines[i].indexOf(':') 60607 if ( 60608 posColon === -1 || 60609 posColon === 0 60610 ) { 60611 return 60612 } 60613 m = RE_HDR.exec(lines[i]) 60614 h = m[1].toLowerCase() 60615 this.header[h] = this.header[h] || [] 60616 this.header[h].push((m[2] || '')) 60617 if (++this.npairs === this.maxHeaderPairs) { break } 60618 } 60619 } 60620 60621 module.exports = HeaderParser 60622 60623 60624 /***/ }), 60625 60626 /***/ 1620: 60627 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60628 60629 "use strict"; 60630 60631 60632 const inherits = (__nccwpck_require__(7261).inherits) 60633 const ReadableStream = (__nccwpck_require__(4492).Readable) 60634 60635 function PartStream (opts) { 60636 ReadableStream.call(this, opts) 60637 } 60638 inherits(PartStream, ReadableStream) 60639 60640 PartStream.prototype._read = function (n) {} 60641 60642 module.exports = PartStream 60643 60644 60645 /***/ }), 60646 60647 /***/ 1142: 60648 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60649 60650 "use strict"; 60651 60652 60653 /** 60654 * Copyright Brian White. All rights reserved. 60655 * 60656 * @see https://github.com/mscdex/streamsearch 60657 * 60658 * Permission is hereby granted, free of charge, to any person obtaining a copy 60659 * of this software and associated documentation files (the "Software"), to 60660 * deal in the Software without restriction, including without limitation the 60661 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 60662 * sell copies of the Software, and to permit persons to whom the Software is 60663 * furnished to do so, subject to the following conditions: 60664 * 60665 * The above copyright notice and this permission notice shall be included in 60666 * all copies or substantial portions of the Software. 60667 * 60668 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 60669 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 60670 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 60671 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 60672 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 60673 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 60674 * IN THE SOFTWARE. 60675 * 60676 * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation 60677 * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool 60678 */ 60679 const EventEmitter = (__nccwpck_require__(5673).EventEmitter) 60680 const inherits = (__nccwpck_require__(7261).inherits) 60681 60682 function SBMH (needle) { 60683 if (typeof needle === 'string') { 60684 needle = Buffer.from(needle) 60685 } 60686 60687 if (!Buffer.isBuffer(needle)) { 60688 throw new TypeError('The needle has to be a String or a Buffer.') 60689 } 60690 60691 const needleLength = needle.length 60692 60693 if (needleLength === 0) { 60694 throw new Error('The needle cannot be an empty String/Buffer.') 60695 } 60696 60697 if (needleLength > 256) { 60698 throw new Error('The needle cannot have a length bigger than 256.') 60699 } 60700 60701 this.maxMatches = Infinity 60702 this.matches = 0 60703 60704 this._occ = new Array(256) 60705 .fill(needleLength) // Initialize occurrence table. 60706 this._lookbehind_size = 0 60707 this._needle = needle 60708 this._bufpos = 0 60709 60710 this._lookbehind = Buffer.alloc(needleLength) 60711 60712 // Populate occurrence table with analysis of the needle, 60713 // ignoring last letter. 60714 for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var 60715 this._occ[needle[i]] = needleLength - 1 - i 60716 } 60717 } 60718 inherits(SBMH, EventEmitter) 60719 60720 SBMH.prototype.reset = function () { 60721 this._lookbehind_size = 0 60722 this.matches = 0 60723 this._bufpos = 0 60724 } 60725 60726 SBMH.prototype.push = function (chunk, pos) { 60727 if (!Buffer.isBuffer(chunk)) { 60728 chunk = Buffer.from(chunk, 'binary') 60729 } 60730 const chlen = chunk.length 60731 this._bufpos = pos || 0 60732 let r 60733 while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } 60734 return r 60735 } 60736 60737 SBMH.prototype._sbmh_feed = function (data) { 60738 const len = data.length 60739 const needle = this._needle 60740 const needleLength = needle.length 60741 const lastNeedleChar = needle[needleLength - 1] 60742 60743 // Positive: points to a position in `data` 60744 // pos == 3 points to data[3] 60745 // Negative: points to a position in the lookbehind buffer 60746 // pos == -2 points to lookbehind[lookbehind_size - 2] 60747 let pos = -this._lookbehind_size 60748 let ch 60749 60750 if (pos < 0) { 60751 // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool 60752 // search with character lookup code that considers both the 60753 // lookbehind buffer and the current round's haystack data. 60754 // 60755 // Loop until 60756 // there is a match. 60757 // or until 60758 // we've moved past the position that requires the 60759 // lookbehind buffer. In this case we switch to the 60760 // optimized loop. 60761 // or until 60762 // the character to look at lies outside the haystack. 60763 while (pos < 0 && pos <= len - needleLength) { 60764 ch = this._sbmh_lookup_char(data, pos + needleLength - 1) 60765 60766 if ( 60767 ch === lastNeedleChar && 60768 this._sbmh_memcmp(data, pos, needleLength - 1) 60769 ) { 60770 this._lookbehind_size = 0 60771 ++this.matches 60772 this.emit('info', true) 60773 60774 return (this._bufpos = pos + needleLength) 60775 } 60776 pos += this._occ[ch] 60777 } 60778 60779 // No match. 60780 60781 if (pos < 0) { 60782 // There's too few data for Boyer-Moore-Horspool to run, 60783 // so let's use a different algorithm to skip as much as 60784 // we can. 60785 // Forward pos until 60786 // the trailing part of lookbehind + data 60787 // looks like the beginning of the needle 60788 // or until 60789 // pos == 0 60790 while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } 60791 } 60792 60793 if (pos >= 0) { 60794 // Discard lookbehind buffer. 60795 this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) 60796 this._lookbehind_size = 0 60797 } else { 60798 // Cut off part of the lookbehind buffer that has 60799 // been processed and append the entire haystack 60800 // into it. 60801 const bytesToCutOff = this._lookbehind_size + pos 60802 if (bytesToCutOff > 0) { 60803 // The cut off data is guaranteed not to contain the needle. 60804 this.emit('info', false, this._lookbehind, 0, bytesToCutOff) 60805 } 60806 60807 this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, 60808 this._lookbehind_size - bytesToCutOff) 60809 this._lookbehind_size -= bytesToCutOff 60810 60811 data.copy(this._lookbehind, this._lookbehind_size) 60812 this._lookbehind_size += len 60813 60814 this._bufpos = len 60815 return len 60816 } 60817 } 60818 60819 pos += (pos >= 0) * this._bufpos 60820 60821 // Lookbehind buffer is now empty. We only need to check if the 60822 // needle is in the haystack. 60823 if (data.indexOf(needle, pos) !== -1) { 60824 pos = data.indexOf(needle, pos) 60825 ++this.matches 60826 if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } 60827 60828 return (this._bufpos = pos + needleLength) 60829 } else { 60830 pos = len - needleLength 60831 } 60832 60833 // There was no match. If there's trailing haystack data that we cannot 60834 // match yet using the Boyer-Moore-Horspool algorithm (because the trailing 60835 // data is less than the needle size) then match using a modified 60836 // algorithm that starts matching from the beginning instead of the end. 60837 // Whatever trailing data is left after running this algorithm is added to 60838 // the lookbehind buffer. 60839 while ( 60840 pos < len && 60841 ( 60842 data[pos] !== needle[0] || 60843 ( 60844 (Buffer.compare( 60845 data.subarray(pos, pos + len - pos), 60846 needle.subarray(0, len - pos) 60847 ) !== 0) 60848 ) 60849 ) 60850 ) { 60851 ++pos 60852 } 60853 if (pos < len) { 60854 data.copy(this._lookbehind, 0, pos, pos + (len - pos)) 60855 this._lookbehind_size = len - pos 60856 } 60857 60858 // Everything until pos is guaranteed not to contain needle data. 60859 if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } 60860 60861 this._bufpos = len 60862 return len 60863 } 60864 60865 SBMH.prototype._sbmh_lookup_char = function (data, pos) { 60866 return (pos < 0) 60867 ? this._lookbehind[this._lookbehind_size + pos] 60868 : data[pos] 60869 } 60870 60871 SBMH.prototype._sbmh_memcmp = function (data, pos, len) { 60872 for (var i = 0; i < len; ++i) { // eslint-disable-line no-var 60873 if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } 60874 } 60875 return true 60876 } 60877 60878 module.exports = SBMH 60879 60880 60881 /***/ }), 60882 60883 /***/ 727: 60884 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60885 60886 "use strict"; 60887 60888 60889 const WritableStream = (__nccwpck_require__(4492).Writable) 60890 const { inherits } = __nccwpck_require__(7261) 60891 const Dicer = __nccwpck_require__(2960) 60892 60893 const MultipartParser = __nccwpck_require__(2183) 60894 const UrlencodedParser = __nccwpck_require__(8306) 60895 const parseParams = __nccwpck_require__(1854) 60896 60897 function Busboy (opts) { 60898 if (!(this instanceof Busboy)) { return new Busboy(opts) } 60899 60900 if (typeof opts !== 'object') { 60901 throw new TypeError('Busboy expected an options-Object.') 60902 } 60903 if (typeof opts.headers !== 'object') { 60904 throw new TypeError('Busboy expected an options-Object with headers-attribute.') 60905 } 60906 if (typeof opts.headers['content-type'] !== 'string') { 60907 throw new TypeError('Missing Content-Type-header.') 60908 } 60909 60910 const { 60911 headers, 60912 ...streamOptions 60913 } = opts 60914 60915 this.opts = { 60916 autoDestroy: false, 60917 ...streamOptions 60918 } 60919 WritableStream.call(this, this.opts) 60920 60921 this._done = false 60922 this._parser = this.getParserByHeaders(headers) 60923 this._finished = false 60924 } 60925 inherits(Busboy, WritableStream) 60926 60927 Busboy.prototype.emit = function (ev) { 60928 if (ev === 'finish') { 60929 if (!this._done) { 60930 this._parser?.end() 60931 return 60932 } else if (this._finished) { 60933 return 60934 } 60935 this._finished = true 60936 } 60937 WritableStream.prototype.emit.apply(this, arguments) 60938 } 60939 60940 Busboy.prototype.getParserByHeaders = function (headers) { 60941 const parsed = parseParams(headers['content-type']) 60942 60943 const cfg = { 60944 defCharset: this.opts.defCharset, 60945 fileHwm: this.opts.fileHwm, 60946 headers, 60947 highWaterMark: this.opts.highWaterMark, 60948 isPartAFile: this.opts.isPartAFile, 60949 limits: this.opts.limits, 60950 parsedConType: parsed, 60951 preservePath: this.opts.preservePath 60952 } 60953 60954 if (MultipartParser.detect.test(parsed[0])) { 60955 return new MultipartParser(this, cfg) 60956 } 60957 if (UrlencodedParser.detect.test(parsed[0])) { 60958 return new UrlencodedParser(this, cfg) 60959 } 60960 throw new Error('Unsupported Content-Type.') 60961 } 60962 60963 Busboy.prototype._write = function (chunk, encoding, cb) { 60964 this._parser.write(chunk, cb) 60965 } 60966 60967 module.exports = Busboy 60968 module.exports["default"] = Busboy 60969 module.exports.Busboy = Busboy 60970 60971 module.exports.Dicer = Dicer 60972 60973 60974 /***/ }), 60975 60976 /***/ 2183: 60977 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 60978 60979 "use strict"; 60980 60981 60982 // TODO: 60983 // * support 1 nested multipart level 60984 // (see second multipart example here: 60985 // http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) 60986 // * support limits.fieldNameSize 60987 // -- this will require modifications to utils.parseParams 60988 60989 const { Readable } = __nccwpck_require__(4492) 60990 const { inherits } = __nccwpck_require__(7261) 60991 60992 const Dicer = __nccwpck_require__(2960) 60993 60994 const parseParams = __nccwpck_require__(1854) 60995 const decodeText = __nccwpck_require__(4619) 60996 const basename = __nccwpck_require__(8647) 60997 const getLimit = __nccwpck_require__(1467) 60998 60999 const RE_BOUNDARY = /^boundary$/i 61000 const RE_FIELD = /^form-data$/i 61001 const RE_CHARSET = /^charset$/i 61002 const RE_FILENAME = /^filename$/i 61003 const RE_NAME = /^name$/i 61004 61005 Multipart.detect = /^multipart\/form-data/i 61006 function Multipart (boy, cfg) { 61007 let i 61008 let len 61009 const self = this 61010 let boundary 61011 const limits = cfg.limits 61012 const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) 61013 const parsedConType = cfg.parsedConType || [] 61014 const defCharset = cfg.defCharset || 'utf8' 61015 const preservePath = cfg.preservePath 61016 const fileOpts = { highWaterMark: cfg.fileHwm } 61017 61018 for (i = 0, len = parsedConType.length; i < len; ++i) { 61019 if (Array.isArray(parsedConType[i]) && 61020 RE_BOUNDARY.test(parsedConType[i][0])) { 61021 boundary = parsedConType[i][1] 61022 break 61023 } 61024 } 61025 61026 function checkFinished () { 61027 if (nends === 0 && finished && !boy._done) { 61028 finished = false 61029 self.end() 61030 } 61031 } 61032 61033 if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } 61034 61035 const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) 61036 const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) 61037 const filesLimit = getLimit(limits, 'files', Infinity) 61038 const fieldsLimit = getLimit(limits, 'fields', Infinity) 61039 const partsLimit = getLimit(limits, 'parts', Infinity) 61040 const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) 61041 const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) 61042 61043 let nfiles = 0 61044 let nfields = 0 61045 let nends = 0 61046 let curFile 61047 let curField 61048 let finished = false 61049 61050 this._needDrain = false 61051 this._pause = false 61052 this._cb = undefined 61053 this._nparts = 0 61054 this._boy = boy 61055 61056 const parserCfg = { 61057 boundary, 61058 maxHeaderPairs: headerPairsLimit, 61059 maxHeaderSize: headerSizeLimit, 61060 partHwm: fileOpts.highWaterMark, 61061 highWaterMark: cfg.highWaterMark 61062 } 61063 61064 this.parser = new Dicer(parserCfg) 61065 this.parser.on('drain', function () { 61066 self._needDrain = false 61067 if (self._cb && !self._pause) { 61068 const cb = self._cb 61069 self._cb = undefined 61070 cb() 61071 } 61072 }).on('part', function onPart (part) { 61073 if (++self._nparts > partsLimit) { 61074 self.parser.removeListener('part', onPart) 61075 self.parser.on('part', skipPart) 61076 boy.hitPartsLimit = true 61077 boy.emit('partsLimit') 61078 return skipPart(part) 61079 } 61080 61081 // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let 61082 // us emit 'end' early since we know the part has ended if we are already 61083 // seeing the next part 61084 if (curField) { 61085 const field = curField 61086 field.emit('end') 61087 field.removeAllListeners('end') 61088 } 61089 61090 part.on('header', function (header) { 61091 let contype 61092 let fieldname 61093 let parsed 61094 let charset 61095 let encoding 61096 let filename 61097 let nsize = 0 61098 61099 if (header['content-type']) { 61100 parsed = parseParams(header['content-type'][0]) 61101 if (parsed[0]) { 61102 contype = parsed[0].toLowerCase() 61103 for (i = 0, len = parsed.length; i < len; ++i) { 61104 if (RE_CHARSET.test(parsed[i][0])) { 61105 charset = parsed[i][1].toLowerCase() 61106 break 61107 } 61108 } 61109 } 61110 } 61111 61112 if (contype === undefined) { contype = 'text/plain' } 61113 if (charset === undefined) { charset = defCharset } 61114 61115 if (header['content-disposition']) { 61116 parsed = parseParams(header['content-disposition'][0]) 61117 if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } 61118 for (i = 0, len = parsed.length; i < len; ++i) { 61119 if (RE_NAME.test(parsed[i][0])) { 61120 fieldname = parsed[i][1] 61121 } else if (RE_FILENAME.test(parsed[i][0])) { 61122 filename = parsed[i][1] 61123 if (!preservePath) { filename = basename(filename) } 61124 } 61125 } 61126 } else { return skipPart(part) } 61127 61128 if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } 61129 61130 let onData, 61131 onEnd 61132 61133 if (isPartAFile(fieldname, contype, filename)) { 61134 // file/binary field 61135 if (nfiles === filesLimit) { 61136 if (!boy.hitFilesLimit) { 61137 boy.hitFilesLimit = true 61138 boy.emit('filesLimit') 61139 } 61140 return skipPart(part) 61141 } 61142 61143 ++nfiles 61144 61145 if (boy.listenerCount('file') === 0) { 61146 self.parser._ignore() 61147 return 61148 } 61149 61150 ++nends 61151 const file = new FileStream(fileOpts) 61152 curFile = file 61153 file.on('end', function () { 61154 --nends 61155 self._pause = false 61156 checkFinished() 61157 if (self._cb && !self._needDrain) { 61158 const cb = self._cb 61159 self._cb = undefined 61160 cb() 61161 } 61162 }) 61163 file._read = function (n) { 61164 if (!self._pause) { return } 61165 self._pause = false 61166 if (self._cb && !self._needDrain) { 61167 const cb = self._cb 61168 self._cb = undefined 61169 cb() 61170 } 61171 } 61172 boy.emit('file', fieldname, file, filename, encoding, contype) 61173 61174 onData = function (data) { 61175 if ((nsize += data.length) > fileSizeLimit) { 61176 const extralen = fileSizeLimit - nsize + data.length 61177 if (extralen > 0) { file.push(data.slice(0, extralen)) } 61178 file.truncated = true 61179 file.bytesRead = fileSizeLimit 61180 part.removeAllListeners('data') 61181 file.emit('limit') 61182 return 61183 } else if (!file.push(data)) { self._pause = true } 61184 61185 file.bytesRead = nsize 61186 } 61187 61188 onEnd = function () { 61189 curFile = undefined 61190 file.push(null) 61191 } 61192 } else { 61193 // non-file field 61194 if (nfields === fieldsLimit) { 61195 if (!boy.hitFieldsLimit) { 61196 boy.hitFieldsLimit = true 61197 boy.emit('fieldsLimit') 61198 } 61199 return skipPart(part) 61200 } 61201 61202 ++nfields 61203 ++nends 61204 let buffer = '' 61205 let truncated = false 61206 curField = part 61207 61208 onData = function (data) { 61209 if ((nsize += data.length) > fieldSizeLimit) { 61210 const extralen = (fieldSizeLimit - (nsize - data.length)) 61211 buffer += data.toString('binary', 0, extralen) 61212 truncated = true 61213 part.removeAllListeners('data') 61214 } else { buffer += data.toString('binary') } 61215 } 61216 61217 onEnd = function () { 61218 curField = undefined 61219 if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } 61220 boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) 61221 --nends 61222 checkFinished() 61223 } 61224 } 61225 61226 /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become 61227 broken. Streams2/streams3 is a huge black box of confusion, but 61228 somehow overriding the sync state seems to fix things again (and still 61229 seems to work for previous node versions). 61230 */ 61231 part._readableState.sync = false 61232 61233 part.on('data', onData) 61234 part.on('end', onEnd) 61235 }).on('error', function (err) { 61236 if (curFile) { curFile.emit('error', err) } 61237 }) 61238 }).on('error', function (err) { 61239 boy.emit('error', err) 61240 }).on('finish', function () { 61241 finished = true 61242 checkFinished() 61243 }) 61244 } 61245 61246 Multipart.prototype.write = function (chunk, cb) { 61247 const r = this.parser.write(chunk) 61248 if (r && !this._pause) { 61249 cb() 61250 } else { 61251 this._needDrain = !r 61252 this._cb = cb 61253 } 61254 } 61255 61256 Multipart.prototype.end = function () { 61257 const self = this 61258 61259 if (self.parser.writable) { 61260 self.parser.end() 61261 } else if (!self._boy._done) { 61262 process.nextTick(function () { 61263 self._boy._done = true 61264 self._boy.emit('finish') 61265 }) 61266 } 61267 } 61268 61269 function skipPart (part) { 61270 part.resume() 61271 } 61272 61273 function FileStream (opts) { 61274 Readable.call(this, opts) 61275 61276 this.bytesRead = 0 61277 61278 this.truncated = false 61279 } 61280 61281 inherits(FileStream, Readable) 61282 61283 FileStream.prototype._read = function (n) {} 61284 61285 module.exports = Multipart 61286 61287 61288 /***/ }), 61289 61290 /***/ 8306: 61291 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 61292 61293 "use strict"; 61294 61295 61296 const Decoder = __nccwpck_require__(7100) 61297 const decodeText = __nccwpck_require__(4619) 61298 const getLimit = __nccwpck_require__(1467) 61299 61300 const RE_CHARSET = /^charset$/i 61301 61302 UrlEncoded.detect = /^application\/x-www-form-urlencoded/i 61303 function UrlEncoded (boy, cfg) { 61304 const limits = cfg.limits 61305 const parsedConType = cfg.parsedConType 61306 this.boy = boy 61307 61308 this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) 61309 this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) 61310 this.fieldsLimit = getLimit(limits, 'fields', Infinity) 61311 61312 let charset 61313 for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var 61314 if (Array.isArray(parsedConType[i]) && 61315 RE_CHARSET.test(parsedConType[i][0])) { 61316 charset = parsedConType[i][1].toLowerCase() 61317 break 61318 } 61319 } 61320 61321 if (charset === undefined) { charset = cfg.defCharset || 'utf8' } 61322 61323 this.decoder = new Decoder() 61324 this.charset = charset 61325 this._fields = 0 61326 this._state = 'key' 61327 this._checkingBytes = true 61328 this._bytesKey = 0 61329 this._bytesVal = 0 61330 this._key = '' 61331 this._val = '' 61332 this._keyTrunc = false 61333 this._valTrunc = false 61334 this._hitLimit = false 61335 } 61336 61337 UrlEncoded.prototype.write = function (data, cb) { 61338 if (this._fields === this.fieldsLimit) { 61339 if (!this.boy.hitFieldsLimit) { 61340 this.boy.hitFieldsLimit = true 61341 this.boy.emit('fieldsLimit') 61342 } 61343 return cb() 61344 } 61345 61346 let idxeq; let idxamp; let i; let p = 0; const len = data.length 61347 61348 while (p < len) { 61349 if (this._state === 'key') { 61350 idxeq = idxamp = undefined 61351 for (i = p; i < len; ++i) { 61352 if (!this._checkingBytes) { ++p } 61353 if (data[i] === 0x3D/* = */) { 61354 idxeq = i 61355 break 61356 } else if (data[i] === 0x26/* & */) { 61357 idxamp = i 61358 break 61359 } 61360 if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { 61361 this._hitLimit = true 61362 break 61363 } else if (this._checkingBytes) { ++this._bytesKey } 61364 } 61365 61366 if (idxeq !== undefined) { 61367 // key with assignment 61368 if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } 61369 this._state = 'val' 61370 61371 this._hitLimit = false 61372 this._checkingBytes = true 61373 this._val = '' 61374 this._bytesVal = 0 61375 this._valTrunc = false 61376 this.decoder.reset() 61377 61378 p = idxeq + 1 61379 } else if (idxamp !== undefined) { 61380 // key with no assignment 61381 ++this._fields 61382 let key; const keyTrunc = this._keyTrunc 61383 if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } 61384 61385 this._hitLimit = false 61386 this._checkingBytes = true 61387 this._key = '' 61388 this._bytesKey = 0 61389 this._keyTrunc = false 61390 this.decoder.reset() 61391 61392 if (key.length) { 61393 this.boy.emit('field', decodeText(key, 'binary', this.charset), 61394 '', 61395 keyTrunc, 61396 false) 61397 } 61398 61399 p = idxamp + 1 61400 if (this._fields === this.fieldsLimit) { return cb() } 61401 } else if (this._hitLimit) { 61402 // we may not have hit the actual limit if there are encoded bytes... 61403 if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } 61404 p = i 61405 if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { 61406 // yep, we actually did hit the limit 61407 this._checkingBytes = false 61408 this._keyTrunc = true 61409 } 61410 } else { 61411 if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } 61412 p = len 61413 } 61414 } else { 61415 idxamp = undefined 61416 for (i = p; i < len; ++i) { 61417 if (!this._checkingBytes) { ++p } 61418 if (data[i] === 0x26/* & */) { 61419 idxamp = i 61420 break 61421 } 61422 if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { 61423 this._hitLimit = true 61424 break 61425 } else if (this._checkingBytes) { ++this._bytesVal } 61426 } 61427 61428 if (idxamp !== undefined) { 61429 ++this._fields 61430 if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } 61431 this.boy.emit('field', decodeText(this._key, 'binary', this.charset), 61432 decodeText(this._val, 'binary', this.charset), 61433 this._keyTrunc, 61434 this._valTrunc) 61435 this._state = 'key' 61436 61437 this._hitLimit = false 61438 this._checkingBytes = true 61439 this._key = '' 61440 this._bytesKey = 0 61441 this._keyTrunc = false 61442 this.decoder.reset() 61443 61444 p = idxamp + 1 61445 if (this._fields === this.fieldsLimit) { return cb() } 61446 } else if (this._hitLimit) { 61447 // we may not have hit the actual limit if there are encoded bytes... 61448 if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } 61449 p = i 61450 if ((this._val === '' && this.fieldSizeLimit === 0) || 61451 (this._bytesVal = this._val.length) === this.fieldSizeLimit) { 61452 // yep, we actually did hit the limit 61453 this._checkingBytes = false 61454 this._valTrunc = true 61455 } 61456 } else { 61457 if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } 61458 p = len 61459 } 61460 } 61461 } 61462 cb() 61463 } 61464 61465 UrlEncoded.prototype.end = function () { 61466 if (this.boy._done) { return } 61467 61468 if (this._state === 'key' && this._key.length > 0) { 61469 this.boy.emit('field', decodeText(this._key, 'binary', this.charset), 61470 '', 61471 this._keyTrunc, 61472 false) 61473 } else if (this._state === 'val') { 61474 this.boy.emit('field', decodeText(this._key, 'binary', this.charset), 61475 decodeText(this._val, 'binary', this.charset), 61476 this._keyTrunc, 61477 this._valTrunc) 61478 } 61479 this.boy._done = true 61480 this.boy.emit('finish') 61481 } 61482 61483 module.exports = UrlEncoded 61484 61485 61486 /***/ }), 61487 61488 /***/ 7100: 61489 /***/ ((module) => { 61490 61491 "use strict"; 61492 61493 61494 const RE_PLUS = /\+/g 61495 61496 const HEX = [ 61497 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61498 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61499 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61500 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 61501 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61502 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61503 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61504 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 61505 ] 61506 61507 function Decoder () { 61508 this.buffer = undefined 61509 } 61510 Decoder.prototype.write = function (str) { 61511 // Replace '+' with ' ' before decoding 61512 str = str.replace(RE_PLUS, ' ') 61513 let res = '' 61514 let i = 0; let p = 0; const len = str.length 61515 for (; i < len; ++i) { 61516 if (this.buffer !== undefined) { 61517 if (!HEX[str.charCodeAt(i)]) { 61518 res += '%' + this.buffer 61519 this.buffer = undefined 61520 --i // retry character 61521 } else { 61522 this.buffer += str[i] 61523 ++p 61524 if (this.buffer.length === 2) { 61525 res += String.fromCharCode(parseInt(this.buffer, 16)) 61526 this.buffer = undefined 61527 } 61528 } 61529 } else if (str[i] === '%') { 61530 if (i > p) { 61531 res += str.substring(p, i) 61532 p = i 61533 } 61534 this.buffer = '' 61535 ++p 61536 } 61537 } 61538 if (p < len && this.buffer === undefined) { res += str.substring(p) } 61539 return res 61540 } 61541 Decoder.prototype.reset = function () { 61542 this.buffer = undefined 61543 } 61544 61545 module.exports = Decoder 61546 61547 61548 /***/ }), 61549 61550 /***/ 8647: 61551 /***/ ((module) => { 61552 61553 "use strict"; 61554 61555 61556 module.exports = function basename (path) { 61557 if (typeof path !== 'string') { return '' } 61558 for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var 61559 switch (path.charCodeAt(i)) { 61560 case 0x2F: // '/' 61561 case 0x5C: // '\' 61562 path = path.slice(i + 1) 61563 return (path === '..' || path === '.' ? '' : path) 61564 } 61565 } 61566 return (path === '..' || path === '.' ? '' : path) 61567 } 61568 61569 61570 /***/ }), 61571 61572 /***/ 4619: 61573 /***/ (function(module) { 61574 61575 "use strict"; 61576 61577 61578 // Node has always utf-8 61579 const utf8Decoder = new TextDecoder('utf-8') 61580 const textDecoders = new Map([ 61581 ['utf-8', utf8Decoder], 61582 ['utf8', utf8Decoder] 61583 ]) 61584 61585 function getDecoder (charset) { 61586 let lc 61587 while (true) { 61588 switch (charset) { 61589 case 'utf-8': 61590 case 'utf8': 61591 return decoders.utf8 61592 case 'latin1': 61593 case 'ascii': // TODO: Make these a separate, strict decoder? 61594 case 'us-ascii': 61595 case 'iso-8859-1': 61596 case 'iso8859-1': 61597 case 'iso88591': 61598 case 'iso_8859-1': 61599 case 'windows-1252': 61600 case 'iso_8859-1:1987': 61601 case 'cp1252': 61602 case 'x-cp1252': 61603 return decoders.latin1 61604 case 'utf16le': 61605 case 'utf-16le': 61606 case 'ucs2': 61607 case 'ucs-2': 61608 return decoders.utf16le 61609 case 'base64': 61610 return decoders.base64 61611 default: 61612 if (lc === undefined) { 61613 lc = true 61614 charset = charset.toLowerCase() 61615 continue 61616 } 61617 return decoders.other.bind(charset) 61618 } 61619 } 61620 } 61621 61622 const decoders = { 61623 utf8: (data, sourceEncoding) => { 61624 if (data.length === 0) { 61625 return '' 61626 } 61627 if (typeof data === 'string') { 61628 data = Buffer.from(data, sourceEncoding) 61629 } 61630 return data.utf8Slice(0, data.length) 61631 }, 61632 61633 latin1: (data, sourceEncoding) => { 61634 if (data.length === 0) { 61635 return '' 61636 } 61637 if (typeof data === 'string') { 61638 return data 61639 } 61640 return data.latin1Slice(0, data.length) 61641 }, 61642 61643 utf16le: (data, sourceEncoding) => { 61644 if (data.length === 0) { 61645 return '' 61646 } 61647 if (typeof data === 'string') { 61648 data = Buffer.from(data, sourceEncoding) 61649 } 61650 return data.ucs2Slice(0, data.length) 61651 }, 61652 61653 base64: (data, sourceEncoding) => { 61654 if (data.length === 0) { 61655 return '' 61656 } 61657 if (typeof data === 'string') { 61658 data = Buffer.from(data, sourceEncoding) 61659 } 61660 return data.base64Slice(0, data.length) 61661 }, 61662 61663 other: (data, sourceEncoding) => { 61664 if (data.length === 0) { 61665 return '' 61666 } 61667 if (typeof data === 'string') { 61668 data = Buffer.from(data, sourceEncoding) 61669 } 61670 61671 if (textDecoders.has(this.toString())) { 61672 try { 61673 return textDecoders.get(this).decode(data) 61674 } catch {} 61675 } 61676 return typeof data === 'string' 61677 ? data 61678 : data.toString() 61679 } 61680 } 61681 61682 function decodeText (text, sourceEncoding, destEncoding) { 61683 if (text) { 61684 return getDecoder(destEncoding)(text, sourceEncoding) 61685 } 61686 return text 61687 } 61688 61689 module.exports = decodeText 61690 61691 61692 /***/ }), 61693 61694 /***/ 1467: 61695 /***/ ((module) => { 61696 61697 "use strict"; 61698 61699 61700 module.exports = function getLimit (limits, name, defaultLimit) { 61701 if ( 61702 !limits || 61703 limits[name] === undefined || 61704 limits[name] === null 61705 ) { return defaultLimit } 61706 61707 if ( 61708 typeof limits[name] !== 'number' || 61709 isNaN(limits[name]) 61710 ) { throw new TypeError('Limit ' + name + ' is not a valid number') } 61711 61712 return limits[name] 61713 } 61714 61715 61716 /***/ }), 61717 61718 /***/ 1854: 61719 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { 61720 61721 "use strict"; 61722 /* eslint-disable object-property-newline */ 61723 61724 61725 const decodeText = __nccwpck_require__(4619) 61726 61727 const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g 61728 61729 const EncodedLookup = { 61730 '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', 61731 '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', 61732 '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', 61733 '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', 61734 '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', 61735 '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', 61736 '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', 61737 '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', 61738 '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', 61739 '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', 61740 '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', 61741 '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', 61742 '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', 61743 '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', 61744 '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', 61745 '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', 61746 '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', 61747 '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', 61748 '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', 61749 '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', 61750 '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', 61751 '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', 61752 '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', 61753 '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', 61754 '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', 61755 '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', 61756 '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', 61757 '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', 61758 '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', 61759 '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', 61760 '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', 61761 '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', 61762 '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', 61763 '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', 61764 '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', 61765 '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', 61766 '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', 61767 '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', 61768 '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', 61769 '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', 61770 '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', 61771 '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', 61772 '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', 61773 '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', 61774 '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', 61775 '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', 61776 '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', 61777 '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', 61778 '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', 61779 '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', 61780 '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', 61781 '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', 61782 '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', 61783 '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', 61784 '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', 61785 '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', 61786 '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', 61787 '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', 61788 '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', 61789 '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', 61790 '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', 61791 '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', 61792 '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', 61793 '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', 61794 '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', 61795 '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', 61796 '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', 61797 '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', 61798 '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', 61799 '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', 61800 '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', 61801 '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', 61802 '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', 61803 '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', 61804 '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', 61805 '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', 61806 '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', 61807 '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', 61808 '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', 61809 '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', 61810 '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', 61811 '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', 61812 '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', 61813 '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', 61814 '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', 61815 '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', 61816 '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', 61817 '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', 61818 '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', 61819 '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', 61820 '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', 61821 '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', 61822 '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', 61823 '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', 61824 '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', 61825 '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', 61826 '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' 61827 } 61828 61829 function encodedReplacer (match) { 61830 return EncodedLookup[match] 61831 } 61832 61833 const STATE_KEY = 0 61834 const STATE_VALUE = 1 61835 const STATE_CHARSET = 2 61836 const STATE_LANG = 3 61837 61838 function parseParams (str) { 61839 const res = [] 61840 let state = STATE_KEY 61841 let charset = '' 61842 let inquote = false 61843 let escaping = false 61844 let p = 0 61845 let tmp = '' 61846 const len = str.length 61847 61848 for (var i = 0; i < len; ++i) { // eslint-disable-line no-var 61849 const char = str[i] 61850 if (char === '\\' && inquote) { 61851 if (escaping) { escaping = false } else { 61852 escaping = true 61853 continue 61854 } 61855 } else if (char === '"') { 61856 if (!escaping) { 61857 if (inquote) { 61858 inquote = false 61859 state = STATE_KEY 61860 } else { inquote = true } 61861 continue 61862 } else { escaping = false } 61863 } else { 61864 if (escaping && inquote) { tmp += '\\' } 61865 escaping = false 61866 if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { 61867 if (state === STATE_CHARSET) { 61868 state = STATE_LANG 61869 charset = tmp.substring(1) 61870 } else { state = STATE_VALUE } 61871 tmp = '' 61872 continue 61873 } else if (state === STATE_KEY && 61874 (char === '*' || char === '=') && 61875 res.length) { 61876 state = char === '*' 61877 ? STATE_CHARSET 61878 : STATE_VALUE 61879 res[p] = [tmp, undefined] 61880 tmp = '' 61881 continue 61882 } else if (!inquote && char === ';') { 61883 state = STATE_KEY 61884 if (charset) { 61885 if (tmp.length) { 61886 tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), 61887 'binary', 61888 charset) 61889 } 61890 charset = '' 61891 } else if (tmp.length) { 61892 tmp = decodeText(tmp, 'binary', 'utf8') 61893 } 61894 if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } 61895 tmp = '' 61896 ++p 61897 continue 61898 } else if (!inquote && (char === ' ' || char === '\t')) { continue } 61899 } 61900 tmp += char 61901 } 61902 if (charset && tmp.length) { 61903 tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), 61904 'binary', 61905 charset) 61906 } else if (tmp) { 61907 tmp = decodeText(tmp, 'binary', 'utf8') 61908 } 61909 61910 if (res[p] === undefined) { 61911 if (tmp) { res[p] = tmp } 61912 } else { res[p][1] = tmp } 61913 61914 return res 61915 } 61916 61917 module.exports = parseParams 61918 61919 61920 /***/ }), 61921 61922 /***/ 4446: 61923 /***/ ((__unused_webpack_module, exports) => { 61924 61925 "use strict"; 61926 61927 /** 61928 * @module LRUCache 61929 */ 61930 Object.defineProperty(exports, "__esModule", ({ value: true })); 61931 exports.LRUCache = void 0; 61932 const perf = typeof performance === 'object' && 61933 performance && 61934 typeof performance.now === 'function' 61935 ? performance 61936 : Date; 61937 const warned = new Set(); 61938 /* c8 ignore start */ 61939 const PROCESS = (typeof process === 'object' && !!process ? process : {}); 61940 /* c8 ignore start */ 61941 const emitWarning = (msg, type, code, fn) => { 61942 typeof PROCESS.emitWarning === 'function' 61943 ? PROCESS.emitWarning(msg, type, code, fn) 61944 : console.error(`[${code}] ${type}: ${msg}`); 61945 }; 61946 let AC = globalThis.AbortController; 61947 let AS = globalThis.AbortSignal; 61948 /* c8 ignore start */ 61949 if (typeof AC === 'undefined') { 61950 //@ts-ignore 61951 AS = class AbortSignal { 61952 onabort; 61953 _onabort = []; 61954 reason; 61955 aborted = false; 61956 addEventListener(_, fn) { 61957 this._onabort.push(fn); 61958 } 61959 }; 61960 //@ts-ignore 61961 AC = class AbortController { 61962 constructor() { 61963 warnACPolyfill(); 61964 } 61965 signal = new AS(); 61966 abort(reason) { 61967 if (this.signal.aborted) 61968 return; 61969 //@ts-ignore 61970 this.signal.reason = reason; 61971 //@ts-ignore 61972 this.signal.aborted = true; 61973 //@ts-ignore 61974 for (const fn of this.signal._onabort) { 61975 fn(reason); 61976 } 61977 this.signal.onabort?.(reason); 61978 } 61979 }; 61980 let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; 61981 const warnACPolyfill = () => { 61982 if (!printACPolyfillWarning) 61983 return; 61984 printACPolyfillWarning = false; 61985 emitWarning('AbortController is not defined. If using lru-cache in ' + 61986 'node 14, load an AbortController polyfill from the ' + 61987 '`node-abort-controller` package. A minimal polyfill is ' + 61988 'provided for use by LRUCache.fetch(), but it should not be ' + 61989 'relied upon in other contexts (eg, passing it to other APIs that ' + 61990 'use AbortController/AbortSignal might have undesirable effects). ' + 61991 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); 61992 }; 61993 } 61994 /* c8 ignore stop */ 61995 const shouldWarn = (code) => !warned.has(code); 61996 const TYPE = Symbol('type'); 61997 const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); 61998 /* c8 ignore start */ 61999 // This is a little bit ridiculous, tbh. 62000 // The maximum array length is 2^32-1 or thereabouts on most JS impls. 62001 // And well before that point, you're caching the entire world, I mean, 62002 // that's ~32GB of just integers for the next/prev links, plus whatever 62003 // else to hold that many keys and values. Just filling the memory with 62004 // zeroes at init time is brutal when you get that big. 62005 // But why not be complete? 62006 // Maybe in the future, these limits will have expanded. 62007 const getUintArray = (max) => !isPosInt(max) 62008 ? null 62009 : max <= Math.pow(2, 8) 62010 ? Uint8Array 62011 : max <= Math.pow(2, 16) 62012 ? Uint16Array 62013 : max <= Math.pow(2, 32) 62014 ? Uint32Array 62015 : max <= Number.MAX_SAFE_INTEGER 62016 ? ZeroArray 62017 : null; 62018 /* c8 ignore stop */ 62019 class ZeroArray extends Array { 62020 constructor(size) { 62021 super(size); 62022 this.fill(0); 62023 } 62024 } 62025 class Stack { 62026 heap; 62027 length; 62028 // private constructor 62029 static #constructing = false; 62030 static create(max) { 62031 const HeapCls = getUintArray(max); 62032 if (!HeapCls) 62033 return []; 62034 Stack.#constructing = true; 62035 const s = new Stack(max, HeapCls); 62036 Stack.#constructing = false; 62037 return s; 62038 } 62039 constructor(max, HeapCls) { 62040 /* c8 ignore start */ 62041 if (!Stack.#constructing) { 62042 throw new TypeError('instantiate Stack using Stack.create(n)'); 62043 } 62044 /* c8 ignore stop */ 62045 this.heap = new HeapCls(max); 62046 this.length = 0; 62047 } 62048 push(n) { 62049 this.heap[this.length++] = n; 62050 } 62051 pop() { 62052 return this.heap[--this.length]; 62053 } 62054 } 62055 /** 62056 * Default export, the thing you're using this module to get. 62057 * 62058 * All properties from the options object (with the exception of 62059 * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as 62060 * normal public members. (`max` and `maxBase` are read-only getters.) 62061 * Changing any of these will alter the defaults for subsequent method calls, 62062 * but is otherwise safe. 62063 */ 62064 class LRUCache { 62065 // properties coming in from the options of these, only max and maxSize 62066 // really *need* to be protected. The rest can be modified, as they just 62067 // set defaults for various methods. 62068 #max; 62069 #maxSize; 62070 #dispose; 62071 #disposeAfter; 62072 #fetchMethod; 62073 /** 62074 * {@link LRUCache.OptionsBase.ttl} 62075 */ 62076 ttl; 62077 /** 62078 * {@link LRUCache.OptionsBase.ttlResolution} 62079 */ 62080 ttlResolution; 62081 /** 62082 * {@link LRUCache.OptionsBase.ttlAutopurge} 62083 */ 62084 ttlAutopurge; 62085 /** 62086 * {@link LRUCache.OptionsBase.updateAgeOnGet} 62087 */ 62088 updateAgeOnGet; 62089 /** 62090 * {@link LRUCache.OptionsBase.updateAgeOnHas} 62091 */ 62092 updateAgeOnHas; 62093 /** 62094 * {@link LRUCache.OptionsBase.allowStale} 62095 */ 62096 allowStale; 62097 /** 62098 * {@link LRUCache.OptionsBase.noDisposeOnSet} 62099 */ 62100 noDisposeOnSet; 62101 /** 62102 * {@link LRUCache.OptionsBase.noUpdateTTL} 62103 */ 62104 noUpdateTTL; 62105 /** 62106 * {@link LRUCache.OptionsBase.maxEntrySize} 62107 */ 62108 maxEntrySize; 62109 /** 62110 * {@link LRUCache.OptionsBase.sizeCalculation} 62111 */ 62112 sizeCalculation; 62113 /** 62114 * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} 62115 */ 62116 noDeleteOnFetchRejection; 62117 /** 62118 * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} 62119 */ 62120 noDeleteOnStaleGet; 62121 /** 62122 * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} 62123 */ 62124 allowStaleOnFetchAbort; 62125 /** 62126 * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} 62127 */ 62128 allowStaleOnFetchRejection; 62129 /** 62130 * {@link LRUCache.OptionsBase.ignoreFetchAbort} 62131 */ 62132 ignoreFetchAbort; 62133 // computed properties 62134 #size; 62135 #calculatedSize; 62136 #keyMap; 62137 #keyList; 62138 #valList; 62139 #next; 62140 #prev; 62141 #head; 62142 #tail; 62143 #free; 62144 #disposed; 62145 #sizes; 62146 #starts; 62147 #ttls; 62148 #hasDispose; 62149 #hasFetchMethod; 62150 #hasDisposeAfter; 62151 /** 62152 * Do not call this method unless you need to inspect the 62153 * inner workings of the cache. If anything returned by this 62154 * object is modified in any way, strange breakage may occur. 62155 * 62156 * These fields are private for a reason! 62157 * 62158 * @internal 62159 */ 62160 static unsafeExposeInternals(c) { 62161 return { 62162 // properties 62163 starts: c.#starts, 62164 ttls: c.#ttls, 62165 sizes: c.#sizes, 62166 keyMap: c.#keyMap, 62167 keyList: c.#keyList, 62168 valList: c.#valList, 62169 next: c.#next, 62170 prev: c.#prev, 62171 get head() { 62172 return c.#head; 62173 }, 62174 get tail() { 62175 return c.#tail; 62176 }, 62177 free: c.#free, 62178 // methods 62179 isBackgroundFetch: (p) => c.#isBackgroundFetch(p), 62180 backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), 62181 moveToTail: (index) => c.#moveToTail(index), 62182 indexes: (options) => c.#indexes(options), 62183 rindexes: (options) => c.#rindexes(options), 62184 isStale: (index) => c.#isStale(index), 62185 }; 62186 } 62187 // Protected read-only members 62188 /** 62189 * {@link LRUCache.OptionsBase.max} (read-only) 62190 */ 62191 get max() { 62192 return this.#max; 62193 } 62194 /** 62195 * {@link LRUCache.OptionsBase.maxSize} (read-only) 62196 */ 62197 get maxSize() { 62198 return this.#maxSize; 62199 } 62200 /** 62201 * The total computed size of items in the cache (read-only) 62202 */ 62203 get calculatedSize() { 62204 return this.#calculatedSize; 62205 } 62206 /** 62207 * The number of items stored in the cache (read-only) 62208 */ 62209 get size() { 62210 return this.#size; 62211 } 62212 /** 62213 * {@link LRUCache.OptionsBase.fetchMethod} (read-only) 62214 */ 62215 get fetchMethod() { 62216 return this.#fetchMethod; 62217 } 62218 /** 62219 * {@link LRUCache.OptionsBase.dispose} (read-only) 62220 */ 62221 get dispose() { 62222 return this.#dispose; 62223 } 62224 /** 62225 * {@link LRUCache.OptionsBase.disposeAfter} (read-only) 62226 */ 62227 get disposeAfter() { 62228 return this.#disposeAfter; 62229 } 62230 constructor(options) { 62231 const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; 62232 if (max !== 0 && !isPosInt(max)) { 62233 throw new TypeError('max option must be a nonnegative integer'); 62234 } 62235 const UintArray = max ? getUintArray(max) : Array; 62236 if (!UintArray) { 62237 throw new Error('invalid max value: ' + max); 62238 } 62239 this.#max = max; 62240 this.#maxSize = maxSize; 62241 this.maxEntrySize = maxEntrySize || this.#maxSize; 62242 this.sizeCalculation = sizeCalculation; 62243 if (this.sizeCalculation) { 62244 if (!this.#maxSize && !this.maxEntrySize) { 62245 throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); 62246 } 62247 if (typeof this.sizeCalculation !== 'function') { 62248 throw new TypeError('sizeCalculation set to non-function'); 62249 } 62250 } 62251 if (fetchMethod !== undefined && 62252 typeof fetchMethod !== 'function') { 62253 throw new TypeError('fetchMethod must be a function if specified'); 62254 } 62255 this.#fetchMethod = fetchMethod; 62256 this.#hasFetchMethod = !!fetchMethod; 62257 this.#keyMap = new Map(); 62258 this.#keyList = new Array(max).fill(undefined); 62259 this.#valList = new Array(max).fill(undefined); 62260 this.#next = new UintArray(max); 62261 this.#prev = new UintArray(max); 62262 this.#head = 0; 62263 this.#tail = 0; 62264 this.#free = Stack.create(max); 62265 this.#size = 0; 62266 this.#calculatedSize = 0; 62267 if (typeof dispose === 'function') { 62268 this.#dispose = dispose; 62269 } 62270 if (typeof disposeAfter === 'function') { 62271 this.#disposeAfter = disposeAfter; 62272 this.#disposed = []; 62273 } 62274 else { 62275 this.#disposeAfter = undefined; 62276 this.#disposed = undefined; 62277 } 62278 this.#hasDispose = !!this.#dispose; 62279 this.#hasDisposeAfter = !!this.#disposeAfter; 62280 this.noDisposeOnSet = !!noDisposeOnSet; 62281 this.noUpdateTTL = !!noUpdateTTL; 62282 this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; 62283 this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; 62284 this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; 62285 this.ignoreFetchAbort = !!ignoreFetchAbort; 62286 // NB: maxEntrySize is set to maxSize if it's set 62287 if (this.maxEntrySize !== 0) { 62288 if (this.#maxSize !== 0) { 62289 if (!isPosInt(this.#maxSize)) { 62290 throw new TypeError('maxSize must be a positive integer if specified'); 62291 } 62292 } 62293 if (!isPosInt(this.maxEntrySize)) { 62294 throw new TypeError('maxEntrySize must be a positive integer if specified'); 62295 } 62296 this.#initializeSizeTracking(); 62297 } 62298 this.allowStale = !!allowStale; 62299 this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; 62300 this.updateAgeOnGet = !!updateAgeOnGet; 62301 this.updateAgeOnHas = !!updateAgeOnHas; 62302 this.ttlResolution = 62303 isPosInt(ttlResolution) || ttlResolution === 0 62304 ? ttlResolution 62305 : 1; 62306 this.ttlAutopurge = !!ttlAutopurge; 62307 this.ttl = ttl || 0; 62308 if (this.ttl) { 62309 if (!isPosInt(this.ttl)) { 62310 throw new TypeError('ttl must be a positive integer if specified'); 62311 } 62312 this.#initializeTTLTracking(); 62313 } 62314 // do not allow completely unbounded caches 62315 if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { 62316 throw new TypeError('At least one of max, maxSize, or ttl is required'); 62317 } 62318 if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { 62319 const code = 'LRU_CACHE_UNBOUNDED'; 62320 if (shouldWarn(code)) { 62321 warned.add(code); 62322 const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 62323 'result in unbounded memory consumption.'; 62324 emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); 62325 } 62326 } 62327 } 62328 /** 62329 * Return the remaining TTL time for a given entry key 62330 */ 62331 getRemainingTTL(key) { 62332 return this.#keyMap.has(key) ? Infinity : 0; 62333 } 62334 #initializeTTLTracking() { 62335 const ttls = new ZeroArray(this.#max); 62336 const starts = new ZeroArray(this.#max); 62337 this.#ttls = ttls; 62338 this.#starts = starts; 62339 this.#setItemTTL = (index, ttl, start = perf.now()) => { 62340 starts[index] = ttl !== 0 ? start : 0; 62341 ttls[index] = ttl; 62342 if (ttl !== 0 && this.ttlAutopurge) { 62343 const t = setTimeout(() => { 62344 if (this.#isStale(index)) { 62345 this.delete(this.#keyList[index]); 62346 } 62347 }, ttl + 1); 62348 // unref() not supported on all platforms 62349 /* c8 ignore start */ 62350 if (t.unref) { 62351 t.unref(); 62352 } 62353 /* c8 ignore stop */ 62354 } 62355 }; 62356 this.#updateItemAge = index => { 62357 starts[index] = ttls[index] !== 0 ? perf.now() : 0; 62358 }; 62359 this.#statusTTL = (status, index) => { 62360 if (ttls[index]) { 62361 const ttl = ttls[index]; 62362 const start = starts[index]; 62363 /* c8 ignore next */ 62364 if (!ttl || !start) 62365 return; 62366 status.ttl = ttl; 62367 status.start = start; 62368 status.now = cachedNow || getNow(); 62369 const age = status.now - start; 62370 status.remainingTTL = ttl - age; 62371 } 62372 }; 62373 // debounce calls to perf.now() to 1s so we're not hitting 62374 // that costly call repeatedly. 62375 let cachedNow = 0; 62376 const getNow = () => { 62377 const n = perf.now(); 62378 if (this.ttlResolution > 0) { 62379 cachedNow = n; 62380 const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); 62381 // not available on all platforms 62382 /* c8 ignore start */ 62383 if (t.unref) { 62384 t.unref(); 62385 } 62386 /* c8 ignore stop */ 62387 } 62388 return n; 62389 }; 62390 this.getRemainingTTL = key => { 62391 const index = this.#keyMap.get(key); 62392 if (index === undefined) { 62393 return 0; 62394 } 62395 const ttl = ttls[index]; 62396 const start = starts[index]; 62397 if (!ttl || !start) { 62398 return Infinity; 62399 } 62400 const age = (cachedNow || getNow()) - start; 62401 return ttl - age; 62402 }; 62403 this.#isStale = index => { 62404 const s = starts[index]; 62405 const t = ttls[index]; 62406 return !!t && !!s && (cachedNow || getNow()) - s > t; 62407 }; 62408 } 62409 // conditionally set private methods related to TTL 62410 #updateItemAge = () => { }; 62411 #statusTTL = () => { }; 62412 #setItemTTL = () => { }; 62413 /* c8 ignore stop */ 62414 #isStale = () => false; 62415 #initializeSizeTracking() { 62416 const sizes = new ZeroArray(this.#max); 62417 this.#calculatedSize = 0; 62418 this.#sizes = sizes; 62419 this.#removeItemSize = index => { 62420 this.#calculatedSize -= sizes[index]; 62421 sizes[index] = 0; 62422 }; 62423 this.#requireSize = (k, v, size, sizeCalculation) => { 62424 // provisionally accept background fetches. 62425 // actual value size will be checked when they return. 62426 if (this.#isBackgroundFetch(v)) { 62427 return 0; 62428 } 62429 if (!isPosInt(size)) { 62430 if (sizeCalculation) { 62431 if (typeof sizeCalculation !== 'function') { 62432 throw new TypeError('sizeCalculation must be a function'); 62433 } 62434 size = sizeCalculation(v, k); 62435 if (!isPosInt(size)) { 62436 throw new TypeError('sizeCalculation return invalid (expect positive integer)'); 62437 } 62438 } 62439 else { 62440 throw new TypeError('invalid size value (must be positive integer). ' + 62441 'When maxSize or maxEntrySize is used, sizeCalculation ' + 62442 'or size must be set.'); 62443 } 62444 } 62445 return size; 62446 }; 62447 this.#addItemSize = (index, size, status) => { 62448 sizes[index] = size; 62449 if (this.#maxSize) { 62450 const maxSize = this.#maxSize - sizes[index]; 62451 while (this.#calculatedSize > maxSize) { 62452 this.#evict(true); 62453 } 62454 } 62455 this.#calculatedSize += sizes[index]; 62456 if (status) { 62457 status.entrySize = size; 62458 status.totalCalculatedSize = this.#calculatedSize; 62459 } 62460 }; 62461 } 62462 #removeItemSize = _i => { }; 62463 #addItemSize = (_i, _s, _st) => { }; 62464 #requireSize = (_k, _v, size, sizeCalculation) => { 62465 if (size || sizeCalculation) { 62466 throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); 62467 } 62468 return 0; 62469 }; 62470 *#indexes({ allowStale = this.allowStale } = {}) { 62471 if (this.#size) { 62472 for (let i = this.#tail; true;) { 62473 if (!this.#isValidIndex(i)) { 62474 break; 62475 } 62476 if (allowStale || !this.#isStale(i)) { 62477 yield i; 62478 } 62479 if (i === this.#head) { 62480 break; 62481 } 62482 else { 62483 i = this.#prev[i]; 62484 } 62485 } 62486 } 62487 } 62488 *#rindexes({ allowStale = this.allowStale } = {}) { 62489 if (this.#size) { 62490 for (let i = this.#head; true;) { 62491 if (!this.#isValidIndex(i)) { 62492 break; 62493 } 62494 if (allowStale || !this.#isStale(i)) { 62495 yield i; 62496 } 62497 if (i === this.#tail) { 62498 break; 62499 } 62500 else { 62501 i = this.#next[i]; 62502 } 62503 } 62504 } 62505 } 62506 #isValidIndex(index) { 62507 return (index !== undefined && 62508 this.#keyMap.get(this.#keyList[index]) === index); 62509 } 62510 /** 62511 * Return a generator yielding `[key, value]` pairs, 62512 * in order from most recently used to least recently used. 62513 */ 62514 *entries() { 62515 for (const i of this.#indexes()) { 62516 if (this.#valList[i] !== undefined && 62517 this.#keyList[i] !== undefined && 62518 !this.#isBackgroundFetch(this.#valList[i])) { 62519 yield [this.#keyList[i], this.#valList[i]]; 62520 } 62521 } 62522 } 62523 /** 62524 * Inverse order version of {@link LRUCache.entries} 62525 * 62526 * Return a generator yielding `[key, value]` pairs, 62527 * in order from least recently used to most recently used. 62528 */ 62529 *rentries() { 62530 for (const i of this.#rindexes()) { 62531 if (this.#valList[i] !== undefined && 62532 this.#keyList[i] !== undefined && 62533 !this.#isBackgroundFetch(this.#valList[i])) { 62534 yield [this.#keyList[i], this.#valList[i]]; 62535 } 62536 } 62537 } 62538 /** 62539 * Return a generator yielding the keys in the cache, 62540 * in order from most recently used to least recently used. 62541 */ 62542 *keys() { 62543 for (const i of this.#indexes()) { 62544 const k = this.#keyList[i]; 62545 if (k !== undefined && 62546 !this.#isBackgroundFetch(this.#valList[i])) { 62547 yield k; 62548 } 62549 } 62550 } 62551 /** 62552 * Inverse order version of {@link LRUCache.keys} 62553 * 62554 * Return a generator yielding the keys in the cache, 62555 * in order from least recently used to most recently used. 62556 */ 62557 *rkeys() { 62558 for (const i of this.#rindexes()) { 62559 const k = this.#keyList[i]; 62560 if (k !== undefined && 62561 !this.#isBackgroundFetch(this.#valList[i])) { 62562 yield k; 62563 } 62564 } 62565 } 62566 /** 62567 * Return a generator yielding the values in the cache, 62568 * in order from most recently used to least recently used. 62569 */ 62570 *values() { 62571 for (const i of this.#indexes()) { 62572 const v = this.#valList[i]; 62573 if (v !== undefined && 62574 !this.#isBackgroundFetch(this.#valList[i])) { 62575 yield this.#valList[i]; 62576 } 62577 } 62578 } 62579 /** 62580 * Inverse order version of {@link LRUCache.values} 62581 * 62582 * Return a generator yielding the values in the cache, 62583 * in order from least recently used to most recently used. 62584 */ 62585 *rvalues() { 62586 for (const i of this.#rindexes()) { 62587 const v = this.#valList[i]; 62588 if (v !== undefined && 62589 !this.#isBackgroundFetch(this.#valList[i])) { 62590 yield this.#valList[i]; 62591 } 62592 } 62593 } 62594 /** 62595 * Iterating over the cache itself yields the same results as 62596 * {@link LRUCache.entries} 62597 */ 62598 [Symbol.iterator]() { 62599 return this.entries(); 62600 } 62601 /** 62602 * A String value that is used in the creation of the default string description of an object. 62603 * Called by the built-in method Object.prototype.toString. 62604 */ 62605 [Symbol.toStringTag] = 'LRUCache'; 62606 /** 62607 * Find a value for which the supplied fn method returns a truthy value, 62608 * similar to Array.find(). fn is called as fn(value, key, cache). 62609 */ 62610 find(fn, getOptions = {}) { 62611 for (const i of this.#indexes()) { 62612 const v = this.#valList[i]; 62613 const value = this.#isBackgroundFetch(v) 62614 ? v.__staleWhileFetching 62615 : v; 62616 if (value === undefined) 62617 continue; 62618 if (fn(value, this.#keyList[i], this)) { 62619 return this.get(this.#keyList[i], getOptions); 62620 } 62621 } 62622 } 62623 /** 62624 * Call the supplied function on each item in the cache, in order from 62625 * most recently used to least recently used. fn is called as 62626 * fn(value, key, cache). Does not update age or recenty of use. 62627 * Does not iterate over stale values. 62628 */ 62629 forEach(fn, thisp = this) { 62630 for (const i of this.#indexes()) { 62631 const v = this.#valList[i]; 62632 const value = this.#isBackgroundFetch(v) 62633 ? v.__staleWhileFetching 62634 : v; 62635 if (value === undefined) 62636 continue; 62637 fn.call(thisp, value, this.#keyList[i], this); 62638 } 62639 } 62640 /** 62641 * The same as {@link LRUCache.forEach} but items are iterated over in 62642 * reverse order. (ie, less recently used items are iterated over first.) 62643 */ 62644 rforEach(fn, thisp = this) { 62645 for (const i of this.#rindexes()) { 62646 const v = this.#valList[i]; 62647 const value = this.#isBackgroundFetch(v) 62648 ? v.__staleWhileFetching 62649 : v; 62650 if (value === undefined) 62651 continue; 62652 fn.call(thisp, value, this.#keyList[i], this); 62653 } 62654 } 62655 /** 62656 * Delete any stale entries. Returns true if anything was removed, 62657 * false otherwise. 62658 */ 62659 purgeStale() { 62660 let deleted = false; 62661 for (const i of this.#rindexes({ allowStale: true })) { 62662 if (this.#isStale(i)) { 62663 this.delete(this.#keyList[i]); 62664 deleted = true; 62665 } 62666 } 62667 return deleted; 62668 } 62669 /** 62670 * Get the extended info about a given entry, to get its value, size, and 62671 * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a 62672 * single key. Always returns stale values, if their info is found in the 62673 * cache, so be sure to check for expired TTLs if relevant. 62674 */ 62675 info(key) { 62676 const i = this.#keyMap.get(key); 62677 if (i === undefined) 62678 return undefined; 62679 const v = this.#valList[i]; 62680 const value = this.#isBackgroundFetch(v) 62681 ? v.__staleWhileFetching 62682 : v; 62683 if (value === undefined) 62684 return undefined; 62685 const entry = { value }; 62686 if (this.#ttls && this.#starts) { 62687 const ttl = this.#ttls[i]; 62688 const start = this.#starts[i]; 62689 if (ttl && start) { 62690 const remain = ttl - (perf.now() - start); 62691 entry.ttl = remain; 62692 entry.start = Date.now(); 62693 } 62694 } 62695 if (this.#sizes) { 62696 entry.size = this.#sizes[i]; 62697 } 62698 return entry; 62699 } 62700 /** 62701 * Return an array of [key, {@link LRUCache.Entry}] tuples which can be 62702 * passed to cache.load() 62703 */ 62704 dump() { 62705 const arr = []; 62706 for (const i of this.#indexes({ allowStale: true })) { 62707 const key = this.#keyList[i]; 62708 const v = this.#valList[i]; 62709 const value = this.#isBackgroundFetch(v) 62710 ? v.__staleWhileFetching 62711 : v; 62712 if (value === undefined || key === undefined) 62713 continue; 62714 const entry = { value }; 62715 if (this.#ttls && this.#starts) { 62716 entry.ttl = this.#ttls[i]; 62717 // always dump the start relative to a portable timestamp 62718 // it's ok for this to be a bit slow, it's a rare operation. 62719 const age = perf.now() - this.#starts[i]; 62720 entry.start = Math.floor(Date.now() - age); 62721 } 62722 if (this.#sizes) { 62723 entry.size = this.#sizes[i]; 62724 } 62725 arr.unshift([key, entry]); 62726 } 62727 return arr; 62728 } 62729 /** 62730 * Reset the cache and load in the items in entries in the order listed. 62731 * Note that the shape of the resulting cache may be different if the 62732 * same options are not used in both caches. 62733 */ 62734 load(arr) { 62735 this.clear(); 62736 for (const [key, entry] of arr) { 62737 if (entry.start) { 62738 // entry.start is a portable timestamp, but we may be using 62739 // node's performance.now(), so calculate the offset, so that 62740 // we get the intended remaining TTL, no matter how long it's 62741 // been on ice. 62742 // 62743 // it's ok for this to be a bit slow, it's a rare operation. 62744 const age = Date.now() - entry.start; 62745 entry.start = perf.now() - age; 62746 } 62747 this.set(key, entry.value, entry); 62748 } 62749 } 62750 /** 62751 * Add a value to the cache. 62752 * 62753 * Note: if `undefined` is specified as a value, this is an alias for 62754 * {@link LRUCache#delete} 62755 */ 62756 set(k, v, setOptions = {}) { 62757 if (v === undefined) { 62758 this.delete(k); 62759 return this; 62760 } 62761 const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; 62762 let { noUpdateTTL = this.noUpdateTTL } = setOptions; 62763 const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); 62764 // if the item doesn't fit, don't do anything 62765 // NB: maxEntrySize set to maxSize by default 62766 if (this.maxEntrySize && size > this.maxEntrySize) { 62767 if (status) { 62768 status.set = 'miss'; 62769 status.maxEntrySizeExceeded = true; 62770 } 62771 // have to delete, in case something is there already. 62772 this.delete(k); 62773 return this; 62774 } 62775 let index = this.#size === 0 ? undefined : this.#keyMap.get(k); 62776 if (index === undefined) { 62777 // addition 62778 index = (this.#size === 0 62779 ? this.#tail 62780 : this.#free.length !== 0 62781 ? this.#free.pop() 62782 : this.#size === this.#max 62783 ? this.#evict(false) 62784 : this.#size); 62785 this.#keyList[index] = k; 62786 this.#valList[index] = v; 62787 this.#keyMap.set(k, index); 62788 this.#next[this.#tail] = index; 62789 this.#prev[index] = this.#tail; 62790 this.#tail = index; 62791 this.#size++; 62792 this.#addItemSize(index, size, status); 62793 if (status) 62794 status.set = 'add'; 62795 noUpdateTTL = false; 62796 } 62797 else { 62798 // update 62799 this.#moveToTail(index); 62800 const oldVal = this.#valList[index]; 62801 if (v !== oldVal) { 62802 if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { 62803 oldVal.__abortController.abort(new Error('replaced')); 62804 const { __staleWhileFetching: s } = oldVal; 62805 if (s !== undefined && !noDisposeOnSet) { 62806 if (this.#hasDispose) { 62807 this.#dispose?.(s, k, 'set'); 62808 } 62809 if (this.#hasDisposeAfter) { 62810 this.#disposed?.push([s, k, 'set']); 62811 } 62812 } 62813 } 62814 else if (!noDisposeOnSet) { 62815 if (this.#hasDispose) { 62816 this.#dispose?.(oldVal, k, 'set'); 62817 } 62818 if (this.#hasDisposeAfter) { 62819 this.#disposed?.push([oldVal, k, 'set']); 62820 } 62821 } 62822 this.#removeItemSize(index); 62823 this.#addItemSize(index, size, status); 62824 this.#valList[index] = v; 62825 if (status) { 62826 status.set = 'replace'; 62827 const oldValue = oldVal && this.#isBackgroundFetch(oldVal) 62828 ? oldVal.__staleWhileFetching 62829 : oldVal; 62830 if (oldValue !== undefined) 62831 status.oldValue = oldValue; 62832 } 62833 } 62834 else if (status) { 62835 status.set = 'update'; 62836 } 62837 } 62838 if (ttl !== 0 && !this.#ttls) { 62839 this.#initializeTTLTracking(); 62840 } 62841 if (this.#ttls) { 62842 if (!noUpdateTTL) { 62843 this.#setItemTTL(index, ttl, start); 62844 } 62845 if (status) 62846 this.#statusTTL(status, index); 62847 } 62848 if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { 62849 const dt = this.#disposed; 62850 let task; 62851 while ((task = dt?.shift())) { 62852 this.#disposeAfter?.(...task); 62853 } 62854 } 62855 return this; 62856 } 62857 /** 62858 * Evict the least recently used item, returning its value or 62859 * `undefined` if cache is empty. 62860 */ 62861 pop() { 62862 try { 62863 while (this.#size) { 62864 const val = this.#valList[this.#head]; 62865 this.#evict(true); 62866 if (this.#isBackgroundFetch(val)) { 62867 if (val.__staleWhileFetching) { 62868 return val.__staleWhileFetching; 62869 } 62870 } 62871 else if (val !== undefined) { 62872 return val; 62873 } 62874 } 62875 } 62876 finally { 62877 if (this.#hasDisposeAfter && this.#disposed) { 62878 const dt = this.#disposed; 62879 let task; 62880 while ((task = dt?.shift())) { 62881 this.#disposeAfter?.(...task); 62882 } 62883 } 62884 } 62885 } 62886 #evict(free) { 62887 const head = this.#head; 62888 const k = this.#keyList[head]; 62889 const v = this.#valList[head]; 62890 if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { 62891 v.__abortController.abort(new Error('evicted')); 62892 } 62893 else if (this.#hasDispose || this.#hasDisposeAfter) { 62894 if (this.#hasDispose) { 62895 this.#dispose?.(v, k, 'evict'); 62896 } 62897 if (this.#hasDisposeAfter) { 62898 this.#disposed?.push([v, k, 'evict']); 62899 } 62900 } 62901 this.#removeItemSize(head); 62902 // if we aren't about to use the index, then null these out 62903 if (free) { 62904 this.#keyList[head] = undefined; 62905 this.#valList[head] = undefined; 62906 this.#free.push(head); 62907 } 62908 if (this.#size === 1) { 62909 this.#head = this.#tail = 0; 62910 this.#free.length = 0; 62911 } 62912 else { 62913 this.#head = this.#next[head]; 62914 } 62915 this.#keyMap.delete(k); 62916 this.#size--; 62917 return head; 62918 } 62919 /** 62920 * Check if a key is in the cache, without updating the recency of use. 62921 * Will return false if the item is stale, even though it is technically 62922 * in the cache. 62923 * 62924 * Will not update item age unless 62925 * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. 62926 */ 62927 has(k, hasOptions = {}) { 62928 const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; 62929 const index = this.#keyMap.get(k); 62930 if (index !== undefined) { 62931 const v = this.#valList[index]; 62932 if (this.#isBackgroundFetch(v) && 62933 v.__staleWhileFetching === undefined) { 62934 return false; 62935 } 62936 if (!this.#isStale(index)) { 62937 if (updateAgeOnHas) { 62938 this.#updateItemAge(index); 62939 } 62940 if (status) { 62941 status.has = 'hit'; 62942 this.#statusTTL(status, index); 62943 } 62944 return true; 62945 } 62946 else if (status) { 62947 status.has = 'stale'; 62948 this.#statusTTL(status, index); 62949 } 62950 } 62951 else if (status) { 62952 status.has = 'miss'; 62953 } 62954 return false; 62955 } 62956 /** 62957 * Like {@link LRUCache#get} but doesn't update recency or delete stale 62958 * items. 62959 * 62960 * Returns `undefined` if the item is stale, unless 62961 * {@link LRUCache.OptionsBase.allowStale} is set. 62962 */ 62963 peek(k, peekOptions = {}) { 62964 const { allowStale = this.allowStale } = peekOptions; 62965 const index = this.#keyMap.get(k); 62966 if (index === undefined || 62967 (!allowStale && this.#isStale(index))) { 62968 return; 62969 } 62970 const v = this.#valList[index]; 62971 // either stale and allowed, or forcing a refresh of non-stale value 62972 return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; 62973 } 62974 #backgroundFetch(k, index, options, context) { 62975 const v = index === undefined ? undefined : this.#valList[index]; 62976 if (this.#isBackgroundFetch(v)) { 62977 return v; 62978 } 62979 const ac = new AC(); 62980 const { signal } = options; 62981 // when/if our AC signals, then stop listening to theirs. 62982 signal?.addEventListener('abort', () => ac.abort(signal.reason), { 62983 signal: ac.signal, 62984 }); 62985 const fetchOpts = { 62986 signal: ac.signal, 62987 options, 62988 context, 62989 }; 62990 const cb = (v, updateCache = false) => { 62991 const { aborted } = ac.signal; 62992 const ignoreAbort = options.ignoreFetchAbort && v !== undefined; 62993 if (options.status) { 62994 if (aborted && !updateCache) { 62995 options.status.fetchAborted = true; 62996 options.status.fetchError = ac.signal.reason; 62997 if (ignoreAbort) 62998 options.status.fetchAbortIgnored = true; 62999 } 63000 else { 63001 options.status.fetchResolved = true; 63002 } 63003 } 63004 if (aborted && !ignoreAbort && !updateCache) { 63005 return fetchFail(ac.signal.reason); 63006 } 63007 // either we didn't abort, and are still here, or we did, and ignored 63008 const bf = p; 63009 if (this.#valList[index] === p) { 63010 if (v === undefined) { 63011 if (bf.__staleWhileFetching) { 63012 this.#valList[index] = bf.__staleWhileFetching; 63013 } 63014 else { 63015 this.delete(k); 63016 } 63017 } 63018 else { 63019 if (options.status) 63020 options.status.fetchUpdated = true; 63021 this.set(k, v, fetchOpts.options); 63022 } 63023 } 63024 return v; 63025 }; 63026 const eb = (er) => { 63027 if (options.status) { 63028 options.status.fetchRejected = true; 63029 options.status.fetchError = er; 63030 } 63031 return fetchFail(er); 63032 }; 63033 const fetchFail = (er) => { 63034 const { aborted } = ac.signal; 63035 const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; 63036 const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; 63037 const noDelete = allowStale || options.noDeleteOnFetchRejection; 63038 const bf = p; 63039 if (this.#valList[index] === p) { 63040 // if we allow stale on fetch rejections, then we need to ensure that 63041 // the stale value is not removed from the cache when the fetch fails. 63042 const del = !noDelete || bf.__staleWhileFetching === undefined; 63043 if (del) { 63044 this.delete(k); 63045 } 63046 else if (!allowStaleAborted) { 63047 // still replace the *promise* with the stale value, 63048 // since we are done with the promise at this point. 63049 // leave it untouched if we're still waiting for an 63050 // aborted background fetch that hasn't yet returned. 63051 this.#valList[index] = bf.__staleWhileFetching; 63052 } 63053 } 63054 if (allowStale) { 63055 if (options.status && bf.__staleWhileFetching !== undefined) { 63056 options.status.returnedStale = true; 63057 } 63058 return bf.__staleWhileFetching; 63059 } 63060 else if (bf.__returned === bf) { 63061 throw er; 63062 } 63063 }; 63064 const pcall = (res, rej) => { 63065 const fmp = this.#fetchMethod?.(k, v, fetchOpts); 63066 if (fmp && fmp instanceof Promise) { 63067 fmp.then(v => res(v === undefined ? undefined : v), rej); 63068 } 63069 // ignored, we go until we finish, regardless. 63070 // defer check until we are actually aborting, 63071 // so fetchMethod can override. 63072 ac.signal.addEventListener('abort', () => { 63073 if (!options.ignoreFetchAbort || 63074 options.allowStaleOnFetchAbort) { 63075 res(undefined); 63076 // when it eventually resolves, update the cache. 63077 if (options.allowStaleOnFetchAbort) { 63078 res = v => cb(v, true); 63079 } 63080 } 63081 }); 63082 }; 63083 if (options.status) 63084 options.status.fetchDispatched = true; 63085 const p = new Promise(pcall).then(cb, eb); 63086 const bf = Object.assign(p, { 63087 __abortController: ac, 63088 __staleWhileFetching: v, 63089 __returned: undefined, 63090 }); 63091 if (index === undefined) { 63092 // internal, don't expose status. 63093 this.set(k, bf, { ...fetchOpts.options, status: undefined }); 63094 index = this.#keyMap.get(k); 63095 } 63096 else { 63097 this.#valList[index] = bf; 63098 } 63099 return bf; 63100 } 63101 #isBackgroundFetch(p) { 63102 if (!this.#hasFetchMethod) 63103 return false; 63104 const b = p; 63105 return (!!b && 63106 b instanceof Promise && 63107 b.hasOwnProperty('__staleWhileFetching') && 63108 b.__abortController instanceof AC); 63109 } 63110 async fetch(k, fetchOptions = {}) { 63111 const { 63112 // get options 63113 allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, 63114 // set options 63115 ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, 63116 // fetch exclusive options 63117 noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; 63118 if (!this.#hasFetchMethod) { 63119 if (status) 63120 status.fetch = 'get'; 63121 return this.get(k, { 63122 allowStale, 63123 updateAgeOnGet, 63124 noDeleteOnStaleGet, 63125 status, 63126 }); 63127 } 63128 const options = { 63129 allowStale, 63130 updateAgeOnGet, 63131 noDeleteOnStaleGet, 63132 ttl, 63133 noDisposeOnSet, 63134 size, 63135 sizeCalculation, 63136 noUpdateTTL, 63137 noDeleteOnFetchRejection, 63138 allowStaleOnFetchRejection, 63139 allowStaleOnFetchAbort, 63140 ignoreFetchAbort, 63141 status, 63142 signal, 63143 }; 63144 let index = this.#keyMap.get(k); 63145 if (index === undefined) { 63146 if (status) 63147 status.fetch = 'miss'; 63148 const p = this.#backgroundFetch(k, index, options, context); 63149 return (p.__returned = p); 63150 } 63151 else { 63152 // in cache, maybe already fetching 63153 const v = this.#valList[index]; 63154 if (this.#isBackgroundFetch(v)) { 63155 const stale = allowStale && v.__staleWhileFetching !== undefined; 63156 if (status) { 63157 status.fetch = 'inflight'; 63158 if (stale) 63159 status.returnedStale = true; 63160 } 63161 return stale ? v.__staleWhileFetching : (v.__returned = v); 63162 } 63163 // if we force a refresh, that means do NOT serve the cached value, 63164 // unless we are already in the process of refreshing the cache. 63165 const isStale = this.#isStale(index); 63166 if (!forceRefresh && !isStale) { 63167 if (status) 63168 status.fetch = 'hit'; 63169 this.#moveToTail(index); 63170 if (updateAgeOnGet) { 63171 this.#updateItemAge(index); 63172 } 63173 if (status) 63174 this.#statusTTL(status, index); 63175 return v; 63176 } 63177 // ok, it is stale or a forced refresh, and not already fetching. 63178 // refresh the cache. 63179 const p = this.#backgroundFetch(k, index, options, context); 63180 const hasStale = p.__staleWhileFetching !== undefined; 63181 const staleVal = hasStale && allowStale; 63182 if (status) { 63183 status.fetch = isStale ? 'stale' : 'refresh'; 63184 if (staleVal && isStale) 63185 status.returnedStale = true; 63186 } 63187 return staleVal ? p.__staleWhileFetching : (p.__returned = p); 63188 } 63189 } 63190 /** 63191 * Return a value from the cache. Will update the recency of the cache 63192 * entry found. 63193 * 63194 * If the key is not found, get() will return `undefined`. 63195 */ 63196 get(k, getOptions = {}) { 63197 const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; 63198 const index = this.#keyMap.get(k); 63199 if (index !== undefined) { 63200 const value = this.#valList[index]; 63201 const fetching = this.#isBackgroundFetch(value); 63202 if (status) 63203 this.#statusTTL(status, index); 63204 if (this.#isStale(index)) { 63205 if (status) 63206 status.get = 'stale'; 63207 // delete only if not an in-flight background fetch 63208 if (!fetching) { 63209 if (!noDeleteOnStaleGet) { 63210 this.delete(k); 63211 } 63212 if (status && allowStale) 63213 status.returnedStale = true; 63214 return allowStale ? value : undefined; 63215 } 63216 else { 63217 if (status && 63218 allowStale && 63219 value.__staleWhileFetching !== undefined) { 63220 status.returnedStale = true; 63221 } 63222 return allowStale ? value.__staleWhileFetching : undefined; 63223 } 63224 } 63225 else { 63226 if (status) 63227 status.get = 'hit'; 63228 // if we're currently fetching it, we don't actually have it yet 63229 // it's not stale, which means this isn't a staleWhileRefetching. 63230 // If it's not stale, and fetching, AND has a __staleWhileFetching 63231 // value, then that means the user fetched with {forceRefresh:true}, 63232 // so it's safe to return that value. 63233 if (fetching) { 63234 return value.__staleWhileFetching; 63235 } 63236 this.#moveToTail(index); 63237 if (updateAgeOnGet) { 63238 this.#updateItemAge(index); 63239 } 63240 return value; 63241 } 63242 } 63243 else if (status) { 63244 status.get = 'miss'; 63245 } 63246 } 63247 #connect(p, n) { 63248 this.#prev[n] = p; 63249 this.#next[p] = n; 63250 } 63251 #moveToTail(index) { 63252 // if tail already, nothing to do 63253 // if head, move head to next[index] 63254 // else 63255 // move next[prev[index]] to next[index] (head has no prev) 63256 // move prev[next[index]] to prev[index] 63257 // prev[index] = tail 63258 // next[tail] = index 63259 // tail = index 63260 if (index !== this.#tail) { 63261 if (index === this.#head) { 63262 this.#head = this.#next[index]; 63263 } 63264 else { 63265 this.#connect(this.#prev[index], this.#next[index]); 63266 } 63267 this.#connect(this.#tail, index); 63268 this.#tail = index; 63269 } 63270 } 63271 /** 63272 * Deletes a key out of the cache. 63273 * Returns true if the key was deleted, false otherwise. 63274 */ 63275 delete(k) { 63276 let deleted = false; 63277 if (this.#size !== 0) { 63278 const index = this.#keyMap.get(k); 63279 if (index !== undefined) { 63280 deleted = true; 63281 if (this.#size === 1) { 63282 this.clear(); 63283 } 63284 else { 63285 this.#removeItemSize(index); 63286 const v = this.#valList[index]; 63287 if (this.#isBackgroundFetch(v)) { 63288 v.__abortController.abort(new Error('deleted')); 63289 } 63290 else if (this.#hasDispose || this.#hasDisposeAfter) { 63291 if (this.#hasDispose) { 63292 this.#dispose?.(v, k, 'delete'); 63293 } 63294 if (this.#hasDisposeAfter) { 63295 this.#disposed?.push([v, k, 'delete']); 63296 } 63297 } 63298 this.#keyMap.delete(k); 63299 this.#keyList[index] = undefined; 63300 this.#valList[index] = undefined; 63301 if (index === this.#tail) { 63302 this.#tail = this.#prev[index]; 63303 } 63304 else if (index === this.#head) { 63305 this.#head = this.#next[index]; 63306 } 63307 else { 63308 const pi = this.#prev[index]; 63309 this.#next[pi] = this.#next[index]; 63310 const ni = this.#next[index]; 63311 this.#prev[ni] = this.#prev[index]; 63312 } 63313 this.#size--; 63314 this.#free.push(index); 63315 } 63316 } 63317 } 63318 if (this.#hasDisposeAfter && this.#disposed?.length) { 63319 const dt = this.#disposed; 63320 let task; 63321 while ((task = dt?.shift())) { 63322 this.#disposeAfter?.(...task); 63323 } 63324 } 63325 return deleted; 63326 } 63327 /** 63328 * Clear the cache entirely, throwing away all values. 63329 */ 63330 clear() { 63331 for (const index of this.#rindexes({ allowStale: true })) { 63332 const v = this.#valList[index]; 63333 if (this.#isBackgroundFetch(v)) { 63334 v.__abortController.abort(new Error('deleted')); 63335 } 63336 else { 63337 const k = this.#keyList[index]; 63338 if (this.#hasDispose) { 63339 this.#dispose?.(v, k, 'delete'); 63340 } 63341 if (this.#hasDisposeAfter) { 63342 this.#disposed?.push([v, k, 'delete']); 63343 } 63344 } 63345 } 63346 this.#keyMap.clear(); 63347 this.#valList.fill(undefined); 63348 this.#keyList.fill(undefined); 63349 if (this.#ttls && this.#starts) { 63350 this.#ttls.fill(0); 63351 this.#starts.fill(0); 63352 } 63353 if (this.#sizes) { 63354 this.#sizes.fill(0); 63355 } 63356 this.#head = 0; 63357 this.#tail = 0; 63358 this.#free.length = 0; 63359 this.#calculatedSize = 0; 63360 this.#size = 0; 63361 if (this.#hasDisposeAfter && this.#disposed) { 63362 const dt = this.#disposed; 63363 let task; 63364 while ((task = dt?.shift())) { 63365 this.#disposeAfter?.(...task); 63366 } 63367 } 63368 } 63369 } 63370 exports.LRUCache = LRUCache; 63371 //# sourceMappingURL=index.js.map 63372 63373 /***/ }), 63374 63375 /***/ 3033: 63376 /***/ ((__unused_webpack_module, exports) => { 63377 63378 "use strict"; 63379 63380 Object.defineProperty(exports, "__esModule", ({ value: true })); 63381 exports.assertValidPattern = void 0; 63382 const MAX_PATTERN_LENGTH = 1024 * 64; 63383 const assertValidPattern = (pattern) => { 63384 if (typeof pattern !== 'string') { 63385 throw new TypeError('invalid pattern'); 63386 } 63387 if (pattern.length > MAX_PATTERN_LENGTH) { 63388 throw new TypeError('pattern is too long'); 63389 } 63390 }; 63391 exports.assertValidPattern = assertValidPattern; 63392 //# sourceMappingURL=assert-valid-pattern.js.map 63393 63394 /***/ }), 63395 63396 /***/ 596: 63397 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 63398 63399 "use strict"; 63400 63401 // parse a single path portion 63402 Object.defineProperty(exports, "__esModule", ({ value: true })); 63403 exports.AST = void 0; 63404 const brace_expressions_js_1 = __nccwpck_require__(3857); 63405 const unescape_js_1 = __nccwpck_require__(6615); 63406 const types = new Set(['!', '?', '+', '*', '@']); 63407 const isExtglobType = (c) => types.has(c); 63408 // Patterns that get prepended to bind to the start of either the 63409 // entire string, or just a single path portion, to prevent dots 63410 // and/or traversal patterns, when needed. 63411 // Exts don't need the ^ or / bit, because the root binds that already. 63412 const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; 63413 const startNoDot = '(?!\\.)'; 63414 // characters that indicate a start of pattern needs the "no dots" bit, 63415 // because a dot *might* be matched. ( is not in the list, because in 63416 // the case of a child extglob, it will handle the prevention itself. 63417 const addPatternStart = new Set(['[', '.']); 63418 // cases where traversal is A-OK, no dot prevention needed 63419 const justDots = new Set(['..', '.']); 63420 const reSpecials = new Set('().*{}+?[]^$\\!'); 63421 const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 63422 // any single thing other than / 63423 const qmark = '[^/]'; 63424 // * => any number of characters 63425 const star = qmark + '*?'; 63426 // use + when we need to ensure that *something* matches, because the * is 63427 // the only thing in the path portion. 63428 const starNoEmpty = qmark + '+?'; 63429 // remove the \ chars that we added if we end up doing a nonmagic compare 63430 // const deslash = (s: string) => s.replace(/\\(.)/g, '$1') 63431 class AST { 63432 type; 63433 #root; 63434 #hasMagic; 63435 #uflag = false; 63436 #parts = []; 63437 #parent; 63438 #parentIndex; 63439 #negs; 63440 #filledNegs = false; 63441 #options; 63442 #toString; 63443 // set to true if it's an extglob with no children 63444 // (which really means one child of '') 63445 #emptyExt = false; 63446 constructor(type, parent, options = {}) { 63447 this.type = type; 63448 // extglobs are inherently magical 63449 if (type) 63450 this.#hasMagic = true; 63451 this.#parent = parent; 63452 this.#root = this.#parent ? this.#parent.#root : this; 63453 this.#options = this.#root === this ? options : this.#root.#options; 63454 this.#negs = this.#root === this ? [] : this.#root.#negs; 63455 if (type === '!' && !this.#root.#filledNegs) 63456 this.#negs.push(this); 63457 this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; 63458 } 63459 get hasMagic() { 63460 /* c8 ignore start */ 63461 if (this.#hasMagic !== undefined) 63462 return this.#hasMagic; 63463 /* c8 ignore stop */ 63464 for (const p of this.#parts) { 63465 if (typeof p === 'string') 63466 continue; 63467 if (p.type || p.hasMagic) 63468 return (this.#hasMagic = true); 63469 } 63470 // note: will be undefined until we generate the regexp src and find out 63471 return this.#hasMagic; 63472 } 63473 // reconstructs the pattern 63474 toString() { 63475 if (this.#toString !== undefined) 63476 return this.#toString; 63477 if (!this.type) { 63478 return (this.#toString = this.#parts.map(p => String(p)).join('')); 63479 } 63480 else { 63481 return (this.#toString = 63482 this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); 63483 } 63484 } 63485 #fillNegs() { 63486 /* c8 ignore start */ 63487 if (this !== this.#root) 63488 throw new Error('should only call on root'); 63489 if (this.#filledNegs) 63490 return this; 63491 /* c8 ignore stop */ 63492 // call toString() once to fill this out 63493 this.toString(); 63494 this.#filledNegs = true; 63495 let n; 63496 while ((n = this.#negs.pop())) { 63497 if (n.type !== '!') 63498 continue; 63499 // walk up the tree, appending everthing that comes AFTER parentIndex 63500 let p = n; 63501 let pp = p.#parent; 63502 while (pp) { 63503 for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { 63504 for (const part of n.#parts) { 63505 /* c8 ignore start */ 63506 if (typeof part === 'string') { 63507 throw new Error('string part in extglob AST??'); 63508 } 63509 /* c8 ignore stop */ 63510 part.copyIn(pp.#parts[i]); 63511 } 63512 } 63513 p = pp; 63514 pp = p.#parent; 63515 } 63516 } 63517 return this; 63518 } 63519 push(...parts) { 63520 for (const p of parts) { 63521 if (p === '') 63522 continue; 63523 /* c8 ignore start */ 63524 if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { 63525 throw new Error('invalid part: ' + p); 63526 } 63527 /* c8 ignore stop */ 63528 this.#parts.push(p); 63529 } 63530 } 63531 toJSON() { 63532 const ret = this.type === null 63533 ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) 63534 : [this.type, ...this.#parts.map(p => p.toJSON())]; 63535 if (this.isStart() && !this.type) 63536 ret.unshift([]); 63537 if (this.isEnd() && 63538 (this === this.#root || 63539 (this.#root.#filledNegs && this.#parent?.type === '!'))) { 63540 ret.push({}); 63541 } 63542 return ret; 63543 } 63544 isStart() { 63545 if (this.#root === this) 63546 return true; 63547 // if (this.type) return !!this.#parent?.isStart() 63548 if (!this.#parent?.isStart()) 63549 return false; 63550 if (this.#parentIndex === 0) 63551 return true; 63552 // if everything AHEAD of this is a negation, then it's still the "start" 63553 const p = this.#parent; 63554 for (let i = 0; i < this.#parentIndex; i++) { 63555 const pp = p.#parts[i]; 63556 if (!(pp instanceof AST && pp.type === '!')) { 63557 return false; 63558 } 63559 } 63560 return true; 63561 } 63562 isEnd() { 63563 if (this.#root === this) 63564 return true; 63565 if (this.#parent?.type === '!') 63566 return true; 63567 if (!this.#parent?.isEnd()) 63568 return false; 63569 if (!this.type) 63570 return this.#parent?.isEnd(); 63571 // if not root, it'll always have a parent 63572 /* c8 ignore start */ 63573 const pl = this.#parent ? this.#parent.#parts.length : 0; 63574 /* c8 ignore stop */ 63575 return this.#parentIndex === pl - 1; 63576 } 63577 copyIn(part) { 63578 if (typeof part === 'string') 63579 this.push(part); 63580 else 63581 this.push(part.clone(this)); 63582 } 63583 clone(parent) { 63584 const c = new AST(this.type, parent); 63585 for (const p of this.#parts) { 63586 c.copyIn(p); 63587 } 63588 return c; 63589 } 63590 static #parseAST(str, ast, pos, opt) { 63591 let escaping = false; 63592 let inBrace = false; 63593 let braceStart = -1; 63594 let braceNeg = false; 63595 if (ast.type === null) { 63596 // outside of a extglob, append until we find a start 63597 let i = pos; 63598 let acc = ''; 63599 while (i < str.length) { 63600 const c = str.charAt(i++); 63601 // still accumulate escapes at this point, but we do ignore 63602 // starts that are escaped 63603 if (escaping || c === '\\') { 63604 escaping = !escaping; 63605 acc += c; 63606 continue; 63607 } 63608 if (inBrace) { 63609 if (i === braceStart + 1) { 63610 if (c === '^' || c === '!') { 63611 braceNeg = true; 63612 } 63613 } 63614 else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { 63615 inBrace = false; 63616 } 63617 acc += c; 63618 continue; 63619 } 63620 else if (c === '[') { 63621 inBrace = true; 63622 braceStart = i; 63623 braceNeg = false; 63624 acc += c; 63625 continue; 63626 } 63627 if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { 63628 ast.push(acc); 63629 acc = ''; 63630 const ext = new AST(c, ast); 63631 i = AST.#parseAST(str, ext, i, opt); 63632 ast.push(ext); 63633 continue; 63634 } 63635 acc += c; 63636 } 63637 ast.push(acc); 63638 return i; 63639 } 63640 // some kind of extglob, pos is at the ( 63641 // find the next | or ) 63642 let i = pos + 1; 63643 let part = new AST(null, ast); 63644 const parts = []; 63645 let acc = ''; 63646 while (i < str.length) { 63647 const c = str.charAt(i++); 63648 // still accumulate escapes at this point, but we do ignore 63649 // starts that are escaped 63650 if (escaping || c === '\\') { 63651 escaping = !escaping; 63652 acc += c; 63653 continue; 63654 } 63655 if (inBrace) { 63656 if (i === braceStart + 1) { 63657 if (c === '^' || c === '!') { 63658 braceNeg = true; 63659 } 63660 } 63661 else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { 63662 inBrace = false; 63663 } 63664 acc += c; 63665 continue; 63666 } 63667 else if (c === '[') { 63668 inBrace = true; 63669 braceStart = i; 63670 braceNeg = false; 63671 acc += c; 63672 continue; 63673 } 63674 if (isExtglobType(c) && str.charAt(i) === '(') { 63675 part.push(acc); 63676 acc = ''; 63677 const ext = new AST(c, part); 63678 part.push(ext); 63679 i = AST.#parseAST(str, ext, i, opt); 63680 continue; 63681 } 63682 if (c === '|') { 63683 part.push(acc); 63684 acc = ''; 63685 parts.push(part); 63686 part = new AST(null, ast); 63687 continue; 63688 } 63689 if (c === ')') { 63690 if (acc === '' && ast.#parts.length === 0) { 63691 ast.#emptyExt = true; 63692 } 63693 part.push(acc); 63694 acc = ''; 63695 ast.push(...parts, part); 63696 return i; 63697 } 63698 acc += c; 63699 } 63700 // unfinished extglob 63701 // if we got here, it was a malformed extglob! not an extglob, but 63702 // maybe something else in there. 63703 ast.type = null; 63704 ast.#hasMagic = undefined; 63705 ast.#parts = [str.substring(pos - 1)]; 63706 return i; 63707 } 63708 static fromGlob(pattern, options = {}) { 63709 const ast = new AST(null, undefined, options); 63710 AST.#parseAST(pattern, ast, 0, options); 63711 return ast; 63712 } 63713 // returns the regular expression if there's magic, or the unescaped 63714 // string if not. 63715 toMMPattern() { 63716 // should only be called on root 63717 /* c8 ignore start */ 63718 if (this !== this.#root) 63719 return this.#root.toMMPattern(); 63720 /* c8 ignore stop */ 63721 const glob = this.toString(); 63722 const [re, body, hasMagic, uflag] = this.toRegExpSource(); 63723 // if we're in nocase mode, and not nocaseMagicOnly, then we do 63724 // still need a regular expression if we have to case-insensitively 63725 // match capital/lowercase characters. 63726 const anyMagic = hasMagic || 63727 this.#hasMagic || 63728 (this.#options.nocase && 63729 !this.#options.nocaseMagicOnly && 63730 glob.toUpperCase() !== glob.toLowerCase()); 63731 if (!anyMagic) { 63732 return body; 63733 } 63734 const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); 63735 return Object.assign(new RegExp(`^${re}$`, flags), { 63736 _src: re, 63737 _glob: glob, 63738 }); 63739 } 63740 // returns the string match, the regexp source, whether there's magic 63741 // in the regexp (so a regular expression is required) and whether or 63742 // not the uflag is needed for the regular expression (for posix classes) 63743 // TODO: instead of injecting the start/end at this point, just return 63744 // the BODY of the regexp, along with the start/end portions suitable 63745 // for binding the start/end in either a joined full-path makeRe context 63746 // (where we bind to (^|/), or a standalone matchPart context (where 63747 // we bind to ^, and not /). Otherwise slashes get duped! 63748 // 63749 // In part-matching mode, the start is: 63750 // - if not isStart: nothing 63751 // - if traversal possible, but not allowed: ^(?!\.\.?$) 63752 // - if dots allowed or not possible: ^ 63753 // - if dots possible and not allowed: ^(?!\.) 63754 // end is: 63755 // - if not isEnd(): nothing 63756 // - else: $ 63757 // 63758 // In full-path matching mode, we put the slash at the START of the 63759 // pattern, so start is: 63760 // - if first pattern: same as part-matching mode 63761 // - if not isStart(): nothing 63762 // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) 63763 // - if dots allowed or not possible: / 63764 // - if dots possible and not allowed: /(?!\.) 63765 // end is: 63766 // - if last pattern, same as part-matching mode 63767 // - else nothing 63768 // 63769 // Always put the (?:$|/) on negated tails, though, because that has to be 63770 // there to bind the end of the negated pattern portion, and it's easier to 63771 // just stick it in now rather than try to inject it later in the middle of 63772 // the pattern. 63773 // 63774 // We can just always return the same end, and leave it up to the caller 63775 // to know whether it's going to be used joined or in parts. 63776 // And, if the start is adjusted slightly, can do the same there: 63777 // - if not isStart: nothing 63778 // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) 63779 // - if dots allowed or not possible: (?:/|^) 63780 // - if dots possible and not allowed: (?:/|^)(?!\.) 63781 // 63782 // But it's better to have a simpler binding without a conditional, for 63783 // performance, so probably better to return both start options. 63784 // 63785 // Then the caller just ignores the end if it's not the first pattern, 63786 // and the start always gets applied. 63787 // 63788 // But that's always going to be $ if it's the ending pattern, or nothing, 63789 // so the caller can just attach $ at the end of the pattern when building. 63790 // 63791 // So the todo is: 63792 // - better detect what kind of start is needed 63793 // - return both flavors of starting pattern 63794 // - attach $ at the end of the pattern when creating the actual RegExp 63795 // 63796 // Ah, but wait, no, that all only applies to the root when the first pattern 63797 // is not an extglob. If the first pattern IS an extglob, then we need all 63798 // that dot prevention biz to live in the extglob portions, because eg 63799 // +(*|.x*) can match .xy but not .yx. 63800 // 63801 // So, return the two flavors if it's #root and the first child is not an 63802 // AST, otherwise leave it to the child AST to handle it, and there, 63803 // use the (?:^|/) style of start binding. 63804 // 63805 // Even simplified further: 63806 // - Since the start for a join is eg /(?!\.) and the start for a part 63807 // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root 63808 // or start or whatever) and prepend ^ or / at the Regexp construction. 63809 toRegExpSource(allowDot) { 63810 const dot = allowDot ?? !!this.#options.dot; 63811 if (this.#root === this) 63812 this.#fillNegs(); 63813 if (!this.type) { 63814 const noEmpty = this.isStart() && this.isEnd(); 63815 const src = this.#parts 63816 .map(p => { 63817 const [re, _, hasMagic, uflag] = typeof p === 'string' 63818 ? AST.#parseGlob(p, this.#hasMagic, noEmpty) 63819 : p.toRegExpSource(allowDot); 63820 this.#hasMagic = this.#hasMagic || hasMagic; 63821 this.#uflag = this.#uflag || uflag; 63822 return re; 63823 }) 63824 .join(''); 63825 let start = ''; 63826 if (this.isStart()) { 63827 if (typeof this.#parts[0] === 'string') { 63828 // this is the string that will match the start of the pattern, 63829 // so we need to protect against dots and such. 63830 // '.' and '..' cannot match unless the pattern is that exactly, 63831 // even if it starts with . or dot:true is set. 63832 const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); 63833 if (!dotTravAllowed) { 63834 const aps = addPatternStart; 63835 // check if we have a possibility of matching . or .., 63836 // and prevent that. 63837 const needNoTrav = 63838 // dots are allowed, and the pattern starts with [ or . 63839 (dot && aps.has(src.charAt(0))) || 63840 // the pattern starts with \., and then [ or . 63841 (src.startsWith('\\.') && aps.has(src.charAt(2))) || 63842 // the pattern starts with \.\., and then [ or . 63843 (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); 63844 // no need to prevent dots if it can't match a dot, or if a 63845 // sub-pattern will be preventing it anyway. 63846 const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); 63847 start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; 63848 } 63849 } 63850 } 63851 // append the "end of path portion" pattern to negation tails 63852 let end = ''; 63853 if (this.isEnd() && 63854 this.#root.#filledNegs && 63855 this.#parent?.type === '!') { 63856 end = '(?:$|\\/)'; 63857 } 63858 const final = start + src + end; 63859 return [ 63860 final, 63861 (0, unescape_js_1.unescape)(src), 63862 (this.#hasMagic = !!this.#hasMagic), 63863 this.#uflag, 63864 ]; 63865 } 63866 // We need to calculate the body *twice* if it's a repeat pattern 63867 // at the start, once in nodot mode, then again in dot mode, so a 63868 // pattern like *(?) can match 'x.y' 63869 const repeated = this.type === '*' || this.type === '+'; 63870 // some kind of extglob 63871 const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; 63872 let body = this.#partsToRegExp(dot); 63873 if (this.isStart() && this.isEnd() && !body && this.type !== '!') { 63874 // invalid extglob, has to at least be *something* present, if it's 63875 // the entire path portion. 63876 const s = this.toString(); 63877 this.#parts = [s]; 63878 this.type = null; 63879 this.#hasMagic = undefined; 63880 return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; 63881 } 63882 // XXX abstract out this map method 63883 let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot 63884 ? '' 63885 : this.#partsToRegExp(true); 63886 if (bodyDotAllowed === body) { 63887 bodyDotAllowed = ''; 63888 } 63889 if (bodyDotAllowed) { 63890 body = `(?:${body})(?:${bodyDotAllowed})*?`; 63891 } 63892 // an empty !() is exactly equivalent to a starNoEmpty 63893 let final = ''; 63894 if (this.type === '!' && this.#emptyExt) { 63895 final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; 63896 } 63897 else { 63898 const close = this.type === '!' 63899 ? // !() must match something,but !(x) can match '' 63900 '))' + 63901 (this.isStart() && !dot && !allowDot ? startNoDot : '') + 63902 star + 63903 ')' 63904 : this.type === '@' 63905 ? ')' 63906 : this.type === '?' 63907 ? ')?' 63908 : this.type === '+' && bodyDotAllowed 63909 ? ')' 63910 : this.type === '*' && bodyDotAllowed 63911 ? `)?` 63912 : `)${this.type}`; 63913 final = start + body + close; 63914 } 63915 return [ 63916 final, 63917 (0, unescape_js_1.unescape)(body), 63918 (this.#hasMagic = !!this.#hasMagic), 63919 this.#uflag, 63920 ]; 63921 } 63922 #partsToRegExp(dot) { 63923 return this.#parts 63924 .map(p => { 63925 // extglob ASTs should only contain parent ASTs 63926 /* c8 ignore start */ 63927 if (typeof p === 'string') { 63928 throw new Error('string type in extglob ast??'); 63929 } 63930 /* c8 ignore stop */ 63931 // can ignore hasMagic, because extglobs are already always magic 63932 const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); 63933 this.#uflag = this.#uflag || uflag; 63934 return re; 63935 }) 63936 .filter(p => !(this.isStart() && this.isEnd()) || !!p) 63937 .join('|'); 63938 } 63939 static #parseGlob(glob, hasMagic, noEmpty = false) { 63940 let escaping = false; 63941 let re = ''; 63942 let uflag = false; 63943 for (let i = 0; i < glob.length; i++) { 63944 const c = glob.charAt(i); 63945 if (escaping) { 63946 escaping = false; 63947 re += (reSpecials.has(c) ? '\\' : '') + c; 63948 continue; 63949 } 63950 if (c === '\\') { 63951 if (i === glob.length - 1) { 63952 re += '\\\\'; 63953 } 63954 else { 63955 escaping = true; 63956 } 63957 continue; 63958 } 63959 if (c === '[') { 63960 const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); 63961 if (consumed) { 63962 re += src; 63963 uflag = uflag || needUflag; 63964 i += consumed - 1; 63965 hasMagic = hasMagic || magic; 63966 continue; 63967 } 63968 } 63969 if (c === '*') { 63970 if (noEmpty && glob === '*') 63971 re += starNoEmpty; 63972 else 63973 re += star; 63974 hasMagic = true; 63975 continue; 63976 } 63977 if (c === '?') { 63978 re += qmark; 63979 hasMagic = true; 63980 continue; 63981 } 63982 re += regExpEscape(c); 63983 } 63984 return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; 63985 } 63986 } 63987 exports.AST = AST; 63988 //# sourceMappingURL=ast.js.map 63989 63990 /***/ }), 63991 63992 /***/ 3857: 63993 /***/ ((__unused_webpack_module, exports) => { 63994 63995 "use strict"; 63996 63997 // translate the various posix character classes into unicode properties 63998 // this works across all unicode locales 63999 Object.defineProperty(exports, "__esModule", ({ value: true })); 64000 exports.parseClass = void 0; 64001 // { <posix class>: [<translation>, /u flag required, negated] 64002 const posixClasses = { 64003 '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], 64004 '[:alpha:]': ['\\p{L}\\p{Nl}', true], 64005 '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], 64006 '[:blank:]': ['\\p{Zs}\\t', true], 64007 '[:cntrl:]': ['\\p{Cc}', true], 64008 '[:digit:]': ['\\p{Nd}', true], 64009 '[:graph:]': ['\\p{Z}\\p{C}', true, true], 64010 '[:lower:]': ['\\p{Ll}', true], 64011 '[:print:]': ['\\p{C}', true], 64012 '[:punct:]': ['\\p{P}', true], 64013 '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], 64014 '[:upper:]': ['\\p{Lu}', true], 64015 '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], 64016 '[:xdigit:]': ['A-Fa-f0-9', false], 64017 }; 64018 // only need to escape a few things inside of brace expressions 64019 // escapes: [ \ ] - 64020 const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); 64021 // escape all regexp magic characters 64022 const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 64023 // everything has already been escaped, we just have to join 64024 const rangesToString = (ranges) => ranges.join(''); 64025 // takes a glob string at a posix brace expression, and returns 64026 // an equivalent regular expression source, and boolean indicating 64027 // whether the /u flag needs to be applied, and the number of chars 64028 // consumed to parse the character class. 64029 // This also removes out of order ranges, and returns ($.) if the 64030 // entire class just no good. 64031 const parseClass = (glob, position) => { 64032 const pos = position; 64033 /* c8 ignore start */ 64034 if (glob.charAt(pos) !== '[') { 64035 throw new Error('not in a brace expression'); 64036 } 64037 /* c8 ignore stop */ 64038 const ranges = []; 64039 const negs = []; 64040 let i = pos + 1; 64041 let sawStart = false; 64042 let uflag = false; 64043 let escaping = false; 64044 let negate = false; 64045 let endPos = pos; 64046 let rangeStart = ''; 64047 WHILE: while (i < glob.length) { 64048 const c = glob.charAt(i); 64049 if ((c === '!' || c === '^') && i === pos + 1) { 64050 negate = true; 64051 i++; 64052 continue; 64053 } 64054 if (c === ']' && sawStart && !escaping) { 64055 endPos = i + 1; 64056 break; 64057 } 64058 sawStart = true; 64059 if (c === '\\') { 64060 if (!escaping) { 64061 escaping = true; 64062 i++; 64063 continue; 64064 } 64065 // escaped \ char, fall through and treat like normal char 64066 } 64067 if (c === '[' && !escaping) { 64068 // either a posix class, a collation equivalent, or just a [ 64069 for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { 64070 if (glob.startsWith(cls, i)) { 64071 // invalid, [a-[] is fine, but not [a-[:alpha]] 64072 if (rangeStart) { 64073 return ['$.', false, glob.length - pos, true]; 64074 } 64075 i += cls.length; 64076 if (neg) 64077 negs.push(unip); 64078 else 64079 ranges.push(unip); 64080 uflag = uflag || u; 64081 continue WHILE; 64082 } 64083 } 64084 } 64085 // now it's just a normal character, effectively 64086 escaping = false; 64087 if (rangeStart) { 64088 // throw this range away if it's not valid, but others 64089 // can still match. 64090 if (c > rangeStart) { 64091 ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); 64092 } 64093 else if (c === rangeStart) { 64094 ranges.push(braceEscape(c)); 64095 } 64096 rangeStart = ''; 64097 i++; 64098 continue; 64099 } 64100 // now might be the start of a range. 64101 // can be either c-d or c-] or c<more...>] or c] at this point 64102 if (glob.startsWith('-]', i + 1)) { 64103 ranges.push(braceEscape(c + '-')); 64104 i += 2; 64105 continue; 64106 } 64107 if (glob.startsWith('-', i + 1)) { 64108 rangeStart = c; 64109 i += 2; 64110 continue; 64111 } 64112 // not the start of a range, just a single character 64113 ranges.push(braceEscape(c)); 64114 i++; 64115 } 64116 if (endPos < i) { 64117 // didn't see the end of the class, not a valid class, 64118 // but might still be valid as a literal match. 64119 return ['', false, 0, false]; 64120 } 64121 // if we got no ranges and no negates, then we have a range that 64122 // cannot possibly match anything, and that poisons the whole glob 64123 if (!ranges.length && !negs.length) { 64124 return ['$.', false, glob.length - pos, true]; 64125 } 64126 // if we got one positive range, and it's a single character, then that's 64127 // not actually a magic pattern, it's just that one literal character. 64128 // we should not treat that as "magic", we should just return the literal 64129 // character. [_] is a perfectly valid way to escape glob magic chars. 64130 if (negs.length === 0 && 64131 ranges.length === 1 && 64132 /^\\?.$/.test(ranges[0]) && 64133 !negate) { 64134 const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; 64135 return [regexpEscape(r), false, endPos - pos, false]; 64136 } 64137 const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; 64138 const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; 64139 const comb = ranges.length && negs.length 64140 ? '(' + sranges + '|' + snegs + ')' 64141 : ranges.length 64142 ? sranges 64143 : snegs; 64144 return [comb, uflag, endPos - pos, true]; 64145 }; 64146 exports.parseClass = parseClass; 64147 //# sourceMappingURL=brace-expressions.js.map 64148 64149 /***/ }), 64150 64151 /***/ 5615: 64152 /***/ ((__unused_webpack_module, exports) => { 64153 64154 "use strict"; 64155 64156 Object.defineProperty(exports, "__esModule", ({ value: true })); 64157 exports.escape = void 0; 64158 /** 64159 * Escape all magic characters in a glob pattern. 64160 * 64161 * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} 64162 * option is used, then characters are escaped by wrapping in `[]`, because 64163 * a magic character wrapped in a character class can only be satisfied by 64164 * that exact character. In this mode, `\` is _not_ escaped, because it is 64165 * not interpreted as a magic character, but instead as a path separator. 64166 */ 64167 const escape = (s, { windowsPathsNoEscape = false, } = {}) => { 64168 // don't need to escape +@! because we escape the parens 64169 // that make those magic, and escaping ! as [!] isn't valid, 64170 // because [!]] is a valid glob class meaning not ']'. 64171 return windowsPathsNoEscape 64172 ? s.replace(/[?*()[\]]/g, '[$&]') 64173 : s.replace(/[?*()[\]\\]/g, '\\$&'); 64174 }; 64175 exports.escape = escape; 64176 //# sourceMappingURL=escape.js.map 64177 64178 /***/ }), 64179 64180 /***/ 4878: 64181 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 64182 64183 "use strict"; 64184 64185 var __importDefault = (this && this.__importDefault) || function (mod) { 64186 return (mod && mod.__esModule) ? mod : { "default": mod }; 64187 }; 64188 Object.defineProperty(exports, "__esModule", ({ value: true })); 64189 exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; 64190 const brace_expansion_1 = __importDefault(__nccwpck_require__(4515)); 64191 const assert_valid_pattern_js_1 = __nccwpck_require__(3033); 64192 const ast_js_1 = __nccwpck_require__(596); 64193 const escape_js_1 = __nccwpck_require__(5615); 64194 const unescape_js_1 = __nccwpck_require__(6615); 64195 const minimatch = (p, pattern, options = {}) => { 64196 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 64197 // shortcut: comments match nothing. 64198 if (!options.nocomment && pattern.charAt(0) === '#') { 64199 return false; 64200 } 64201 return new Minimatch(pattern, options).match(p); 64202 }; 64203 exports.minimatch = minimatch; 64204 // Optimized checking for the most common glob patterns. 64205 const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; 64206 const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); 64207 const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); 64208 const starDotExtTestNocase = (ext) => { 64209 ext = ext.toLowerCase(); 64210 return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); 64211 }; 64212 const starDotExtTestNocaseDot = (ext) => { 64213 ext = ext.toLowerCase(); 64214 return (f) => f.toLowerCase().endsWith(ext); 64215 }; 64216 const starDotStarRE = /^\*+\.\*+$/; 64217 const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); 64218 const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); 64219 const dotStarRE = /^\.\*+$/; 64220 const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); 64221 const starRE = /^\*+$/; 64222 const starTest = (f) => f.length !== 0 && !f.startsWith('.'); 64223 const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; 64224 const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; 64225 const qmarksTestNocase = ([$0, ext = '']) => { 64226 const noext = qmarksTestNoExt([$0]); 64227 if (!ext) 64228 return noext; 64229 ext = ext.toLowerCase(); 64230 return (f) => noext(f) && f.toLowerCase().endsWith(ext); 64231 }; 64232 const qmarksTestNocaseDot = ([$0, ext = '']) => { 64233 const noext = qmarksTestNoExtDot([$0]); 64234 if (!ext) 64235 return noext; 64236 ext = ext.toLowerCase(); 64237 return (f) => noext(f) && f.toLowerCase().endsWith(ext); 64238 }; 64239 const qmarksTestDot = ([$0, ext = '']) => { 64240 const noext = qmarksTestNoExtDot([$0]); 64241 return !ext ? noext : (f) => noext(f) && f.endsWith(ext); 64242 }; 64243 const qmarksTest = ([$0, ext = '']) => { 64244 const noext = qmarksTestNoExt([$0]); 64245 return !ext ? noext : (f) => noext(f) && f.endsWith(ext); 64246 }; 64247 const qmarksTestNoExt = ([$0]) => { 64248 const len = $0.length; 64249 return (f) => f.length === len && !f.startsWith('.'); 64250 }; 64251 const qmarksTestNoExtDot = ([$0]) => { 64252 const len = $0.length; 64253 return (f) => f.length === len && f !== '.' && f !== '..'; 64254 }; 64255 /* c8 ignore start */ 64256 const defaultPlatform = (typeof process === 'object' && process 64257 ? (typeof process.env === 'object' && 64258 process.env && 64259 process.env.__MINIMATCH_TESTING_PLATFORM__) || 64260 process.platform 64261 : 'posix'); 64262 const path = { 64263 win32: { sep: '\\' }, 64264 posix: { sep: '/' }, 64265 }; 64266 /* c8 ignore stop */ 64267 exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; 64268 exports.minimatch.sep = exports.sep; 64269 exports.GLOBSTAR = Symbol('globstar **'); 64270 exports.minimatch.GLOBSTAR = exports.GLOBSTAR; 64271 // any single thing other than / 64272 // don't need to escape / when using new RegExp() 64273 const qmark = '[^/]'; 64274 // * => any number of characters 64275 const star = qmark + '*?'; 64276 // ** when dots are allowed. Anything goes, except .. and . 64277 // not (^ or / followed by one or two dots followed by $ or /), 64278 // followed by anything, any number of times. 64279 const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; 64280 // not a ^ or / followed by a dot, 64281 // followed by anything, any number of times. 64282 const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; 64283 const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); 64284 exports.filter = filter; 64285 exports.minimatch.filter = exports.filter; 64286 const ext = (a, b = {}) => Object.assign({}, a, b); 64287 const defaults = (def) => { 64288 if (!def || typeof def !== 'object' || !Object.keys(def).length) { 64289 return exports.minimatch; 64290 } 64291 const orig = exports.minimatch; 64292 const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); 64293 return Object.assign(m, { 64294 Minimatch: class Minimatch extends orig.Minimatch { 64295 constructor(pattern, options = {}) { 64296 super(pattern, ext(def, options)); 64297 } 64298 static defaults(options) { 64299 return orig.defaults(ext(def, options)).Minimatch; 64300 } 64301 }, 64302 AST: class AST extends orig.AST { 64303 /* c8 ignore start */ 64304 constructor(type, parent, options = {}) { 64305 super(type, parent, ext(def, options)); 64306 } 64307 /* c8 ignore stop */ 64308 static fromGlob(pattern, options = {}) { 64309 return orig.AST.fromGlob(pattern, ext(def, options)); 64310 } 64311 }, 64312 unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), 64313 escape: (s, options = {}) => orig.escape(s, ext(def, options)), 64314 filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), 64315 defaults: (options) => orig.defaults(ext(def, options)), 64316 makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), 64317 braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), 64318 match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), 64319 sep: orig.sep, 64320 GLOBSTAR: exports.GLOBSTAR, 64321 }); 64322 }; 64323 exports.defaults = defaults; 64324 exports.minimatch.defaults = exports.defaults; 64325 // Brace expansion: 64326 // a{b,c}d -> abd acd 64327 // a{b,}c -> abc ac 64328 // a{0..3}d -> a0d a1d a2d a3d 64329 // a{b,c{d,e}f}g -> abg acdfg acefg 64330 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg 64331 // 64332 // Invalid sets are not expanded. 64333 // a{2..}b -> a{2..}b 64334 // a{b}c -> a{b}c 64335 const braceExpand = (pattern, options = {}) => { 64336 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 64337 // Thanks to Yeting Li <https://github.com/yetingli> for 64338 // improving this regexp to avoid a ReDOS vulnerability. 64339 if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { 64340 // shortcut. no need to expand. 64341 return [pattern]; 64342 } 64343 return (0, brace_expansion_1.default)(pattern); 64344 }; 64345 exports.braceExpand = braceExpand; 64346 exports.minimatch.braceExpand = exports.braceExpand; 64347 // parse a component of the expanded set. 64348 // At this point, no pattern may contain "/" in it 64349 // so we're going to return a 2d array, where each entry is the full 64350 // pattern, split on '/', and then turned into a regular expression. 64351 // A regexp is made at the end which joins each array with an 64352 // escaped /, and another full one which joins each regexp with |. 64353 // 64354 // Following the lead of Bash 4.1, note that "**" only has special meaning 64355 // when it is the *only* thing in a path portion. Otherwise, any series 64356 // of * is equivalent to a single *. Globstar behavior is enabled by 64357 // default, and can be disabled by setting options.noglobstar. 64358 const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); 64359 exports.makeRe = makeRe; 64360 exports.minimatch.makeRe = exports.makeRe; 64361 const match = (list, pattern, options = {}) => { 64362 const mm = new Minimatch(pattern, options); 64363 list = list.filter(f => mm.match(f)); 64364 if (mm.options.nonull && !list.length) { 64365 list.push(pattern); 64366 } 64367 return list; 64368 }; 64369 exports.match = match; 64370 exports.minimatch.match = exports.match; 64371 // replace stuff like \* with * 64372 const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; 64373 const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 64374 class Minimatch { 64375 options; 64376 set; 64377 pattern; 64378 windowsPathsNoEscape; 64379 nonegate; 64380 negate; 64381 comment; 64382 empty; 64383 preserveMultipleSlashes; 64384 partial; 64385 globSet; 64386 globParts; 64387 nocase; 64388 isWindows; 64389 platform; 64390 windowsNoMagicRoot; 64391 regexp; 64392 constructor(pattern, options = {}) { 64393 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 64394 options = options || {}; 64395 this.options = options; 64396 this.pattern = pattern; 64397 this.platform = options.platform || defaultPlatform; 64398 this.isWindows = this.platform === 'win32'; 64399 this.windowsPathsNoEscape = 64400 !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; 64401 if (this.windowsPathsNoEscape) { 64402 this.pattern = this.pattern.replace(/\\/g, '/'); 64403 } 64404 this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; 64405 this.regexp = null; 64406 this.negate = false; 64407 this.nonegate = !!options.nonegate; 64408 this.comment = false; 64409 this.empty = false; 64410 this.partial = !!options.partial; 64411 this.nocase = !!this.options.nocase; 64412 this.windowsNoMagicRoot = 64413 options.windowsNoMagicRoot !== undefined 64414 ? options.windowsNoMagicRoot 64415 : !!(this.isWindows && this.nocase); 64416 this.globSet = []; 64417 this.globParts = []; 64418 this.set = []; 64419 // make the set of regexps etc. 64420 this.make(); 64421 } 64422 hasMagic() { 64423 if (this.options.magicalBraces && this.set.length > 1) { 64424 return true; 64425 } 64426 for (const pattern of this.set) { 64427 for (const part of pattern) { 64428 if (typeof part !== 'string') 64429 return true; 64430 } 64431 } 64432 return false; 64433 } 64434 debug(..._) { } 64435 make() { 64436 const pattern = this.pattern; 64437 const options = this.options; 64438 // empty patterns and comments match nothing. 64439 if (!options.nocomment && pattern.charAt(0) === '#') { 64440 this.comment = true; 64441 return; 64442 } 64443 if (!pattern) { 64444 this.empty = true; 64445 return; 64446 } 64447 // step 1: figure out negation, etc. 64448 this.parseNegate(); 64449 // step 2: expand braces 64450 this.globSet = [...new Set(this.braceExpand())]; 64451 if (options.debug) { 64452 this.debug = (...args) => console.error(...args); 64453 } 64454 this.debug(this.pattern, this.globSet); 64455 // step 3: now we have a set, so turn each one into a series of 64456 // path-portion matching patterns. 64457 // These will be regexps, except in the case of "**", which is 64458 // set to the GLOBSTAR object for globstar behavior, 64459 // and will not contain any / characters 64460 // 64461 // First, we preprocess to make the glob pattern sets a bit simpler 64462 // and deduped. There are some perf-killing patterns that can cause 64463 // problems with a glob walk, but we can simplify them down a bit. 64464 const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); 64465 this.globParts = this.preprocess(rawGlobParts); 64466 this.debug(this.pattern, this.globParts); 64467 // glob --> regexps 64468 let set = this.globParts.map((s, _, __) => { 64469 if (this.isWindows && this.windowsNoMagicRoot) { 64470 // check if it's a drive or unc path. 64471 const isUNC = s[0] === '' && 64472 s[1] === '' && 64473 (s[2] === '?' || !globMagic.test(s[2])) && 64474 !globMagic.test(s[3]); 64475 const isDrive = /^[a-z]:/i.test(s[0]); 64476 if (isUNC) { 64477 return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; 64478 } 64479 else if (isDrive) { 64480 return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; 64481 } 64482 } 64483 return s.map(ss => this.parse(ss)); 64484 }); 64485 this.debug(this.pattern, set); 64486 // filter out everything that didn't compile properly. 64487 this.set = set.filter(s => s.indexOf(false) === -1); 64488 // do not treat the ? in UNC paths as magic 64489 if (this.isWindows) { 64490 for (let i = 0; i < this.set.length; i++) { 64491 const p = this.set[i]; 64492 if (p[0] === '' && 64493 p[1] === '' && 64494 this.globParts[i][2] === '?' && 64495 typeof p[3] === 'string' && 64496 /^[a-z]:$/i.test(p[3])) { 64497 p[2] = '?'; 64498 } 64499 } 64500 } 64501 this.debug(this.pattern, this.set); 64502 } 64503 // various transforms to equivalent pattern sets that are 64504 // faster to process in a filesystem walk. The goal is to 64505 // eliminate what we can, and push all ** patterns as far 64506 // to the right as possible, even if it increases the number 64507 // of patterns that we have to process. 64508 preprocess(globParts) { 64509 // if we're not in globstar mode, then turn all ** into * 64510 if (this.options.noglobstar) { 64511 for (let i = 0; i < globParts.length; i++) { 64512 for (let j = 0; j < globParts[i].length; j++) { 64513 if (globParts[i][j] === '**') { 64514 globParts[i][j] = '*'; 64515 } 64516 } 64517 } 64518 } 64519 const { optimizationLevel = 1 } = this.options; 64520 if (optimizationLevel >= 2) { 64521 // aggressive optimization for the purpose of fs walking 64522 globParts = this.firstPhasePreProcess(globParts); 64523 globParts = this.secondPhasePreProcess(globParts); 64524 } 64525 else if (optimizationLevel >= 1) { 64526 // just basic optimizations to remove some .. parts 64527 globParts = this.levelOneOptimize(globParts); 64528 } 64529 else { 64530 globParts = this.adjascentGlobstarOptimize(globParts); 64531 } 64532 return globParts; 64533 } 64534 // just get rid of adjascent ** portions 64535 adjascentGlobstarOptimize(globParts) { 64536 return globParts.map(parts => { 64537 let gs = -1; 64538 while (-1 !== (gs = parts.indexOf('**', gs + 1))) { 64539 let i = gs; 64540 while (parts[i + 1] === '**') { 64541 i++; 64542 } 64543 if (i !== gs) { 64544 parts.splice(gs, i - gs); 64545 } 64546 } 64547 return parts; 64548 }); 64549 } 64550 // get rid of adjascent ** and resolve .. portions 64551 levelOneOptimize(globParts) { 64552 return globParts.map(parts => { 64553 parts = parts.reduce((set, part) => { 64554 const prev = set[set.length - 1]; 64555 if (part === '**' && prev === '**') { 64556 return set; 64557 } 64558 if (part === '..') { 64559 if (prev && prev !== '..' && prev !== '.' && prev !== '**') { 64560 set.pop(); 64561 return set; 64562 } 64563 } 64564 set.push(part); 64565 return set; 64566 }, []); 64567 return parts.length === 0 ? [''] : parts; 64568 }); 64569 } 64570 levelTwoFileOptimize(parts) { 64571 if (!Array.isArray(parts)) { 64572 parts = this.slashSplit(parts); 64573 } 64574 let didSomething = false; 64575 do { 64576 didSomething = false; 64577 // <pre>/<e>/<rest> -> <pre>/<rest> 64578 if (!this.preserveMultipleSlashes) { 64579 for (let i = 1; i < parts.length - 1; i++) { 64580 const p = parts[i]; 64581 // don't squeeze out UNC patterns 64582 if (i === 1 && p === '' && parts[0] === '') 64583 continue; 64584 if (p === '.' || p === '') { 64585 didSomething = true; 64586 parts.splice(i, 1); 64587 i--; 64588 } 64589 } 64590 if (parts[0] === '.' && 64591 parts.length === 2 && 64592 (parts[1] === '.' || parts[1] === '')) { 64593 didSomething = true; 64594 parts.pop(); 64595 } 64596 } 64597 // <pre>/<p>/../<rest> -> <pre>/<rest> 64598 let dd = 0; 64599 while (-1 !== (dd = parts.indexOf('..', dd + 1))) { 64600 const p = parts[dd - 1]; 64601 if (p && p !== '.' && p !== '..' && p !== '**') { 64602 didSomething = true; 64603 parts.splice(dd - 1, 2); 64604 dd -= 2; 64605 } 64606 } 64607 } while (didSomething); 64608 return parts.length === 0 ? [''] : parts; 64609 } 64610 // First phase: single-pattern processing 64611 // <pre> is 1 or more portions 64612 // <rest> is 1 or more portions 64613 // <p> is any portion other than ., .., '', or ** 64614 // <e> is . or '' 64615 // 64616 // **/.. is *brutal* for filesystem walking performance, because 64617 // it effectively resets the recursive walk each time it occurs, 64618 // and ** cannot be reduced out by a .. pattern part like a regexp 64619 // or most strings (other than .., ., and '') can be. 64620 // 64621 // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>} 64622 // <pre>/<e>/<rest> -> <pre>/<rest> 64623 // <pre>/<p>/../<rest> -> <pre>/<rest> 64624 // **/**/<rest> -> **/<rest> 64625 // 64626 // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow 64627 // this WOULD be allowed if ** did follow symlinks, or * didn't 64628 firstPhasePreProcess(globParts) { 64629 let didSomething = false; 64630 do { 64631 didSomething = false; 64632 // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>} 64633 for (let parts of globParts) { 64634 let gs = -1; 64635 while (-1 !== (gs = parts.indexOf('**', gs + 1))) { 64636 let gss = gs; 64637 while (parts[gss + 1] === '**') { 64638 // <pre>/**/**/<rest> -> <pre>/**/<rest> 64639 gss++; 64640 } 64641 // eg, if gs is 2 and gss is 4, that means we have 3 ** 64642 // parts, and can remove 2 of them. 64643 if (gss > gs) { 64644 parts.splice(gs + 1, gss - gs); 64645 } 64646 let next = parts[gs + 1]; 64647 const p = parts[gs + 2]; 64648 const p2 = parts[gs + 3]; 64649 if (next !== '..') 64650 continue; 64651 if (!p || 64652 p === '.' || 64653 p === '..' || 64654 !p2 || 64655 p2 === '.' || 64656 p2 === '..') { 64657 continue; 64658 } 64659 didSomething = true; 64660 // edit parts in place, and push the new one 64661 parts.splice(gs, 1); 64662 const other = parts.slice(0); 64663 other[gs] = '**'; 64664 globParts.push(other); 64665 gs--; 64666 } 64667 // <pre>/<e>/<rest> -> <pre>/<rest> 64668 if (!this.preserveMultipleSlashes) { 64669 for (let i = 1; i < parts.length - 1; i++) { 64670 const p = parts[i]; 64671 // don't squeeze out UNC patterns 64672 if (i === 1 && p === '' && parts[0] === '') 64673 continue; 64674 if (p === '.' || p === '') { 64675 didSomething = true; 64676 parts.splice(i, 1); 64677 i--; 64678 } 64679 } 64680 if (parts[0] === '.' && 64681 parts.length === 2 && 64682 (parts[1] === '.' || parts[1] === '')) { 64683 didSomething = true; 64684 parts.pop(); 64685 } 64686 } 64687 // <pre>/<p>/../<rest> -> <pre>/<rest> 64688 let dd = 0; 64689 while (-1 !== (dd = parts.indexOf('..', dd + 1))) { 64690 const p = parts[dd - 1]; 64691 if (p && p !== '.' && p !== '..' && p !== '**') { 64692 didSomething = true; 64693 const needDot = dd === 1 && parts[dd + 1] === '**'; 64694 const splin = needDot ? ['.'] : []; 64695 parts.splice(dd - 1, 2, ...splin); 64696 if (parts.length === 0) 64697 parts.push(''); 64698 dd -= 2; 64699 } 64700 } 64701 } 64702 } while (didSomething); 64703 return globParts; 64704 } 64705 // second phase: multi-pattern dedupes 64706 // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest> 64707 // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest> 64708 // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest> 64709 // 64710 // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest> 64711 // ^-- not valid because ** doens't follow symlinks 64712 secondPhasePreProcess(globParts) { 64713 for (let i = 0; i < globParts.length - 1; i++) { 64714 for (let j = i + 1; j < globParts.length; j++) { 64715 const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes); 64716 if (!matched) 64717 continue; 64718 globParts[i] = matched; 64719 globParts[j] = []; 64720 } 64721 } 64722 return globParts.filter(gs => gs.length); 64723 } 64724 partsMatch(a, b, emptyGSMatch = false) { 64725 let ai = 0; 64726 let bi = 0; 64727 let result = []; 64728 let which = ''; 64729 while (ai < a.length && bi < b.length) { 64730 if (a[ai] === b[bi]) { 64731 result.push(which === 'b' ? b[bi] : a[ai]); 64732 ai++; 64733 bi++; 64734 } 64735 else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) { 64736 result.push(a[ai]); 64737 ai++; 64738 } 64739 else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) { 64740 result.push(b[bi]); 64741 bi++; 64742 } 64743 else if (a[ai] === '*' && 64744 b[bi] && 64745 (this.options.dot || !b[bi].startsWith('.')) && 64746 b[bi] !== '**') { 64747 if (which === 'b') 64748 return false; 64749 which = 'a'; 64750 result.push(a[ai]); 64751 ai++; 64752 bi++; 64753 } 64754 else if (b[bi] === '*' && 64755 a[ai] && 64756 (this.options.dot || !a[ai].startsWith('.')) && 64757 a[ai] !== '**') { 64758 if (which === 'a') 64759 return false; 64760 which = 'b'; 64761 result.push(b[bi]); 64762 ai++; 64763 bi++; 64764 } 64765 else { 64766 return false; 64767 } 64768 } 64769 // if we fall out of the loop, it means they two are identical 64770 // as long as their lengths match 64771 return a.length === b.length && result; 64772 } 64773 parseNegate() { 64774 if (this.nonegate) 64775 return; 64776 const pattern = this.pattern; 64777 let negate = false; 64778 let negateOffset = 0; 64779 for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { 64780 negate = !negate; 64781 negateOffset++; 64782 } 64783 if (negateOffset) 64784 this.pattern = pattern.slice(negateOffset); 64785 this.negate = negate; 64786 } 64787 // set partial to true to test if, for example, 64788 // "/a/b" matches the start of "/*/b/*/d" 64789 // Partial means, if you run out of file before you run 64790 // out of pattern, then that's fine, as long as all 64791 // the parts match. 64792 matchOne(file, pattern, partial = false) { 64793 const options = this.options; 64794 // UNC paths like //?/X:/... can match X:/... and vice versa 64795 // Drive letters in absolute drive or unc paths are always compared 64796 // case-insensitively. 64797 if (this.isWindows) { 64798 const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]); 64799 const fileUNC = !fileDrive && 64800 file[0] === '' && 64801 file[1] === '' && 64802 file[2] === '?' && 64803 /^[a-z]:$/i.test(file[3]); 64804 const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]); 64805 const patternUNC = !patternDrive && 64806 pattern[0] === '' && 64807 pattern[1] === '' && 64808 pattern[2] === '?' && 64809 typeof pattern[3] === 'string' && 64810 /^[a-z]:$/i.test(pattern[3]); 64811 const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined; 64812 const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined; 64813 if (typeof fdi === 'number' && typeof pdi === 'number') { 64814 const [fd, pd] = [file[fdi], pattern[pdi]]; 64815 if (fd.toLowerCase() === pd.toLowerCase()) { 64816 pattern[pdi] = fd; 64817 if (pdi > fdi) { 64818 pattern = pattern.slice(pdi); 64819 } 64820 else if (fdi > pdi) { 64821 file = file.slice(fdi); 64822 } 64823 } 64824 } 64825 } 64826 // resolve and reduce . and .. portions in the file as well. 64827 // dont' need to do the second phase, because it's only one string[] 64828 const { optimizationLevel = 1 } = this.options; 64829 if (optimizationLevel >= 2) { 64830 file = this.levelTwoFileOptimize(file); 64831 } 64832 this.debug('matchOne', this, { file, pattern }); 64833 this.debug('matchOne', file.length, pattern.length); 64834 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { 64835 this.debug('matchOne loop'); 64836 var p = pattern[pi]; 64837 var f = file[fi]; 64838 this.debug(pattern, p, f); 64839 // should be impossible. 64840 // some invalid regexp stuff in the set. 64841 /* c8 ignore start */ 64842 if (p === false) { 64843 return false; 64844 } 64845 /* c8 ignore stop */ 64846 if (p === exports.GLOBSTAR) { 64847 this.debug('GLOBSTAR', [pattern, p, f]); 64848 // "**" 64849 // a/**/b/**/c would match the following: 64850 // a/b/x/y/z/c 64851 // a/x/y/z/b/c 64852 // a/b/x/b/x/c 64853 // a/b/c 64854 // To do this, take the rest of the pattern after 64855 // the **, and see if it would match the file remainder. 64856 // If so, return success. 64857 // If not, the ** "swallows" a segment, and try again. 64858 // This is recursively awful. 64859 // 64860 // a/**/b/**/c matching a/b/x/y/z/c 64861 // - a matches a 64862 // - doublestar 64863 // - matchOne(b/x/y/z/c, b/**/c) 64864 // - b matches b 64865 // - doublestar 64866 // - matchOne(x/y/z/c, c) -> no 64867 // - matchOne(y/z/c, c) -> no 64868 // - matchOne(z/c, c) -> no 64869 // - matchOne(c, c) yes, hit 64870 var fr = fi; 64871 var pr = pi + 1; 64872 if (pr === pl) { 64873 this.debug('** at the end'); 64874 // a ** at the end will just swallow the rest. 64875 // We have found a match. 64876 // however, it will not swallow /.x, unless 64877 // options.dot is set. 64878 // . and .. are *never* matched by **, for explosively 64879 // exponential reasons. 64880 for (; fi < fl; fi++) { 64881 if (file[fi] === '.' || 64882 file[fi] === '..' || 64883 (!options.dot && file[fi].charAt(0) === '.')) 64884 return false; 64885 } 64886 return true; 64887 } 64888 // ok, let's see if we can swallow whatever we can. 64889 while (fr < fl) { 64890 var swallowee = file[fr]; 64891 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); 64892 // XXX remove this slice. Just pass the start index. 64893 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { 64894 this.debug('globstar found match!', fr, fl, swallowee); 64895 // found a match. 64896 return true; 64897 } 64898 else { 64899 // can't swallow "." or ".." ever. 64900 // can only swallow ".foo" when explicitly asked. 64901 if (swallowee === '.' || 64902 swallowee === '..' || 64903 (!options.dot && swallowee.charAt(0) === '.')) { 64904 this.debug('dot detected!', file, fr, pattern, pr); 64905 break; 64906 } 64907 // ** swallows a segment, and continue. 64908 this.debug('globstar swallow a segment, and continue'); 64909 fr++; 64910 } 64911 } 64912 // no match was found. 64913 // However, in partial mode, we can't say this is necessarily over. 64914 /* c8 ignore start */ 64915 if (partial) { 64916 // ran out of file 64917 this.debug('\n>>> no match, partial?', file, fr, pattern, pr); 64918 if (fr === fl) { 64919 return true; 64920 } 64921 } 64922 /* c8 ignore stop */ 64923 return false; 64924 } 64925 // something other than ** 64926 // non-magic patterns just have to match exactly 64927 // patterns with magic have been turned into regexps. 64928 let hit; 64929 if (typeof p === 'string') { 64930 hit = f === p; 64931 this.debug('string match', p, f, hit); 64932 } 64933 else { 64934 hit = p.test(f); 64935 this.debug('pattern match', p, f, hit); 64936 } 64937 if (!hit) 64938 return false; 64939 } 64940 // Note: ending in / means that we'll get a final "" 64941 // at the end of the pattern. This can only match a 64942 // corresponding "" at the end of the file. 64943 // If the file ends in /, then it can only match a 64944 // a pattern that ends in /, unless the pattern just 64945 // doesn't have any more for it. But, a/b/ should *not* 64946 // match "a/b/*", even though "" matches against the 64947 // [^/]*? pattern, except in partial mode, where it might 64948 // simply not be reached yet. 64949 // However, a/b/ should still satisfy a/* 64950 // now either we fell off the end of the pattern, or we're done. 64951 if (fi === fl && pi === pl) { 64952 // ran out of pattern and filename at the same time. 64953 // an exact hit! 64954 return true; 64955 } 64956 else if (fi === fl) { 64957 // ran out of file, but still had pattern left. 64958 // this is ok if we're doing the match as part of 64959 // a glob fs traversal. 64960 return partial; 64961 } 64962 else if (pi === pl) { 64963 // ran out of pattern, still have file left. 64964 // this is only acceptable if we're on the very last 64965 // empty segment of a file with a trailing slash. 64966 // a/* should match a/b/ 64967 return fi === fl - 1 && file[fi] === ''; 64968 /* c8 ignore start */ 64969 } 64970 else { 64971 // should be unreachable. 64972 throw new Error('wtf?'); 64973 } 64974 /* c8 ignore stop */ 64975 } 64976 braceExpand() { 64977 return (0, exports.braceExpand)(this.pattern, this.options); 64978 } 64979 parse(pattern) { 64980 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 64981 const options = this.options; 64982 // shortcuts 64983 if (pattern === '**') 64984 return exports.GLOBSTAR; 64985 if (pattern === '') 64986 return ''; 64987 // far and away, the most common glob pattern parts are 64988 // *, *.*, and *.<ext> Add a fast check method for those. 64989 let m; 64990 let fastTest = null; 64991 if ((m = pattern.match(starRE))) { 64992 fastTest = options.dot ? starTestDot : starTest; 64993 } 64994 else if ((m = pattern.match(starDotExtRE))) { 64995 fastTest = (options.nocase 64996 ? options.dot 64997 ? starDotExtTestNocaseDot 64998 : starDotExtTestNocase 64999 : options.dot 65000 ? starDotExtTestDot 65001 : starDotExtTest)(m[1]); 65002 } 65003 else if ((m = pattern.match(qmarksRE))) { 65004 fastTest = (options.nocase 65005 ? options.dot 65006 ? qmarksTestNocaseDot 65007 : qmarksTestNocase 65008 : options.dot 65009 ? qmarksTestDot 65010 : qmarksTest)(m); 65011 } 65012 else if ((m = pattern.match(starDotStarRE))) { 65013 fastTest = options.dot ? starDotStarTestDot : starDotStarTest; 65014 } 65015 else if ((m = pattern.match(dotStarRE))) { 65016 fastTest = dotStarTest; 65017 } 65018 const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern(); 65019 return fastTest ? Object.assign(re, { test: fastTest }) : re; 65020 } 65021 makeRe() { 65022 if (this.regexp || this.regexp === false) 65023 return this.regexp; 65024 // at this point, this.set is a 2d array of partial 65025 // pattern strings, or "**". 65026 // 65027 // It's better to use .match(). This function shouldn't 65028 // be used, really, but it's pretty convenient sometimes, 65029 // when you just want to work with a regex. 65030 const set = this.set; 65031 if (!set.length) { 65032 this.regexp = false; 65033 return this.regexp; 65034 } 65035 const options = this.options; 65036 const twoStar = options.noglobstar 65037 ? star 65038 : options.dot 65039 ? twoStarDot 65040 : twoStarNoDot; 65041 const flags = new Set(options.nocase ? ['i'] : []); 65042 // regexpify non-globstar patterns 65043 // if ** is only item, then we just do one twoStar 65044 // if ** is first, and there are more, prepend (\/|twoStar\/)? to next 65045 // if ** is last, append (\/twoStar|) to previous 65046 // if ** is in the middle, append (\/|\/twoStar\/) to previous 65047 // then filter out GLOBSTAR symbols 65048 let re = set 65049 .map(pattern => { 65050 const pp = pattern.map(p => { 65051 if (p instanceof RegExp) { 65052 for (const f of p.flags.split('')) 65053 flags.add(f); 65054 } 65055 return typeof p === 'string' 65056 ? regExpEscape(p) 65057 : p === exports.GLOBSTAR 65058 ? exports.GLOBSTAR 65059 : p._src; 65060 }); 65061 pp.forEach((p, i) => { 65062 const next = pp[i + 1]; 65063 const prev = pp[i - 1]; 65064 if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) { 65065 return; 65066 } 65067 if (prev === undefined) { 65068 if (next !== undefined && next !== exports.GLOBSTAR) { 65069 pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next; 65070 } 65071 else { 65072 pp[i] = twoStar; 65073 } 65074 } 65075 else if (next === undefined) { 65076 pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; 65077 } 65078 else if (next !== exports.GLOBSTAR) { 65079 pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next; 65080 pp[i + 1] = exports.GLOBSTAR; 65081 } 65082 }); 65083 return pp.filter(p => p !== exports.GLOBSTAR).join('/'); 65084 }) 65085 .join('|'); 65086 // need to wrap in parens if we had more than one thing with |, 65087 // otherwise only the first will be anchored to ^ and the last to $ 65088 const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']; 65089 // must match entire pattern 65090 // ending in a * or ** will make it less strict. 65091 re = '^' + open + re + close + '$'; 65092 // can match anything, as long as it's not this. 65093 if (this.negate) 65094 re = '^(?!' + re + ').+$'; 65095 try { 65096 this.regexp = new RegExp(re, [...flags].join('')); 65097 /* c8 ignore start */ 65098 } 65099 catch (ex) { 65100 // should be impossible 65101 this.regexp = false; 65102 } 65103 /* c8 ignore stop */ 65104 return this.regexp; 65105 } 65106 slashSplit(p) { 65107 // if p starts with // on windows, we preserve that 65108 // so that UNC paths aren't broken. Otherwise, any number of 65109 // / characters are coalesced into one, unless 65110 // preserveMultipleSlashes is set to true. 65111 if (this.preserveMultipleSlashes) { 65112 return p.split('/'); 65113 } 65114 else if (this.isWindows && /^\/\/[^\/]+/.test(p)) { 65115 // add an extra '' for the one we lose 65116 return ['', ...p.split(/\/+/)]; 65117 } 65118 else { 65119 return p.split(/\/+/); 65120 } 65121 } 65122 match(f, partial = this.partial) { 65123 this.debug('match', f, this.pattern); 65124 // short-circuit in the case of busted things. 65125 // comments, etc. 65126 if (this.comment) { 65127 return false; 65128 } 65129 if (this.empty) { 65130 return f === ''; 65131 } 65132 if (f === '/' && partial) { 65133 return true; 65134 } 65135 const options = this.options; 65136 // windows: need to use /, not \ 65137 if (this.isWindows) { 65138 f = f.split('\\').join('/'); 65139 } 65140 // treat the test path as a set of pathparts. 65141 const ff = this.slashSplit(f); 65142 this.debug(this.pattern, 'split', ff); 65143 // just ONE of the pattern sets in this.set needs to match 65144 // in order for it to be valid. If negating, then just one 65145 // match means that we have failed. 65146 // Either way, return on the first hit. 65147 const set = this.set; 65148 this.debug(this.pattern, 'set', set); 65149 // Find the basename of the path by looking for the last non-empty segment 65150 let filename = ff[ff.length - 1]; 65151 if (!filename) { 65152 for (let i = ff.length - 2; !filename && i >= 0; i--) { 65153 filename = ff[i]; 65154 } 65155 } 65156 for (let i = 0; i < set.length; i++) { 65157 const pattern = set[i]; 65158 let file = ff; 65159 if (options.matchBase && pattern.length === 1) { 65160 file = [filename]; 65161 } 65162 const hit = this.matchOne(file, pattern, partial); 65163 if (hit) { 65164 if (options.flipNegate) { 65165 return true; 65166 } 65167 return !this.negate; 65168 } 65169 } 65170 // didn't get any hits. this is success if it's a negative 65171 // pattern, failure otherwise. 65172 if (options.flipNegate) { 65173 return false; 65174 } 65175 return this.negate; 65176 } 65177 static defaults(def) { 65178 return exports.minimatch.defaults(def).Minimatch; 65179 } 65180 } 65181 exports.Minimatch = Minimatch; 65182 /* c8 ignore start */ 65183 var ast_js_2 = __nccwpck_require__(596); 65184 Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } })); 65185 var escape_js_2 = __nccwpck_require__(5615); 65186 Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } })); 65187 var unescape_js_2 = __nccwpck_require__(6615); 65188 Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } })); 65189 /* c8 ignore stop */ 65190 exports.minimatch.AST = ast_js_1.AST; 65191 exports.minimatch.Minimatch = Minimatch; 65192 exports.minimatch.escape = escape_js_1.escape; 65193 exports.minimatch.unescape = unescape_js_1.unescape; 65194 //# sourceMappingURL=index.js.map 65195 65196 /***/ }), 65197 65198 /***/ 6615: 65199 /***/ ((__unused_webpack_module, exports) => { 65200 65201 "use strict"; 65202 65203 Object.defineProperty(exports, "__esModule", ({ value: true })); 65204 exports.unescape = void 0; 65205 /** 65206 * Un-escape a string that has been escaped with {@link escape}. 65207 * 65208 * If the {@link windowsPathsNoEscape} option is used, then square-brace 65209 * escapes are removed, but not backslash escapes. For example, it will turn 65210 * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`, 65211 * becuase `\` is a path separator in `windowsPathsNoEscape` mode. 65212 * 65213 * When `windowsPathsNoEscape` is not set, then both brace escapes and 65214 * backslash escapes are removed. 65215 * 65216 * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped 65217 * or unescaped. 65218 */ 65219 const unescape = (s, { windowsPathsNoEscape = false, } = {}) => { 65220 return windowsPathsNoEscape 65221 ? s.replace(/\[([^\/\\])\]/g, '$1') 65222 : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1'); 65223 }; 65224 exports.unescape = unescape; 65225 //# sourceMappingURL=unescape.js.map 65226 65227 /***/ }), 65228 65229 /***/ 5339: 65230 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65231 65232 "use strict"; 65233 65234 Object.defineProperty(exports, "__esModule", ({ value: true })); 65235 exports.Glob = void 0; 65236 const minimatch_1 = __nccwpck_require__(7111); 65237 const path_scurry_1 = __nccwpck_require__(1081); 65238 const url_1 = __nccwpck_require__(7310); 65239 const pattern_js_1 = __nccwpck_require__(2895); 65240 const walker_js_1 = __nccwpck_require__(5548); 65241 // if no process global, just call it linux. 65242 // so we default to case-sensitive, / separators 65243 const defaultPlatform = typeof process === 'object' && 65244 process && 65245 typeof process.platform === 'string' 65246 ? process.platform 65247 : 'linux'; 65248 /** 65249 * An object that can perform glob pattern traversals. 65250 */ 65251 class Glob { 65252 absolute; 65253 cwd; 65254 root; 65255 dot; 65256 dotRelative; 65257 follow; 65258 ignore; 65259 magicalBraces; 65260 mark; 65261 matchBase; 65262 maxDepth; 65263 nobrace; 65264 nocase; 65265 nodir; 65266 noext; 65267 noglobstar; 65268 pattern; 65269 platform; 65270 realpath; 65271 scurry; 65272 stat; 65273 signal; 65274 windowsPathsNoEscape; 65275 withFileTypes; 65276 /** 65277 * The options provided to the constructor. 65278 */ 65279 opts; 65280 /** 65281 * An array of parsed immutable {@link Pattern} objects. 65282 */ 65283 patterns; 65284 /** 65285 * All options are stored as properties on the `Glob` object. 65286 * 65287 * See {@link GlobOptions} for full options descriptions. 65288 * 65289 * Note that a previous `Glob` object can be passed as the 65290 * `GlobOptions` to another `Glob` instantiation to re-use settings 65291 * and caches with a new pattern. 65292 * 65293 * Traversal functions can be called multiple times to run the walk 65294 * again. 65295 */ 65296 constructor(pattern, opts) { 65297 /* c8 ignore start */ 65298 if (!opts) 65299 throw new TypeError('glob options required'); 65300 /* c8 ignore stop */ 65301 this.withFileTypes = !!opts.withFileTypes; 65302 this.signal = opts.signal; 65303 this.follow = !!opts.follow; 65304 this.dot = !!opts.dot; 65305 this.dotRelative = !!opts.dotRelative; 65306 this.nodir = !!opts.nodir; 65307 this.mark = !!opts.mark; 65308 if (!opts.cwd) { 65309 this.cwd = ''; 65310 } 65311 else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { 65312 opts.cwd = (0, url_1.fileURLToPath)(opts.cwd); 65313 } 65314 this.cwd = opts.cwd || ''; 65315 this.root = opts.root; 65316 this.magicalBraces = !!opts.magicalBraces; 65317 this.nobrace = !!opts.nobrace; 65318 this.noext = !!opts.noext; 65319 this.realpath = !!opts.realpath; 65320 this.absolute = opts.absolute; 65321 this.noglobstar = !!opts.noglobstar; 65322 this.matchBase = !!opts.matchBase; 65323 this.maxDepth = 65324 typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; 65325 this.stat = !!opts.stat; 65326 this.ignore = opts.ignore; 65327 if (this.withFileTypes && this.absolute !== undefined) { 65328 throw new Error('cannot set absolute and withFileTypes:true'); 65329 } 65330 if (typeof pattern === 'string') { 65331 pattern = [pattern]; 65332 } 65333 this.windowsPathsNoEscape = 65334 !!opts.windowsPathsNoEscape || 65335 opts.allowWindowsEscape === false; 65336 if (this.windowsPathsNoEscape) { 65337 pattern = pattern.map(p => p.replace(/\\/g, '/')); 65338 } 65339 if (this.matchBase) { 65340 if (opts.noglobstar) { 65341 throw new TypeError('base matching requires globstar'); 65342 } 65343 pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); 65344 } 65345 this.pattern = pattern; 65346 this.platform = opts.platform || defaultPlatform; 65347 this.opts = { ...opts, platform: this.platform }; 65348 if (opts.scurry) { 65349 this.scurry = opts.scurry; 65350 if (opts.nocase !== undefined && 65351 opts.nocase !== opts.scurry.nocase) { 65352 throw new Error('nocase option contradicts provided scurry option'); 65353 } 65354 } 65355 else { 65356 const Scurry = opts.platform === 'win32' 65357 ? path_scurry_1.PathScurryWin32 65358 : opts.platform === 'darwin' 65359 ? path_scurry_1.PathScurryDarwin 65360 : opts.platform 65361 ? path_scurry_1.PathScurryPosix 65362 : path_scurry_1.PathScurry; 65363 this.scurry = new Scurry(this.cwd, { 65364 nocase: opts.nocase, 65365 fs: opts.fs, 65366 }); 65367 } 65368 this.nocase = this.scurry.nocase; 65369 // If you do nocase:true on a case-sensitive file system, then 65370 // we need to use regexps instead of strings for non-magic 65371 // path portions, because statting `aBc` won't return results 65372 // for the file `AbC` for example. 65373 const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; 65374 const mmo = { 65375 // default nocase based on platform 65376 ...opts, 65377 dot: this.dot, 65378 matchBase: this.matchBase, 65379 nobrace: this.nobrace, 65380 nocase: this.nocase, 65381 nocaseMagicOnly, 65382 nocomment: true, 65383 noext: this.noext, 65384 nonegate: true, 65385 optimizationLevel: 2, 65386 platform: this.platform, 65387 windowsPathsNoEscape: this.windowsPathsNoEscape, 65388 debug: !!this.opts.debug, 65389 }; 65390 const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); 65391 const [matchSet, globParts] = mms.reduce((set, m) => { 65392 set[0].push(...m.set); 65393 set[1].push(...m.globParts); 65394 return set; 65395 }, [[], []]); 65396 this.patterns = matchSet.map((set, i) => { 65397 const g = globParts[i]; 65398 /* c8 ignore start */ 65399 if (!g) 65400 throw new Error('invalid pattern object'); 65401 /* c8 ignore stop */ 65402 return new pattern_js_1.Pattern(set, g, 0, this.platform); 65403 }); 65404 } 65405 async walk() { 65406 // Walkers always return array of Path objects, so we just have to 65407 // coerce them into the right shape. It will have already called 65408 // realpath() if the option was set to do so, so we know that's cached. 65409 // start out knowing the cwd, at least 65410 return [ 65411 ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { 65412 ...this.opts, 65413 maxDepth: this.maxDepth !== Infinity 65414 ? this.maxDepth + this.scurry.cwd.depth() 65415 : Infinity, 65416 platform: this.platform, 65417 nocase: this.nocase, 65418 }).walk()), 65419 ]; 65420 } 65421 walkSync() { 65422 return [ 65423 ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { 65424 ...this.opts, 65425 maxDepth: this.maxDepth !== Infinity 65426 ? this.maxDepth + this.scurry.cwd.depth() 65427 : Infinity, 65428 platform: this.platform, 65429 nocase: this.nocase, 65430 }).walkSync(), 65431 ]; 65432 } 65433 stream() { 65434 return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { 65435 ...this.opts, 65436 maxDepth: this.maxDepth !== Infinity 65437 ? this.maxDepth + this.scurry.cwd.depth() 65438 : Infinity, 65439 platform: this.platform, 65440 nocase: this.nocase, 65441 }).stream(); 65442 } 65443 streamSync() { 65444 return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { 65445 ...this.opts, 65446 maxDepth: this.maxDepth !== Infinity 65447 ? this.maxDepth + this.scurry.cwd.depth() 65448 : Infinity, 65449 platform: this.platform, 65450 nocase: this.nocase, 65451 }).streamSync(); 65452 } 65453 /** 65454 * Default sync iteration function. Returns a Generator that 65455 * iterates over the results. 65456 */ 65457 iterateSync() { 65458 return this.streamSync()[Symbol.iterator](); 65459 } 65460 [Symbol.iterator]() { 65461 return this.iterateSync(); 65462 } 65463 /** 65464 * Default async iteration function. Returns an AsyncGenerator that 65465 * iterates over the results. 65466 */ 65467 iterate() { 65468 return this.stream()[Symbol.asyncIterator](); 65469 } 65470 [Symbol.asyncIterator]() { 65471 return this.iterate(); 65472 } 65473 } 65474 exports.Glob = Glob; 65475 //# sourceMappingURL=glob.js.map 65476 65477 /***/ }), 65478 65479 /***/ 6490: 65480 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65481 65482 "use strict"; 65483 65484 Object.defineProperty(exports, "__esModule", ({ value: true })); 65485 exports.hasMagic = void 0; 65486 const minimatch_1 = __nccwpck_require__(7111); 65487 /** 65488 * Return true if the patterns provided contain any magic glob characters, 65489 * given the options provided. 65490 * 65491 * Brace expansion is not considered "magic" unless the `magicalBraces` option 65492 * is set, as brace expansion just turns one string into an array of strings. 65493 * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and 65494 * `'xby'` both do not contain any magic glob characters, and it's treated the 65495 * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` 65496 * is in the options, brace expansion _is_ treated as a pattern having magic. 65497 */ 65498 const hasMagic = (pattern, options = {}) => { 65499 if (!Array.isArray(pattern)) { 65500 pattern = [pattern]; 65501 } 65502 for (const p of pattern) { 65503 if (new minimatch_1.Minimatch(p, options).hasMagic()) 65504 return true; 65505 } 65506 return false; 65507 }; 65508 exports.hasMagic = hasMagic; 65509 //# sourceMappingURL=has-magic.js.map 65510 65511 /***/ }), 65512 65513 /***/ 750: 65514 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65515 65516 "use strict"; 65517 65518 // give it a pattern, and it'll be able to tell you if 65519 // a given path should be ignored. 65520 // Ignoring a path ignores its children if the pattern ends in /** 65521 // Ignores are always parsed in dot:true mode 65522 Object.defineProperty(exports, "__esModule", ({ value: true })); 65523 exports.Ignore = void 0; 65524 const minimatch_1 = __nccwpck_require__(7111); 65525 const pattern_js_1 = __nccwpck_require__(2895); 65526 const defaultPlatform = typeof process === 'object' && 65527 process && 65528 typeof process.platform === 'string' 65529 ? process.platform 65530 : 'linux'; 65531 /** 65532 * Class used to process ignored patterns 65533 */ 65534 class Ignore { 65535 relative; 65536 relativeChildren; 65537 absolute; 65538 absoluteChildren; 65539 constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { 65540 this.relative = []; 65541 this.absolute = []; 65542 this.relativeChildren = []; 65543 this.absoluteChildren = []; 65544 const mmopts = { 65545 dot: true, 65546 nobrace, 65547 nocase, 65548 noext, 65549 noglobstar, 65550 optimizationLevel: 2, 65551 platform, 65552 nocomment: true, 65553 nonegate: true, 65554 }; 65555 // this is a little weird, but it gives us a clean set of optimized 65556 // minimatch matchers, without getting tripped up if one of them 65557 // ends in /** inside a brace section, and it's only inefficient at 65558 // the start of the walk, not along it. 65559 // It'd be nice if the Pattern class just had a .test() method, but 65560 // handling globstars is a bit of a pita, and that code already lives 65561 // in minimatch anyway. 65562 // Another way would be if maybe Minimatch could take its set/globParts 65563 // as an option, and then we could at least just use Pattern to test 65564 // for absolute-ness. 65565 // Yet another way, Minimatch could take an array of glob strings, and 65566 // a cwd option, and do the right thing. 65567 for (const ign of ignored) { 65568 const mm = new minimatch_1.Minimatch(ign, mmopts); 65569 for (let i = 0; i < mm.set.length; i++) { 65570 const parsed = mm.set[i]; 65571 const globParts = mm.globParts[i]; 65572 /* c8 ignore start */ 65573 if (!parsed || !globParts) { 65574 throw new Error('invalid pattern object'); 65575 } 65576 /* c8 ignore stop */ 65577 const p = new pattern_js_1.Pattern(parsed, globParts, 0, platform); 65578 const m = new minimatch_1.Minimatch(p.globString(), mmopts); 65579 const children = globParts[globParts.length - 1] === '**'; 65580 const absolute = p.isAbsolute(); 65581 if (absolute) 65582 this.absolute.push(m); 65583 else 65584 this.relative.push(m); 65585 if (children) { 65586 if (absolute) 65587 this.absoluteChildren.push(m); 65588 else 65589 this.relativeChildren.push(m); 65590 } 65591 } 65592 } 65593 } 65594 ignored(p) { 65595 const fullpath = p.fullpath(); 65596 const fullpaths = `${fullpath}/`; 65597 const relative = p.relative() || '.'; 65598 const relatives = `${relative}/`; 65599 for (const m of this.relative) { 65600 if (m.match(relative) || m.match(relatives)) 65601 return true; 65602 } 65603 for (const m of this.absolute) { 65604 if (m.match(fullpath) || m.match(fullpaths)) 65605 return true; 65606 } 65607 return false; 65608 } 65609 childrenIgnored(p) { 65610 const fullpath = p.fullpath() + '/'; 65611 const relative = (p.relative() || '.') + '/'; 65612 for (const m of this.relativeChildren) { 65613 if (m.match(relative)) 65614 return true; 65615 } 65616 for (const m of this.absoluteChildren) { 65617 if (m.match(fullpath)) 65618 return true; 65619 } 65620 return false; 65621 } 65622 } 65623 exports.Ignore = Ignore; 65624 //# sourceMappingURL=ignore.js.map 65625 65626 /***/ }), 65627 65628 /***/ 836: 65629 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65630 65631 "use strict"; 65632 65633 Object.defineProperty(exports, "__esModule", ({ value: true })); 65634 exports.glob = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.globIterate = exports.globIterateSync = exports.globSync = exports.globStream = exports.globStreamSync = void 0; 65635 const minimatch_1 = __nccwpck_require__(7111); 65636 const glob_js_1 = __nccwpck_require__(5339); 65637 const has_magic_js_1 = __nccwpck_require__(6490); 65638 function globStreamSync(pattern, options = {}) { 65639 return new glob_js_1.Glob(pattern, options).streamSync(); 65640 } 65641 exports.globStreamSync = globStreamSync; 65642 function globStream(pattern, options = {}) { 65643 return new glob_js_1.Glob(pattern, options).stream(); 65644 } 65645 exports.globStream = globStream; 65646 function globSync(pattern, options = {}) { 65647 return new glob_js_1.Glob(pattern, options).walkSync(); 65648 } 65649 exports.globSync = globSync; 65650 async function glob_(pattern, options = {}) { 65651 return new glob_js_1.Glob(pattern, options).walk(); 65652 } 65653 function globIterateSync(pattern, options = {}) { 65654 return new glob_js_1.Glob(pattern, options).iterateSync(); 65655 } 65656 exports.globIterateSync = globIterateSync; 65657 function globIterate(pattern, options = {}) { 65658 return new glob_js_1.Glob(pattern, options).iterate(); 65659 } 65660 exports.globIterate = globIterate; 65661 // aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc 65662 exports.streamSync = globStreamSync; 65663 exports.stream = Object.assign(globStream, { sync: globStreamSync }); 65664 exports.iterateSync = globIterateSync; 65665 exports.iterate = Object.assign(globIterate, { 65666 sync: globIterateSync, 65667 }); 65668 exports.sync = Object.assign(globSync, { 65669 stream: globStreamSync, 65670 iterate: globIterateSync, 65671 }); 65672 /* c8 ignore start */ 65673 var minimatch_2 = __nccwpck_require__(7111); 65674 Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return minimatch_2.escape; } })); 65675 Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return minimatch_2.unescape; } })); 65676 var glob_js_2 = __nccwpck_require__(5339); 65677 Object.defineProperty(exports, "Glob", ({ enumerable: true, get: function () { return glob_js_2.Glob; } })); 65678 var has_magic_js_2 = __nccwpck_require__(6490); 65679 Object.defineProperty(exports, "hasMagic", ({ enumerable: true, get: function () { return has_magic_js_2.hasMagic; } })); 65680 /* c8 ignore stop */ 65681 exports.glob = Object.assign(glob_, { 65682 glob: glob_, 65683 globSync, 65684 sync: exports.sync, 65685 globStream, 65686 stream: exports.stream, 65687 globStreamSync, 65688 streamSync: exports.streamSync, 65689 globIterate, 65690 iterate: exports.iterate, 65691 globIterateSync, 65692 iterateSync: exports.iterateSync, 65693 Glob: glob_js_1.Glob, 65694 hasMagic: has_magic_js_1.hasMagic, 65695 escape: minimatch_1.escape, 65696 unescape: minimatch_1.unescape, 65697 }); 65698 exports.glob.glob = exports.glob; 65699 //# sourceMappingURL=index.js.map 65700 65701 /***/ }), 65702 65703 /***/ 2895: 65704 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65705 65706 "use strict"; 65707 65708 // this is just a very light wrapper around 2 arrays with an offset index 65709 Object.defineProperty(exports, "__esModule", ({ value: true })); 65710 exports.Pattern = void 0; 65711 const minimatch_1 = __nccwpck_require__(7111); 65712 const isPatternList = (pl) => pl.length >= 1; 65713 const isGlobList = (gl) => gl.length >= 1; 65714 /** 65715 * An immutable-ish view on an array of glob parts and their parsed 65716 * results 65717 */ 65718 class Pattern { 65719 #patternList; 65720 #globList; 65721 #index; 65722 length; 65723 #platform; 65724 #rest; 65725 #globString; 65726 #isDrive; 65727 #isUNC; 65728 #isAbsolute; 65729 #followGlobstar = true; 65730 constructor(patternList, globList, index, platform) { 65731 if (!isPatternList(patternList)) { 65732 throw new TypeError('empty pattern list'); 65733 } 65734 if (!isGlobList(globList)) { 65735 throw new TypeError('empty glob list'); 65736 } 65737 if (globList.length !== patternList.length) { 65738 throw new TypeError('mismatched pattern list and glob list lengths'); 65739 } 65740 this.length = patternList.length; 65741 if (index < 0 || index >= this.length) { 65742 throw new TypeError('index out of range'); 65743 } 65744 this.#patternList = patternList; 65745 this.#globList = globList; 65746 this.#index = index; 65747 this.#platform = platform; 65748 // normalize root entries of absolute patterns on initial creation. 65749 if (this.#index === 0) { 65750 // c: => ['c:/'] 65751 // C:/ => ['C:/'] 65752 // C:/x => ['C:/', 'x'] 65753 // //host/share => ['//host/share/'] 65754 // //host/share/ => ['//host/share/'] 65755 // //host/share/x => ['//host/share/', 'x'] 65756 // /etc => ['/', 'etc'] 65757 // / => ['/'] 65758 if (this.isUNC()) { 65759 // '' / '' / 'host' / 'share' 65760 const [p0, p1, p2, p3, ...prest] = this.#patternList; 65761 const [g0, g1, g2, g3, ...grest] = this.#globList; 65762 if (prest[0] === '') { 65763 // ends in / 65764 prest.shift(); 65765 grest.shift(); 65766 } 65767 const p = [p0, p1, p2, p3, ''].join('/'); 65768 const g = [g0, g1, g2, g3, ''].join('/'); 65769 this.#patternList = [p, ...prest]; 65770 this.#globList = [g, ...grest]; 65771 this.length = this.#patternList.length; 65772 } 65773 else if (this.isDrive() || this.isAbsolute()) { 65774 const [p1, ...prest] = this.#patternList; 65775 const [g1, ...grest] = this.#globList; 65776 if (prest[0] === '') { 65777 // ends in / 65778 prest.shift(); 65779 grest.shift(); 65780 } 65781 const p = p1 + '/'; 65782 const g = g1 + '/'; 65783 this.#patternList = [p, ...prest]; 65784 this.#globList = [g, ...grest]; 65785 this.length = this.#patternList.length; 65786 } 65787 } 65788 } 65789 /** 65790 * The first entry in the parsed list of patterns 65791 */ 65792 pattern() { 65793 return this.#patternList[this.#index]; 65794 } 65795 /** 65796 * true of if pattern() returns a string 65797 */ 65798 isString() { 65799 return typeof this.#patternList[this.#index] === 'string'; 65800 } 65801 /** 65802 * true of if pattern() returns GLOBSTAR 65803 */ 65804 isGlobstar() { 65805 return this.#patternList[this.#index] === minimatch_1.GLOBSTAR; 65806 } 65807 /** 65808 * true if pattern() returns a regexp 65809 */ 65810 isRegExp() { 65811 return this.#patternList[this.#index] instanceof RegExp; 65812 } 65813 /** 65814 * The /-joined set of glob parts that make up this pattern 65815 */ 65816 globString() { 65817 return (this.#globString = 65818 this.#globString || 65819 (this.#index === 0 65820 ? this.isAbsolute() 65821 ? this.#globList[0] + this.#globList.slice(1).join('/') 65822 : this.#globList.join('/') 65823 : this.#globList.slice(this.#index).join('/'))); 65824 } 65825 /** 65826 * true if there are more pattern parts after this one 65827 */ 65828 hasMore() { 65829 return this.length > this.#index + 1; 65830 } 65831 /** 65832 * The rest of the pattern after this part, or null if this is the end 65833 */ 65834 rest() { 65835 if (this.#rest !== undefined) 65836 return this.#rest; 65837 if (!this.hasMore()) 65838 return (this.#rest = null); 65839 this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); 65840 this.#rest.#isAbsolute = this.#isAbsolute; 65841 this.#rest.#isUNC = this.#isUNC; 65842 this.#rest.#isDrive = this.#isDrive; 65843 return this.#rest; 65844 } 65845 /** 65846 * true if the pattern represents a //unc/path/ on windows 65847 */ 65848 isUNC() { 65849 const pl = this.#patternList; 65850 return this.#isUNC !== undefined 65851 ? this.#isUNC 65852 : (this.#isUNC = 65853 this.#platform === 'win32' && 65854 this.#index === 0 && 65855 pl[0] === '' && 65856 pl[1] === '' && 65857 typeof pl[2] === 'string' && 65858 !!pl[2] && 65859 typeof pl[3] === 'string' && 65860 !!pl[3]); 65861 } 65862 // pattern like C:/... 65863 // split = ['C:', ...] 65864 // XXX: would be nice to handle patterns like `c:*` to test the cwd 65865 // in c: for *, but I don't know of a way to even figure out what that 65866 // cwd is without actually chdir'ing into it? 65867 /** 65868 * True if the pattern starts with a drive letter on Windows 65869 */ 65870 isDrive() { 65871 const pl = this.#patternList; 65872 return this.#isDrive !== undefined 65873 ? this.#isDrive 65874 : (this.#isDrive = 65875 this.#platform === 'win32' && 65876 this.#index === 0 && 65877 this.length > 1 && 65878 typeof pl[0] === 'string' && 65879 /^[a-z]:$/i.test(pl[0])); 65880 } 65881 // pattern = '/' or '/...' or '/x/...' 65882 // split = ['', ''] or ['', ...] or ['', 'x', ...] 65883 // Drive and UNC both considered absolute on windows 65884 /** 65885 * True if the pattern is rooted on an absolute path 65886 */ 65887 isAbsolute() { 65888 const pl = this.#patternList; 65889 return this.#isAbsolute !== undefined 65890 ? this.#isAbsolute 65891 : (this.#isAbsolute = 65892 (pl[0] === '' && pl.length > 1) || 65893 this.isDrive() || 65894 this.isUNC()); 65895 } 65896 /** 65897 * consume the root of the pattern, and return it 65898 */ 65899 root() { 65900 const p = this.#patternList[0]; 65901 return typeof p === 'string' && this.isAbsolute() && this.#index === 0 65902 ? p 65903 : ''; 65904 } 65905 /** 65906 * Check to see if the current globstar pattern is allowed to follow 65907 * a symbolic link. 65908 */ 65909 checkFollowGlobstar() { 65910 return !(this.#index === 0 || 65911 !this.isGlobstar() || 65912 !this.#followGlobstar); 65913 } 65914 /** 65915 * Mark that the current globstar pattern is following a symbolic link 65916 */ 65917 markFollowGlobstar() { 65918 if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) 65919 return false; 65920 this.#followGlobstar = false; 65921 return true; 65922 } 65923 } 65924 exports.Pattern = Pattern; 65925 //# sourceMappingURL=pattern.js.map 65926 65927 /***/ }), 65928 65929 /***/ 2813: 65930 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 65931 65932 "use strict"; 65933 65934 // synchronous utility for filtering entries and calculating subwalks 65935 Object.defineProperty(exports, "__esModule", ({ value: true })); 65936 exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0; 65937 const minimatch_1 = __nccwpck_require__(7111); 65938 /** 65939 * A cache of which patterns have been processed for a given Path 65940 */ 65941 class HasWalkedCache { 65942 store; 65943 constructor(store = new Map()) { 65944 this.store = store; 65945 } 65946 copy() { 65947 return new HasWalkedCache(new Map(this.store)); 65948 } 65949 hasWalked(target, pattern) { 65950 return this.store.get(target.fullpath())?.has(pattern.globString()); 65951 } 65952 storeWalked(target, pattern) { 65953 const fullpath = target.fullpath(); 65954 const cached = this.store.get(fullpath); 65955 if (cached) 65956 cached.add(pattern.globString()); 65957 else 65958 this.store.set(fullpath, new Set([pattern.globString()])); 65959 } 65960 } 65961 exports.HasWalkedCache = HasWalkedCache; 65962 /** 65963 * A record of which paths have been matched in a given walk step, 65964 * and whether they only are considered a match if they are a directory, 65965 * and whether their absolute or relative path should be returned. 65966 */ 65967 class MatchRecord { 65968 store = new Map(); 65969 add(target, absolute, ifDir) { 65970 const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); 65971 const current = this.store.get(target); 65972 this.store.set(target, current === undefined ? n : n & current); 65973 } 65974 // match, absolute, ifdir 65975 entries() { 65976 return [...this.store.entries()].map(([path, n]) => [ 65977 path, 65978 !!(n & 2), 65979 !!(n & 1), 65980 ]); 65981 } 65982 } 65983 exports.MatchRecord = MatchRecord; 65984 /** 65985 * A collection of patterns that must be processed in a subsequent step 65986 * for a given path. 65987 */ 65988 class SubWalks { 65989 store = new Map(); 65990 add(target, pattern) { 65991 if (!target.canReaddir()) { 65992 return; 65993 } 65994 const subs = this.store.get(target); 65995 if (subs) { 65996 if (!subs.find(p => p.globString() === pattern.globString())) { 65997 subs.push(pattern); 65998 } 65999 } 66000 else 66001 this.store.set(target, [pattern]); 66002 } 66003 get(target) { 66004 const subs = this.store.get(target); 66005 /* c8 ignore start */ 66006 if (!subs) { 66007 throw new Error('attempting to walk unknown path'); 66008 } 66009 /* c8 ignore stop */ 66010 return subs; 66011 } 66012 entries() { 66013 return this.keys().map(k => [k, this.store.get(k)]); 66014 } 66015 keys() { 66016 return [...this.store.keys()].filter(t => t.canReaddir()); 66017 } 66018 } 66019 exports.SubWalks = SubWalks; 66020 /** 66021 * The class that processes patterns for a given path. 66022 * 66023 * Handles child entry filtering, and determining whether a path's 66024 * directory contents must be read. 66025 */ 66026 class Processor { 66027 hasWalkedCache; 66028 matches = new MatchRecord(); 66029 subwalks = new SubWalks(); 66030 patterns; 66031 follow; 66032 dot; 66033 opts; 66034 constructor(opts, hasWalkedCache) { 66035 this.opts = opts; 66036 this.follow = !!opts.follow; 66037 this.dot = !!opts.dot; 66038 this.hasWalkedCache = hasWalkedCache 66039 ? hasWalkedCache.copy() 66040 : new HasWalkedCache(); 66041 } 66042 processPatterns(target, patterns) { 66043 this.patterns = patterns; 66044 const processingSet = patterns.map(p => [target, p]); 66045 // map of paths to the magic-starting subwalks they need to walk 66046 // first item in patterns is the filter 66047 for (let [t, pattern] of processingSet) { 66048 this.hasWalkedCache.storeWalked(t, pattern); 66049 const root = pattern.root(); 66050 const absolute = pattern.isAbsolute() && this.opts.absolute !== false; 66051 // start absolute patterns at root 66052 if (root) { 66053 t = t.resolve(root === '/' && this.opts.root !== undefined 66054 ? this.opts.root 66055 : root); 66056 const rest = pattern.rest(); 66057 if (!rest) { 66058 this.matches.add(t, true, false); 66059 continue; 66060 } 66061 else { 66062 pattern = rest; 66063 } 66064 } 66065 if (t.isENOENT()) 66066 continue; 66067 let p; 66068 let rest; 66069 let changed = false; 66070 while (typeof (p = pattern.pattern()) === 'string' && 66071 (rest = pattern.rest())) { 66072 const c = t.resolve(p); 66073 t = c; 66074 pattern = rest; 66075 changed = true; 66076 } 66077 p = pattern.pattern(); 66078 rest = pattern.rest(); 66079 if (changed) { 66080 if (this.hasWalkedCache.hasWalked(t, pattern)) 66081 continue; 66082 this.hasWalkedCache.storeWalked(t, pattern); 66083 } 66084 // now we have either a final string for a known entry, 66085 // more strings for an unknown entry, 66086 // or a pattern starting with magic, mounted on t. 66087 if (typeof p === 'string') { 66088 // must not be final entry, otherwise we would have 66089 // concatenated it earlier. 66090 const ifDir = p === '..' || p === '' || p === '.'; 66091 this.matches.add(t.resolve(p), absolute, ifDir); 66092 continue; 66093 } 66094 else if (p === minimatch_1.GLOBSTAR) { 66095 // if no rest, match and subwalk pattern 66096 // if rest, process rest and subwalk pattern 66097 // if it's a symlink, but we didn't get here by way of a 66098 // globstar match (meaning it's the first time THIS globstar 66099 // has traversed a symlink), then we follow it. Otherwise, stop. 66100 if (!t.isSymbolicLink() || 66101 this.follow || 66102 pattern.checkFollowGlobstar()) { 66103 this.subwalks.add(t, pattern); 66104 } 66105 const rp = rest?.pattern(); 66106 const rrest = rest?.rest(); 66107 if (!rest || ((rp === '' || rp === '.') && !rrest)) { 66108 // only HAS to be a dir if it ends in **/ or **/. 66109 // but ending in ** will match files as well. 66110 this.matches.add(t, absolute, rp === '' || rp === '.'); 66111 } 66112 else { 66113 if (rp === '..') { 66114 // this would mean you're matching **/.. at the fs root, 66115 // and no thanks, I'm not gonna test that specific case. 66116 /* c8 ignore start */ 66117 const tp = t.parent || t; 66118 /* c8 ignore stop */ 66119 if (!rrest) 66120 this.matches.add(tp, absolute, true); 66121 else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { 66122 this.subwalks.add(tp, rrest); 66123 } 66124 } 66125 } 66126 } 66127 else if (p instanceof RegExp) { 66128 this.subwalks.add(t, pattern); 66129 } 66130 } 66131 return this; 66132 } 66133 subwalkTargets() { 66134 return this.subwalks.keys(); 66135 } 66136 child() { 66137 return new Processor(this.opts, this.hasWalkedCache); 66138 } 66139 // return a new Processor containing the subwalks for each 66140 // child entry, and a set of matches, and 66141 // a hasWalkedCache that's a copy of this one 66142 // then we're going to call 66143 filterEntries(parent, entries) { 66144 const patterns = this.subwalks.get(parent); 66145 // put matches and entry walks into the results processor 66146 const results = this.child(); 66147 for (const e of entries) { 66148 for (const pattern of patterns) { 66149 const absolute = pattern.isAbsolute(); 66150 const p = pattern.pattern(); 66151 const rest = pattern.rest(); 66152 if (p === minimatch_1.GLOBSTAR) { 66153 results.testGlobstar(e, pattern, rest, absolute); 66154 } 66155 else if (p instanceof RegExp) { 66156 results.testRegExp(e, p, rest, absolute); 66157 } 66158 else { 66159 results.testString(e, p, rest, absolute); 66160 } 66161 } 66162 } 66163 return results; 66164 } 66165 testGlobstar(e, pattern, rest, absolute) { 66166 if (this.dot || !e.name.startsWith('.')) { 66167 if (!pattern.hasMore()) { 66168 this.matches.add(e, absolute, false); 66169 } 66170 if (e.canReaddir()) { 66171 // if we're in follow mode or it's not a symlink, just keep 66172 // testing the same pattern. If there's more after the globstar, 66173 // then this symlink consumes the globstar. If not, then we can 66174 // follow at most ONE symlink along the way, so we mark it, which 66175 // also checks to ensure that it wasn't already marked. 66176 if (this.follow || !e.isSymbolicLink()) { 66177 this.subwalks.add(e, pattern); 66178 } 66179 else if (e.isSymbolicLink()) { 66180 if (rest && pattern.checkFollowGlobstar()) { 66181 this.subwalks.add(e, rest); 66182 } 66183 else if (pattern.markFollowGlobstar()) { 66184 this.subwalks.add(e, pattern); 66185 } 66186 } 66187 } 66188 } 66189 // if the NEXT thing matches this entry, then also add 66190 // the rest. 66191 if (rest) { 66192 const rp = rest.pattern(); 66193 if (typeof rp === 'string' && 66194 // dots and empty were handled already 66195 rp !== '..' && 66196 rp !== '' && 66197 rp !== '.') { 66198 this.testString(e, rp, rest.rest(), absolute); 66199 } 66200 else if (rp === '..') { 66201 /* c8 ignore start */ 66202 const ep = e.parent || e; 66203 /* c8 ignore stop */ 66204 this.subwalks.add(ep, rest); 66205 } 66206 else if (rp instanceof RegExp) { 66207 this.testRegExp(e, rp, rest.rest(), absolute); 66208 } 66209 } 66210 } 66211 testRegExp(e, p, rest, absolute) { 66212 if (!p.test(e.name)) 66213 return; 66214 if (!rest) { 66215 this.matches.add(e, absolute, false); 66216 } 66217 else { 66218 this.subwalks.add(e, rest); 66219 } 66220 } 66221 testString(e, p, rest, absolute) { 66222 // should never happen? 66223 if (!e.isNamed(p)) 66224 return; 66225 if (!rest) { 66226 this.matches.add(e, absolute, false); 66227 } 66228 else { 66229 this.subwalks.add(e, rest); 66230 } 66231 } 66232 } 66233 exports.Processor = Processor; 66234 //# sourceMappingURL=processor.js.map 66235 66236 /***/ }), 66237 66238 /***/ 5548: 66239 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 66240 66241 "use strict"; 66242 66243 Object.defineProperty(exports, "__esModule", ({ value: true })); 66244 exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0; 66245 /** 66246 * Single-use utility classes to provide functionality to the {@link Glob} 66247 * methods. 66248 * 66249 * @module 66250 */ 66251 const minipass_1 = __nccwpck_require__(4968); 66252 const ignore_js_1 = __nccwpck_require__(750); 66253 const processor_js_1 = __nccwpck_require__(2813); 66254 const makeIgnore = (ignore, opts) => typeof ignore === 'string' 66255 ? new ignore_js_1.Ignore([ignore], opts) 66256 : Array.isArray(ignore) 66257 ? new ignore_js_1.Ignore(ignore, opts) 66258 : ignore; 66259 /** 66260 * basic walking utilities that all the glob walker types use 66261 */ 66262 class GlobUtil { 66263 path; 66264 patterns; 66265 opts; 66266 seen = new Set(); 66267 paused = false; 66268 aborted = false; 66269 #onResume = []; 66270 #ignore; 66271 #sep; 66272 signal; 66273 maxDepth; 66274 constructor(patterns, path, opts) { 66275 this.patterns = patterns; 66276 this.path = path; 66277 this.opts = opts; 66278 this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; 66279 if (opts.ignore) { 66280 this.#ignore = makeIgnore(opts.ignore, opts); 66281 } 66282 // ignore, always set with maxDepth, but it's optional on the 66283 // GlobOptions type 66284 /* c8 ignore start */ 66285 this.maxDepth = opts.maxDepth || Infinity; 66286 /* c8 ignore stop */ 66287 if (opts.signal) { 66288 this.signal = opts.signal; 66289 this.signal.addEventListener('abort', () => { 66290 this.#onResume.length = 0; 66291 }); 66292 } 66293 } 66294 #ignored(path) { 66295 return this.seen.has(path) || !!this.#ignore?.ignored?.(path); 66296 } 66297 #childrenIgnored(path) { 66298 return !!this.#ignore?.childrenIgnored?.(path); 66299 } 66300 // backpressure mechanism 66301 pause() { 66302 this.paused = true; 66303 } 66304 resume() { 66305 /* c8 ignore start */ 66306 if (this.signal?.aborted) 66307 return; 66308 /* c8 ignore stop */ 66309 this.paused = false; 66310 let fn = undefined; 66311 while (!this.paused && (fn = this.#onResume.shift())) { 66312 fn(); 66313 } 66314 } 66315 onResume(fn) { 66316 if (this.signal?.aborted) 66317 return; 66318 /* c8 ignore start */ 66319 if (!this.paused) { 66320 fn(); 66321 } 66322 else { 66323 /* c8 ignore stop */ 66324 this.#onResume.push(fn); 66325 } 66326 } 66327 // do the requisite realpath/stat checking, and return the path 66328 // to add or undefined to filter it out. 66329 async matchCheck(e, ifDir) { 66330 if (ifDir && this.opts.nodir) 66331 return undefined; 66332 let rpc; 66333 if (this.opts.realpath) { 66334 rpc = e.realpathCached() || (await e.realpath()); 66335 if (!rpc) 66336 return undefined; 66337 e = rpc; 66338 } 66339 const needStat = e.isUnknown() || this.opts.stat; 66340 return this.matchCheckTest(needStat ? await e.lstat() : e, ifDir); 66341 } 66342 matchCheckTest(e, ifDir) { 66343 return e && 66344 (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && 66345 (!ifDir || e.canReaddir()) && 66346 (!this.opts.nodir || !e.isDirectory()) && 66347 !this.#ignored(e) 66348 ? e 66349 : undefined; 66350 } 66351 matchCheckSync(e, ifDir) { 66352 if (ifDir && this.opts.nodir) 66353 return undefined; 66354 let rpc; 66355 if (this.opts.realpath) { 66356 rpc = e.realpathCached() || e.realpathSync(); 66357 if (!rpc) 66358 return undefined; 66359 e = rpc; 66360 } 66361 const needStat = e.isUnknown() || this.opts.stat; 66362 return this.matchCheckTest(needStat ? e.lstatSync() : e, ifDir); 66363 } 66364 matchFinish(e, absolute) { 66365 if (this.#ignored(e)) 66366 return; 66367 const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; 66368 this.seen.add(e); 66369 const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; 66370 // ok, we have what we need! 66371 if (this.opts.withFileTypes) { 66372 this.matchEmit(e); 66373 } 66374 else if (abs) { 66375 const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); 66376 this.matchEmit(abs + mark); 66377 } 66378 else { 66379 const rel = this.opts.posix ? e.relativePosix() : e.relative(); 66380 const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) 66381 ? '.' + this.#sep 66382 : ''; 66383 this.matchEmit(!rel ? '.' + mark : pre + rel + mark); 66384 } 66385 } 66386 async match(e, absolute, ifDir) { 66387 const p = await this.matchCheck(e, ifDir); 66388 if (p) 66389 this.matchFinish(p, absolute); 66390 } 66391 matchSync(e, absolute, ifDir) { 66392 const p = this.matchCheckSync(e, ifDir); 66393 if (p) 66394 this.matchFinish(p, absolute); 66395 } 66396 walkCB(target, patterns, cb) { 66397 /* c8 ignore start */ 66398 if (this.signal?.aborted) 66399 cb(); 66400 /* c8 ignore stop */ 66401 this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb); 66402 } 66403 walkCB2(target, patterns, processor, cb) { 66404 if (this.#childrenIgnored(target)) 66405 return cb(); 66406 if (this.signal?.aborted) 66407 cb(); 66408 if (this.paused) { 66409 this.onResume(() => this.walkCB2(target, patterns, processor, cb)); 66410 return; 66411 } 66412 processor.processPatterns(target, patterns); 66413 // done processing. all of the above is sync, can be abstracted out. 66414 // subwalks is a map of paths to the entry filters they need 66415 // matches is a map of paths to [absolute, ifDir] tuples. 66416 let tasks = 1; 66417 const next = () => { 66418 if (--tasks === 0) 66419 cb(); 66420 }; 66421 for (const [m, absolute, ifDir] of processor.matches.entries()) { 66422 if (this.#ignored(m)) 66423 continue; 66424 tasks++; 66425 this.match(m, absolute, ifDir).then(() => next()); 66426 } 66427 for (const t of processor.subwalkTargets()) { 66428 if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { 66429 continue; 66430 } 66431 tasks++; 66432 const childrenCached = t.readdirCached(); 66433 if (t.calledReaddir()) 66434 this.walkCB3(t, childrenCached, processor, next); 66435 else { 66436 t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); 66437 } 66438 } 66439 next(); 66440 } 66441 walkCB3(target, entries, processor, cb) { 66442 processor = processor.filterEntries(target, entries); 66443 let tasks = 1; 66444 const next = () => { 66445 if (--tasks === 0) 66446 cb(); 66447 }; 66448 for (const [m, absolute, ifDir] of processor.matches.entries()) { 66449 if (this.#ignored(m)) 66450 continue; 66451 tasks++; 66452 this.match(m, absolute, ifDir).then(() => next()); 66453 } 66454 for (const [target, patterns] of processor.subwalks.entries()) { 66455 tasks++; 66456 this.walkCB2(target, patterns, processor.child(), next); 66457 } 66458 next(); 66459 } 66460 walkCBSync(target, patterns, cb) { 66461 /* c8 ignore start */ 66462 if (this.signal?.aborted) 66463 cb(); 66464 /* c8 ignore stop */ 66465 this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb); 66466 } 66467 walkCB2Sync(target, patterns, processor, cb) { 66468 if (this.#childrenIgnored(target)) 66469 return cb(); 66470 if (this.signal?.aborted) 66471 cb(); 66472 if (this.paused) { 66473 this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); 66474 return; 66475 } 66476 processor.processPatterns(target, patterns); 66477 // done processing. all of the above is sync, can be abstracted out. 66478 // subwalks is a map of paths to the entry filters they need 66479 // matches is a map of paths to [absolute, ifDir] tuples. 66480 let tasks = 1; 66481 const next = () => { 66482 if (--tasks === 0) 66483 cb(); 66484 }; 66485 for (const [m, absolute, ifDir] of processor.matches.entries()) { 66486 if (this.#ignored(m)) 66487 continue; 66488 this.matchSync(m, absolute, ifDir); 66489 } 66490 for (const t of processor.subwalkTargets()) { 66491 if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { 66492 continue; 66493 } 66494 tasks++; 66495 const children = t.readdirSync(); 66496 this.walkCB3Sync(t, children, processor, next); 66497 } 66498 next(); 66499 } 66500 walkCB3Sync(target, entries, processor, cb) { 66501 processor = processor.filterEntries(target, entries); 66502 let tasks = 1; 66503 const next = () => { 66504 if (--tasks === 0) 66505 cb(); 66506 }; 66507 for (const [m, absolute, ifDir] of processor.matches.entries()) { 66508 if (this.#ignored(m)) 66509 continue; 66510 this.matchSync(m, absolute, ifDir); 66511 } 66512 for (const [target, patterns] of processor.subwalks.entries()) { 66513 tasks++; 66514 this.walkCB2Sync(target, patterns, processor.child(), next); 66515 } 66516 next(); 66517 } 66518 } 66519 exports.GlobUtil = GlobUtil; 66520 class GlobWalker extends GlobUtil { 66521 matches; 66522 constructor(patterns, path, opts) { 66523 super(patterns, path, opts); 66524 this.matches = new Set(); 66525 } 66526 matchEmit(e) { 66527 this.matches.add(e); 66528 } 66529 async walk() { 66530 if (this.signal?.aborted) 66531 throw this.signal.reason; 66532 if (this.path.isUnknown()) { 66533 await this.path.lstat(); 66534 } 66535 await new Promise((res, rej) => { 66536 this.walkCB(this.path, this.patterns, () => { 66537 if (this.signal?.aborted) { 66538 rej(this.signal.reason); 66539 } 66540 else { 66541 res(this.matches); 66542 } 66543 }); 66544 }); 66545 return this.matches; 66546 } 66547 walkSync() { 66548 if (this.signal?.aborted) 66549 throw this.signal.reason; 66550 if (this.path.isUnknown()) { 66551 this.path.lstatSync(); 66552 } 66553 // nothing for the callback to do, because this never pauses 66554 this.walkCBSync(this.path, this.patterns, () => { 66555 if (this.signal?.aborted) 66556 throw this.signal.reason; 66557 }); 66558 return this.matches; 66559 } 66560 } 66561 exports.GlobWalker = GlobWalker; 66562 class GlobStream extends GlobUtil { 66563 results; 66564 constructor(patterns, path, opts) { 66565 super(patterns, path, opts); 66566 this.results = new minipass_1.Minipass({ 66567 signal: this.signal, 66568 objectMode: true, 66569 }); 66570 this.results.on('drain', () => this.resume()); 66571 this.results.on('resume', () => this.resume()); 66572 } 66573 matchEmit(e) { 66574 this.results.write(e); 66575 if (!this.results.flowing) 66576 this.pause(); 66577 } 66578 stream() { 66579 const target = this.path; 66580 if (target.isUnknown()) { 66581 target.lstat().then(() => { 66582 this.walkCB(target, this.patterns, () => this.results.end()); 66583 }); 66584 } 66585 else { 66586 this.walkCB(target, this.patterns, () => this.results.end()); 66587 } 66588 return this.results; 66589 } 66590 streamSync() { 66591 if (this.path.isUnknown()) { 66592 this.path.lstatSync(); 66593 } 66594 this.walkCBSync(this.path, this.patterns, () => this.results.end()); 66595 return this.results; 66596 } 66597 } 66598 exports.GlobStream = GlobStream; 66599 //# sourceMappingURL=walker.js.map 66600 66601 /***/ }), 66602 66603 /***/ 6874: 66604 /***/ ((__unused_webpack_module, exports) => { 66605 66606 "use strict"; 66607 66608 /** 66609 * @module LRUCache 66610 */ 66611 Object.defineProperty(exports, "__esModule", ({ value: true })); 66612 exports.LRUCache = void 0; 66613 const perf = typeof performance === 'object' && 66614 performance && 66615 typeof performance.now === 'function' 66616 ? performance 66617 : Date; 66618 const warned = new Set(); 66619 /* c8 ignore start */ 66620 const PROCESS = (typeof process === 'object' && !!process ? process : {}); 66621 /* c8 ignore start */ 66622 const emitWarning = (msg, type, code, fn) => { 66623 typeof PROCESS.emitWarning === 'function' 66624 ? PROCESS.emitWarning(msg, type, code, fn) 66625 : console.error(`[${code}] ${type}: ${msg}`); 66626 }; 66627 let AC = globalThis.AbortController; 66628 let AS = globalThis.AbortSignal; 66629 /* c8 ignore start */ 66630 if (typeof AC === 'undefined') { 66631 //@ts-ignore 66632 AS = class AbortSignal { 66633 onabort; 66634 _onabort = []; 66635 reason; 66636 aborted = false; 66637 addEventListener(_, fn) { 66638 this._onabort.push(fn); 66639 } 66640 }; 66641 //@ts-ignore 66642 AC = class AbortController { 66643 constructor() { 66644 warnACPolyfill(); 66645 } 66646 signal = new AS(); 66647 abort(reason) { 66648 if (this.signal.aborted) 66649 return; 66650 //@ts-ignore 66651 this.signal.reason = reason; 66652 //@ts-ignore 66653 this.signal.aborted = true; 66654 //@ts-ignore 66655 for (const fn of this.signal._onabort) { 66656 fn(reason); 66657 } 66658 this.signal.onabort?.(reason); 66659 } 66660 }; 66661 let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; 66662 const warnACPolyfill = () => { 66663 if (!printACPolyfillWarning) 66664 return; 66665 printACPolyfillWarning = false; 66666 emitWarning('AbortController is not defined. If using lru-cache in ' + 66667 'node 14, load an AbortController polyfill from the ' + 66668 '`node-abort-controller` package. A minimal polyfill is ' + 66669 'provided for use by LRUCache.fetch(), but it should not be ' + 66670 'relied upon in other contexts (eg, passing it to other APIs that ' + 66671 'use AbortController/AbortSignal might have undesirable effects). ' + 66672 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); 66673 }; 66674 } 66675 /* c8 ignore stop */ 66676 const shouldWarn = (code) => !warned.has(code); 66677 const TYPE = Symbol('type'); 66678 const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); 66679 /* c8 ignore start */ 66680 // This is a little bit ridiculous, tbh. 66681 // The maximum array length is 2^32-1 or thereabouts on most JS impls. 66682 // And well before that point, you're caching the entire world, I mean, 66683 // that's ~32GB of just integers for the next/prev links, plus whatever 66684 // else to hold that many keys and values. Just filling the memory with 66685 // zeroes at init time is brutal when you get that big. 66686 // But why not be complete? 66687 // Maybe in the future, these limits will have expanded. 66688 const getUintArray = (max) => !isPosInt(max) 66689 ? null 66690 : max <= Math.pow(2, 8) 66691 ? Uint8Array 66692 : max <= Math.pow(2, 16) 66693 ? Uint16Array 66694 : max <= Math.pow(2, 32) 66695 ? Uint32Array 66696 : max <= Number.MAX_SAFE_INTEGER 66697 ? ZeroArray 66698 : null; 66699 /* c8 ignore stop */ 66700 class ZeroArray extends Array { 66701 constructor(size) { 66702 super(size); 66703 this.fill(0); 66704 } 66705 } 66706 class Stack { 66707 heap; 66708 length; 66709 // private constructor 66710 static #constructing = false; 66711 static create(max) { 66712 const HeapCls = getUintArray(max); 66713 if (!HeapCls) 66714 return []; 66715 Stack.#constructing = true; 66716 const s = new Stack(max, HeapCls); 66717 Stack.#constructing = false; 66718 return s; 66719 } 66720 constructor(max, HeapCls) { 66721 /* c8 ignore start */ 66722 if (!Stack.#constructing) { 66723 throw new TypeError('instantiate Stack using Stack.create(n)'); 66724 } 66725 /* c8 ignore stop */ 66726 this.heap = new HeapCls(max); 66727 this.length = 0; 66728 } 66729 push(n) { 66730 this.heap[this.length++] = n; 66731 } 66732 pop() { 66733 return this.heap[--this.length]; 66734 } 66735 } 66736 /** 66737 * Default export, the thing you're using this module to get. 66738 * 66739 * All properties from the options object (with the exception of 66740 * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as 66741 * normal public members. (`max` and `maxBase` are read-only getters.) 66742 * Changing any of these will alter the defaults for subsequent method calls, 66743 * but is otherwise safe. 66744 */ 66745 class LRUCache { 66746 // properties coming in from the options of these, only max and maxSize 66747 // really *need* to be protected. The rest can be modified, as they just 66748 // set defaults for various methods. 66749 #max; 66750 #maxSize; 66751 #dispose; 66752 #disposeAfter; 66753 #fetchMethod; 66754 /** 66755 * {@link LRUCache.OptionsBase.ttl} 66756 */ 66757 ttl; 66758 /** 66759 * {@link LRUCache.OptionsBase.ttlResolution} 66760 */ 66761 ttlResolution; 66762 /** 66763 * {@link LRUCache.OptionsBase.ttlAutopurge} 66764 */ 66765 ttlAutopurge; 66766 /** 66767 * {@link LRUCache.OptionsBase.updateAgeOnGet} 66768 */ 66769 updateAgeOnGet; 66770 /** 66771 * {@link LRUCache.OptionsBase.updateAgeOnHas} 66772 */ 66773 updateAgeOnHas; 66774 /** 66775 * {@link LRUCache.OptionsBase.allowStale} 66776 */ 66777 allowStale; 66778 /** 66779 * {@link LRUCache.OptionsBase.noDisposeOnSet} 66780 */ 66781 noDisposeOnSet; 66782 /** 66783 * {@link LRUCache.OptionsBase.noUpdateTTL} 66784 */ 66785 noUpdateTTL; 66786 /** 66787 * {@link LRUCache.OptionsBase.maxEntrySize} 66788 */ 66789 maxEntrySize; 66790 /** 66791 * {@link LRUCache.OptionsBase.sizeCalculation} 66792 */ 66793 sizeCalculation; 66794 /** 66795 * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} 66796 */ 66797 noDeleteOnFetchRejection; 66798 /** 66799 * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} 66800 */ 66801 noDeleteOnStaleGet; 66802 /** 66803 * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} 66804 */ 66805 allowStaleOnFetchAbort; 66806 /** 66807 * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} 66808 */ 66809 allowStaleOnFetchRejection; 66810 /** 66811 * {@link LRUCache.OptionsBase.ignoreFetchAbort} 66812 */ 66813 ignoreFetchAbort; 66814 // computed properties 66815 #size; 66816 #calculatedSize; 66817 #keyMap; 66818 #keyList; 66819 #valList; 66820 #next; 66821 #prev; 66822 #head; 66823 #tail; 66824 #free; 66825 #disposed; 66826 #sizes; 66827 #starts; 66828 #ttls; 66829 #hasDispose; 66830 #hasFetchMethod; 66831 #hasDisposeAfter; 66832 /** 66833 * Do not call this method unless you need to inspect the 66834 * inner workings of the cache. If anything returned by this 66835 * object is modified in any way, strange breakage may occur. 66836 * 66837 * These fields are private for a reason! 66838 * 66839 * @internal 66840 */ 66841 static unsafeExposeInternals(c) { 66842 return { 66843 // properties 66844 starts: c.#starts, 66845 ttls: c.#ttls, 66846 sizes: c.#sizes, 66847 keyMap: c.#keyMap, 66848 keyList: c.#keyList, 66849 valList: c.#valList, 66850 next: c.#next, 66851 prev: c.#prev, 66852 get head() { 66853 return c.#head; 66854 }, 66855 get tail() { 66856 return c.#tail; 66857 }, 66858 free: c.#free, 66859 // methods 66860 isBackgroundFetch: (p) => c.#isBackgroundFetch(p), 66861 backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), 66862 moveToTail: (index) => c.#moveToTail(index), 66863 indexes: (options) => c.#indexes(options), 66864 rindexes: (options) => c.#rindexes(options), 66865 isStale: (index) => c.#isStale(index), 66866 }; 66867 } 66868 // Protected read-only members 66869 /** 66870 * {@link LRUCache.OptionsBase.max} (read-only) 66871 */ 66872 get max() { 66873 return this.#max; 66874 } 66875 /** 66876 * {@link LRUCache.OptionsBase.maxSize} (read-only) 66877 */ 66878 get maxSize() { 66879 return this.#maxSize; 66880 } 66881 /** 66882 * The total computed size of items in the cache (read-only) 66883 */ 66884 get calculatedSize() { 66885 return this.#calculatedSize; 66886 } 66887 /** 66888 * The number of items stored in the cache (read-only) 66889 */ 66890 get size() { 66891 return this.#size; 66892 } 66893 /** 66894 * {@link LRUCache.OptionsBase.fetchMethod} (read-only) 66895 */ 66896 get fetchMethod() { 66897 return this.#fetchMethod; 66898 } 66899 /** 66900 * {@link LRUCache.OptionsBase.dispose} (read-only) 66901 */ 66902 get dispose() { 66903 return this.#dispose; 66904 } 66905 /** 66906 * {@link LRUCache.OptionsBase.disposeAfter} (read-only) 66907 */ 66908 get disposeAfter() { 66909 return this.#disposeAfter; 66910 } 66911 constructor(options) { 66912 const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; 66913 if (max !== 0 && !isPosInt(max)) { 66914 throw new TypeError('max option must be a nonnegative integer'); 66915 } 66916 const UintArray = max ? getUintArray(max) : Array; 66917 if (!UintArray) { 66918 throw new Error('invalid max value: ' + max); 66919 } 66920 this.#max = max; 66921 this.#maxSize = maxSize; 66922 this.maxEntrySize = maxEntrySize || this.#maxSize; 66923 this.sizeCalculation = sizeCalculation; 66924 if (this.sizeCalculation) { 66925 if (!this.#maxSize && !this.maxEntrySize) { 66926 throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); 66927 } 66928 if (typeof this.sizeCalculation !== 'function') { 66929 throw new TypeError('sizeCalculation set to non-function'); 66930 } 66931 } 66932 if (fetchMethod !== undefined && 66933 typeof fetchMethod !== 'function') { 66934 throw new TypeError('fetchMethod must be a function if specified'); 66935 } 66936 this.#fetchMethod = fetchMethod; 66937 this.#hasFetchMethod = !!fetchMethod; 66938 this.#keyMap = new Map(); 66939 this.#keyList = new Array(max).fill(undefined); 66940 this.#valList = new Array(max).fill(undefined); 66941 this.#next = new UintArray(max); 66942 this.#prev = new UintArray(max); 66943 this.#head = 0; 66944 this.#tail = 0; 66945 this.#free = Stack.create(max); 66946 this.#size = 0; 66947 this.#calculatedSize = 0; 66948 if (typeof dispose === 'function') { 66949 this.#dispose = dispose; 66950 } 66951 if (typeof disposeAfter === 'function') { 66952 this.#disposeAfter = disposeAfter; 66953 this.#disposed = []; 66954 } 66955 else { 66956 this.#disposeAfter = undefined; 66957 this.#disposed = undefined; 66958 } 66959 this.#hasDispose = !!this.#dispose; 66960 this.#hasDisposeAfter = !!this.#disposeAfter; 66961 this.noDisposeOnSet = !!noDisposeOnSet; 66962 this.noUpdateTTL = !!noUpdateTTL; 66963 this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; 66964 this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; 66965 this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; 66966 this.ignoreFetchAbort = !!ignoreFetchAbort; 66967 // NB: maxEntrySize is set to maxSize if it's set 66968 if (this.maxEntrySize !== 0) { 66969 if (this.#maxSize !== 0) { 66970 if (!isPosInt(this.#maxSize)) { 66971 throw new TypeError('maxSize must be a positive integer if specified'); 66972 } 66973 } 66974 if (!isPosInt(this.maxEntrySize)) { 66975 throw new TypeError('maxEntrySize must be a positive integer if specified'); 66976 } 66977 this.#initializeSizeTracking(); 66978 } 66979 this.allowStale = !!allowStale; 66980 this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; 66981 this.updateAgeOnGet = !!updateAgeOnGet; 66982 this.updateAgeOnHas = !!updateAgeOnHas; 66983 this.ttlResolution = 66984 isPosInt(ttlResolution) || ttlResolution === 0 66985 ? ttlResolution 66986 : 1; 66987 this.ttlAutopurge = !!ttlAutopurge; 66988 this.ttl = ttl || 0; 66989 if (this.ttl) { 66990 if (!isPosInt(this.ttl)) { 66991 throw new TypeError('ttl must be a positive integer if specified'); 66992 } 66993 this.#initializeTTLTracking(); 66994 } 66995 // do not allow completely unbounded caches 66996 if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { 66997 throw new TypeError('At least one of max, maxSize, or ttl is required'); 66998 } 66999 if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { 67000 const code = 'LRU_CACHE_UNBOUNDED'; 67001 if (shouldWarn(code)) { 67002 warned.add(code); 67003 const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 67004 'result in unbounded memory consumption.'; 67005 emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); 67006 } 67007 } 67008 } 67009 /** 67010 * Return the remaining TTL time for a given entry key 67011 */ 67012 getRemainingTTL(key) { 67013 return this.#keyMap.has(key) ? Infinity : 0; 67014 } 67015 #initializeTTLTracking() { 67016 const ttls = new ZeroArray(this.#max); 67017 const starts = new ZeroArray(this.#max); 67018 this.#ttls = ttls; 67019 this.#starts = starts; 67020 this.#setItemTTL = (index, ttl, start = perf.now()) => { 67021 starts[index] = ttl !== 0 ? start : 0; 67022 ttls[index] = ttl; 67023 if (ttl !== 0 && this.ttlAutopurge) { 67024 const t = setTimeout(() => { 67025 if (this.#isStale(index)) { 67026 this.delete(this.#keyList[index]); 67027 } 67028 }, ttl + 1); 67029 // unref() not supported on all platforms 67030 /* c8 ignore start */ 67031 if (t.unref) { 67032 t.unref(); 67033 } 67034 /* c8 ignore stop */ 67035 } 67036 }; 67037 this.#updateItemAge = index => { 67038 starts[index] = ttls[index] !== 0 ? perf.now() : 0; 67039 }; 67040 this.#statusTTL = (status, index) => { 67041 if (ttls[index]) { 67042 const ttl = ttls[index]; 67043 const start = starts[index]; 67044 /* c8 ignore next */ 67045 if (!ttl || !start) 67046 return; 67047 status.ttl = ttl; 67048 status.start = start; 67049 status.now = cachedNow || getNow(); 67050 const age = status.now - start; 67051 status.remainingTTL = ttl - age; 67052 } 67053 }; 67054 // debounce calls to perf.now() to 1s so we're not hitting 67055 // that costly call repeatedly. 67056 let cachedNow = 0; 67057 const getNow = () => { 67058 const n = perf.now(); 67059 if (this.ttlResolution > 0) { 67060 cachedNow = n; 67061 const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); 67062 // not available on all platforms 67063 /* c8 ignore start */ 67064 if (t.unref) { 67065 t.unref(); 67066 } 67067 /* c8 ignore stop */ 67068 } 67069 return n; 67070 }; 67071 this.getRemainingTTL = key => { 67072 const index = this.#keyMap.get(key); 67073 if (index === undefined) { 67074 return 0; 67075 } 67076 const ttl = ttls[index]; 67077 const start = starts[index]; 67078 if (!ttl || !start) { 67079 return Infinity; 67080 } 67081 const age = (cachedNow || getNow()) - start; 67082 return ttl - age; 67083 }; 67084 this.#isStale = index => { 67085 const s = starts[index]; 67086 const t = ttls[index]; 67087 return !!t && !!s && (cachedNow || getNow()) - s > t; 67088 }; 67089 } 67090 // conditionally set private methods related to TTL 67091 #updateItemAge = () => { }; 67092 #statusTTL = () => { }; 67093 #setItemTTL = () => { }; 67094 /* c8 ignore stop */ 67095 #isStale = () => false; 67096 #initializeSizeTracking() { 67097 const sizes = new ZeroArray(this.#max); 67098 this.#calculatedSize = 0; 67099 this.#sizes = sizes; 67100 this.#removeItemSize = index => { 67101 this.#calculatedSize -= sizes[index]; 67102 sizes[index] = 0; 67103 }; 67104 this.#requireSize = (k, v, size, sizeCalculation) => { 67105 // provisionally accept background fetches. 67106 // actual value size will be checked when they return. 67107 if (this.#isBackgroundFetch(v)) { 67108 return 0; 67109 } 67110 if (!isPosInt(size)) { 67111 if (sizeCalculation) { 67112 if (typeof sizeCalculation !== 'function') { 67113 throw new TypeError('sizeCalculation must be a function'); 67114 } 67115 size = sizeCalculation(v, k); 67116 if (!isPosInt(size)) { 67117 throw new TypeError('sizeCalculation return invalid (expect positive integer)'); 67118 } 67119 } 67120 else { 67121 throw new TypeError('invalid size value (must be positive integer). ' + 67122 'When maxSize or maxEntrySize is used, sizeCalculation ' + 67123 'or size must be set.'); 67124 } 67125 } 67126 return size; 67127 }; 67128 this.#addItemSize = (index, size, status) => { 67129 sizes[index] = size; 67130 if (this.#maxSize) { 67131 const maxSize = this.#maxSize - sizes[index]; 67132 while (this.#calculatedSize > maxSize) { 67133 this.#evict(true); 67134 } 67135 } 67136 this.#calculatedSize += sizes[index]; 67137 if (status) { 67138 status.entrySize = size; 67139 status.totalCalculatedSize = this.#calculatedSize; 67140 } 67141 }; 67142 } 67143 #removeItemSize = _i => { }; 67144 #addItemSize = (_i, _s, _st) => { }; 67145 #requireSize = (_k, _v, size, sizeCalculation) => { 67146 if (size || sizeCalculation) { 67147 throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); 67148 } 67149 return 0; 67150 }; 67151 *#indexes({ allowStale = this.allowStale } = {}) { 67152 if (this.#size) { 67153 for (let i = this.#tail; true;) { 67154 if (!this.#isValidIndex(i)) { 67155 break; 67156 } 67157 if (allowStale || !this.#isStale(i)) { 67158 yield i; 67159 } 67160 if (i === this.#head) { 67161 break; 67162 } 67163 else { 67164 i = this.#prev[i]; 67165 } 67166 } 67167 } 67168 } 67169 *#rindexes({ allowStale = this.allowStale } = {}) { 67170 if (this.#size) { 67171 for (let i = this.#head; true;) { 67172 if (!this.#isValidIndex(i)) { 67173 break; 67174 } 67175 if (allowStale || !this.#isStale(i)) { 67176 yield i; 67177 } 67178 if (i === this.#tail) { 67179 break; 67180 } 67181 else { 67182 i = this.#next[i]; 67183 } 67184 } 67185 } 67186 } 67187 #isValidIndex(index) { 67188 return (index !== undefined && 67189 this.#keyMap.get(this.#keyList[index]) === index); 67190 } 67191 /** 67192 * Return a generator yielding `[key, value]` pairs, 67193 * in order from most recently used to least recently used. 67194 */ 67195 *entries() { 67196 for (const i of this.#indexes()) { 67197 if (this.#valList[i] !== undefined && 67198 this.#keyList[i] !== undefined && 67199 !this.#isBackgroundFetch(this.#valList[i])) { 67200 yield [this.#keyList[i], this.#valList[i]]; 67201 } 67202 } 67203 } 67204 /** 67205 * Inverse order version of {@link LRUCache.entries} 67206 * 67207 * Return a generator yielding `[key, value]` pairs, 67208 * in order from least recently used to most recently used. 67209 */ 67210 *rentries() { 67211 for (const i of this.#rindexes()) { 67212 if (this.#valList[i] !== undefined && 67213 this.#keyList[i] !== undefined && 67214 !this.#isBackgroundFetch(this.#valList[i])) { 67215 yield [this.#keyList[i], this.#valList[i]]; 67216 } 67217 } 67218 } 67219 /** 67220 * Return a generator yielding the keys in the cache, 67221 * in order from most recently used to least recently used. 67222 */ 67223 *keys() { 67224 for (const i of this.#indexes()) { 67225 const k = this.#keyList[i]; 67226 if (k !== undefined && 67227 !this.#isBackgroundFetch(this.#valList[i])) { 67228 yield k; 67229 } 67230 } 67231 } 67232 /** 67233 * Inverse order version of {@link LRUCache.keys} 67234 * 67235 * Return a generator yielding the keys in the cache, 67236 * in order from least recently used to most recently used. 67237 */ 67238 *rkeys() { 67239 for (const i of this.#rindexes()) { 67240 const k = this.#keyList[i]; 67241 if (k !== undefined && 67242 !this.#isBackgroundFetch(this.#valList[i])) { 67243 yield k; 67244 } 67245 } 67246 } 67247 /** 67248 * Return a generator yielding the values in the cache, 67249 * in order from most recently used to least recently used. 67250 */ 67251 *values() { 67252 for (const i of this.#indexes()) { 67253 const v = this.#valList[i]; 67254 if (v !== undefined && 67255 !this.#isBackgroundFetch(this.#valList[i])) { 67256 yield this.#valList[i]; 67257 } 67258 } 67259 } 67260 /** 67261 * Inverse order version of {@link LRUCache.values} 67262 * 67263 * Return a generator yielding the values in the cache, 67264 * in order from least recently used to most recently used. 67265 */ 67266 *rvalues() { 67267 for (const i of this.#rindexes()) { 67268 const v = this.#valList[i]; 67269 if (v !== undefined && 67270 !this.#isBackgroundFetch(this.#valList[i])) { 67271 yield this.#valList[i]; 67272 } 67273 } 67274 } 67275 /** 67276 * Iterating over the cache itself yields the same results as 67277 * {@link LRUCache.entries} 67278 */ 67279 [Symbol.iterator]() { 67280 return this.entries(); 67281 } 67282 /** 67283 * A String value that is used in the creation of the default string description of an object. 67284 * Called by the built-in method Object.prototype.toString. 67285 */ 67286 [Symbol.toStringTag] = 'LRUCache'; 67287 /** 67288 * Find a value for which the supplied fn method returns a truthy value, 67289 * similar to Array.find(). fn is called as fn(value, key, cache). 67290 */ 67291 find(fn, getOptions = {}) { 67292 for (const i of this.#indexes()) { 67293 const v = this.#valList[i]; 67294 const value = this.#isBackgroundFetch(v) 67295 ? v.__staleWhileFetching 67296 : v; 67297 if (value === undefined) 67298 continue; 67299 if (fn(value, this.#keyList[i], this)) { 67300 return this.get(this.#keyList[i], getOptions); 67301 } 67302 } 67303 } 67304 /** 67305 * Call the supplied function on each item in the cache, in order from 67306 * most recently used to least recently used. fn is called as 67307 * fn(value, key, cache). Does not update age or recenty of use. 67308 * Does not iterate over stale values. 67309 */ 67310 forEach(fn, thisp = this) { 67311 for (const i of this.#indexes()) { 67312 const v = this.#valList[i]; 67313 const value = this.#isBackgroundFetch(v) 67314 ? v.__staleWhileFetching 67315 : v; 67316 if (value === undefined) 67317 continue; 67318 fn.call(thisp, value, this.#keyList[i], this); 67319 } 67320 } 67321 /** 67322 * The same as {@link LRUCache.forEach} but items are iterated over in 67323 * reverse order. (ie, less recently used items are iterated over first.) 67324 */ 67325 rforEach(fn, thisp = this) { 67326 for (const i of this.#rindexes()) { 67327 const v = this.#valList[i]; 67328 const value = this.#isBackgroundFetch(v) 67329 ? v.__staleWhileFetching 67330 : v; 67331 if (value === undefined) 67332 continue; 67333 fn.call(thisp, value, this.#keyList[i], this); 67334 } 67335 } 67336 /** 67337 * Delete any stale entries. Returns true if anything was removed, 67338 * false otherwise. 67339 */ 67340 purgeStale() { 67341 let deleted = false; 67342 for (const i of this.#rindexes({ allowStale: true })) { 67343 if (this.#isStale(i)) { 67344 this.delete(this.#keyList[i]); 67345 deleted = true; 67346 } 67347 } 67348 return deleted; 67349 } 67350 /** 67351 * Get the extended info about a given entry, to get its value, size, and 67352 * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a 67353 * single key. Always returns stale values, if their info is found in the 67354 * cache, so be sure to check for expired TTLs if relevant. 67355 */ 67356 info(key) { 67357 const i = this.#keyMap.get(key); 67358 if (i === undefined) 67359 return undefined; 67360 const v = this.#valList[i]; 67361 const value = this.#isBackgroundFetch(v) 67362 ? v.__staleWhileFetching 67363 : v; 67364 if (value === undefined) 67365 return undefined; 67366 const entry = { value }; 67367 if (this.#ttls && this.#starts) { 67368 const ttl = this.#ttls[i]; 67369 const start = this.#starts[i]; 67370 if (ttl && start) { 67371 const remain = ttl - (perf.now() - start); 67372 entry.ttl = remain; 67373 entry.start = Date.now(); 67374 } 67375 } 67376 if (this.#sizes) { 67377 entry.size = this.#sizes[i]; 67378 } 67379 return entry; 67380 } 67381 /** 67382 * Return an array of [key, {@link LRUCache.Entry}] tuples which can be 67383 * passed to cache.load() 67384 */ 67385 dump() { 67386 const arr = []; 67387 for (const i of this.#indexes({ allowStale: true })) { 67388 const key = this.#keyList[i]; 67389 const v = this.#valList[i]; 67390 const value = this.#isBackgroundFetch(v) 67391 ? v.__staleWhileFetching 67392 : v; 67393 if (value === undefined || key === undefined) 67394 continue; 67395 const entry = { value }; 67396 if (this.#ttls && this.#starts) { 67397 entry.ttl = this.#ttls[i]; 67398 // always dump the start relative to a portable timestamp 67399 // it's ok for this to be a bit slow, it's a rare operation. 67400 const age = perf.now() - this.#starts[i]; 67401 entry.start = Math.floor(Date.now() - age); 67402 } 67403 if (this.#sizes) { 67404 entry.size = this.#sizes[i]; 67405 } 67406 arr.unshift([key, entry]); 67407 } 67408 return arr; 67409 } 67410 /** 67411 * Reset the cache and load in the items in entries in the order listed. 67412 * Note that the shape of the resulting cache may be different if the 67413 * same options are not used in both caches. 67414 */ 67415 load(arr) { 67416 this.clear(); 67417 for (const [key, entry] of arr) { 67418 if (entry.start) { 67419 // entry.start is a portable timestamp, but we may be using 67420 // node's performance.now(), so calculate the offset, so that 67421 // we get the intended remaining TTL, no matter how long it's 67422 // been on ice. 67423 // 67424 // it's ok for this to be a bit slow, it's a rare operation. 67425 const age = Date.now() - entry.start; 67426 entry.start = perf.now() - age; 67427 } 67428 this.set(key, entry.value, entry); 67429 } 67430 } 67431 /** 67432 * Add a value to the cache. 67433 * 67434 * Note: if `undefined` is specified as a value, this is an alias for 67435 * {@link LRUCache#delete} 67436 */ 67437 set(k, v, setOptions = {}) { 67438 if (v === undefined) { 67439 this.delete(k); 67440 return this; 67441 } 67442 const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; 67443 let { noUpdateTTL = this.noUpdateTTL } = setOptions; 67444 const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); 67445 // if the item doesn't fit, don't do anything 67446 // NB: maxEntrySize set to maxSize by default 67447 if (this.maxEntrySize && size > this.maxEntrySize) { 67448 if (status) { 67449 status.set = 'miss'; 67450 status.maxEntrySizeExceeded = true; 67451 } 67452 // have to delete, in case something is there already. 67453 this.delete(k); 67454 return this; 67455 } 67456 let index = this.#size === 0 ? undefined : this.#keyMap.get(k); 67457 if (index === undefined) { 67458 // addition 67459 index = (this.#size === 0 67460 ? this.#tail 67461 : this.#free.length !== 0 67462 ? this.#free.pop() 67463 : this.#size === this.#max 67464 ? this.#evict(false) 67465 : this.#size); 67466 this.#keyList[index] = k; 67467 this.#valList[index] = v; 67468 this.#keyMap.set(k, index); 67469 this.#next[this.#tail] = index; 67470 this.#prev[index] = this.#tail; 67471 this.#tail = index; 67472 this.#size++; 67473 this.#addItemSize(index, size, status); 67474 if (status) 67475 status.set = 'add'; 67476 noUpdateTTL = false; 67477 } 67478 else { 67479 // update 67480 this.#moveToTail(index); 67481 const oldVal = this.#valList[index]; 67482 if (v !== oldVal) { 67483 if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { 67484 oldVal.__abortController.abort(new Error('replaced')); 67485 const { __staleWhileFetching: s } = oldVal; 67486 if (s !== undefined && !noDisposeOnSet) { 67487 if (this.#hasDispose) { 67488 this.#dispose?.(s, k, 'set'); 67489 } 67490 if (this.#hasDisposeAfter) { 67491 this.#disposed?.push([s, k, 'set']); 67492 } 67493 } 67494 } 67495 else if (!noDisposeOnSet) { 67496 if (this.#hasDispose) { 67497 this.#dispose?.(oldVal, k, 'set'); 67498 } 67499 if (this.#hasDisposeAfter) { 67500 this.#disposed?.push([oldVal, k, 'set']); 67501 } 67502 } 67503 this.#removeItemSize(index); 67504 this.#addItemSize(index, size, status); 67505 this.#valList[index] = v; 67506 if (status) { 67507 status.set = 'replace'; 67508 const oldValue = oldVal && this.#isBackgroundFetch(oldVal) 67509 ? oldVal.__staleWhileFetching 67510 : oldVal; 67511 if (oldValue !== undefined) 67512 status.oldValue = oldValue; 67513 } 67514 } 67515 else if (status) { 67516 status.set = 'update'; 67517 } 67518 } 67519 if (ttl !== 0 && !this.#ttls) { 67520 this.#initializeTTLTracking(); 67521 } 67522 if (this.#ttls) { 67523 if (!noUpdateTTL) { 67524 this.#setItemTTL(index, ttl, start); 67525 } 67526 if (status) 67527 this.#statusTTL(status, index); 67528 } 67529 if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { 67530 const dt = this.#disposed; 67531 let task; 67532 while ((task = dt?.shift())) { 67533 this.#disposeAfter?.(...task); 67534 } 67535 } 67536 return this; 67537 } 67538 /** 67539 * Evict the least recently used item, returning its value or 67540 * `undefined` if cache is empty. 67541 */ 67542 pop() { 67543 try { 67544 while (this.#size) { 67545 const val = this.#valList[this.#head]; 67546 this.#evict(true); 67547 if (this.#isBackgroundFetch(val)) { 67548 if (val.__staleWhileFetching) { 67549 return val.__staleWhileFetching; 67550 } 67551 } 67552 else if (val !== undefined) { 67553 return val; 67554 } 67555 } 67556 } 67557 finally { 67558 if (this.#hasDisposeAfter && this.#disposed) { 67559 const dt = this.#disposed; 67560 let task; 67561 while ((task = dt?.shift())) { 67562 this.#disposeAfter?.(...task); 67563 } 67564 } 67565 } 67566 } 67567 #evict(free) { 67568 const head = this.#head; 67569 const k = this.#keyList[head]; 67570 const v = this.#valList[head]; 67571 if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { 67572 v.__abortController.abort(new Error('evicted')); 67573 } 67574 else if (this.#hasDispose || this.#hasDisposeAfter) { 67575 if (this.#hasDispose) { 67576 this.#dispose?.(v, k, 'evict'); 67577 } 67578 if (this.#hasDisposeAfter) { 67579 this.#disposed?.push([v, k, 'evict']); 67580 } 67581 } 67582 this.#removeItemSize(head); 67583 // if we aren't about to use the index, then null these out 67584 if (free) { 67585 this.#keyList[head] = undefined; 67586 this.#valList[head] = undefined; 67587 this.#free.push(head); 67588 } 67589 if (this.#size === 1) { 67590 this.#head = this.#tail = 0; 67591 this.#free.length = 0; 67592 } 67593 else { 67594 this.#head = this.#next[head]; 67595 } 67596 this.#keyMap.delete(k); 67597 this.#size--; 67598 return head; 67599 } 67600 /** 67601 * Check if a key is in the cache, without updating the recency of use. 67602 * Will return false if the item is stale, even though it is technically 67603 * in the cache. 67604 * 67605 * Will not update item age unless 67606 * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. 67607 */ 67608 has(k, hasOptions = {}) { 67609 const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; 67610 const index = this.#keyMap.get(k); 67611 if (index !== undefined) { 67612 const v = this.#valList[index]; 67613 if (this.#isBackgroundFetch(v) && 67614 v.__staleWhileFetching === undefined) { 67615 return false; 67616 } 67617 if (!this.#isStale(index)) { 67618 if (updateAgeOnHas) { 67619 this.#updateItemAge(index); 67620 } 67621 if (status) { 67622 status.has = 'hit'; 67623 this.#statusTTL(status, index); 67624 } 67625 return true; 67626 } 67627 else if (status) { 67628 status.has = 'stale'; 67629 this.#statusTTL(status, index); 67630 } 67631 } 67632 else if (status) { 67633 status.has = 'miss'; 67634 } 67635 return false; 67636 } 67637 /** 67638 * Like {@link LRUCache#get} but doesn't update recency or delete stale 67639 * items. 67640 * 67641 * Returns `undefined` if the item is stale, unless 67642 * {@link LRUCache.OptionsBase.allowStale} is set. 67643 */ 67644 peek(k, peekOptions = {}) { 67645 const { allowStale = this.allowStale } = peekOptions; 67646 const index = this.#keyMap.get(k); 67647 if (index === undefined || 67648 (!allowStale && this.#isStale(index))) { 67649 return; 67650 } 67651 const v = this.#valList[index]; 67652 // either stale and allowed, or forcing a refresh of non-stale value 67653 return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; 67654 } 67655 #backgroundFetch(k, index, options, context) { 67656 const v = index === undefined ? undefined : this.#valList[index]; 67657 if (this.#isBackgroundFetch(v)) { 67658 return v; 67659 } 67660 const ac = new AC(); 67661 const { signal } = options; 67662 // when/if our AC signals, then stop listening to theirs. 67663 signal?.addEventListener('abort', () => ac.abort(signal.reason), { 67664 signal: ac.signal, 67665 }); 67666 const fetchOpts = { 67667 signal: ac.signal, 67668 options, 67669 context, 67670 }; 67671 const cb = (v, updateCache = false) => { 67672 const { aborted } = ac.signal; 67673 const ignoreAbort = options.ignoreFetchAbort && v !== undefined; 67674 if (options.status) { 67675 if (aborted && !updateCache) { 67676 options.status.fetchAborted = true; 67677 options.status.fetchError = ac.signal.reason; 67678 if (ignoreAbort) 67679 options.status.fetchAbortIgnored = true; 67680 } 67681 else { 67682 options.status.fetchResolved = true; 67683 } 67684 } 67685 if (aborted && !ignoreAbort && !updateCache) { 67686 return fetchFail(ac.signal.reason); 67687 } 67688 // either we didn't abort, and are still here, or we did, and ignored 67689 const bf = p; 67690 if (this.#valList[index] === p) { 67691 if (v === undefined) { 67692 if (bf.__staleWhileFetching) { 67693 this.#valList[index] = bf.__staleWhileFetching; 67694 } 67695 else { 67696 this.delete(k); 67697 } 67698 } 67699 else { 67700 if (options.status) 67701 options.status.fetchUpdated = true; 67702 this.set(k, v, fetchOpts.options); 67703 } 67704 } 67705 return v; 67706 }; 67707 const eb = (er) => { 67708 if (options.status) { 67709 options.status.fetchRejected = true; 67710 options.status.fetchError = er; 67711 } 67712 return fetchFail(er); 67713 }; 67714 const fetchFail = (er) => { 67715 const { aborted } = ac.signal; 67716 const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; 67717 const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; 67718 const noDelete = allowStale || options.noDeleteOnFetchRejection; 67719 const bf = p; 67720 if (this.#valList[index] === p) { 67721 // if we allow stale on fetch rejections, then we need to ensure that 67722 // the stale value is not removed from the cache when the fetch fails. 67723 const del = !noDelete || bf.__staleWhileFetching === undefined; 67724 if (del) { 67725 this.delete(k); 67726 } 67727 else if (!allowStaleAborted) { 67728 // still replace the *promise* with the stale value, 67729 // since we are done with the promise at this point. 67730 // leave it untouched if we're still waiting for an 67731 // aborted background fetch that hasn't yet returned. 67732 this.#valList[index] = bf.__staleWhileFetching; 67733 } 67734 } 67735 if (allowStale) { 67736 if (options.status && bf.__staleWhileFetching !== undefined) { 67737 options.status.returnedStale = true; 67738 } 67739 return bf.__staleWhileFetching; 67740 } 67741 else if (bf.__returned === bf) { 67742 throw er; 67743 } 67744 }; 67745 const pcall = (res, rej) => { 67746 const fmp = this.#fetchMethod?.(k, v, fetchOpts); 67747 if (fmp && fmp instanceof Promise) { 67748 fmp.then(v => res(v === undefined ? undefined : v), rej); 67749 } 67750 // ignored, we go until we finish, regardless. 67751 // defer check until we are actually aborting, 67752 // so fetchMethod can override. 67753 ac.signal.addEventListener('abort', () => { 67754 if (!options.ignoreFetchAbort || 67755 options.allowStaleOnFetchAbort) { 67756 res(undefined); 67757 // when it eventually resolves, update the cache. 67758 if (options.allowStaleOnFetchAbort) { 67759 res = v => cb(v, true); 67760 } 67761 } 67762 }); 67763 }; 67764 if (options.status) 67765 options.status.fetchDispatched = true; 67766 const p = new Promise(pcall).then(cb, eb); 67767 const bf = Object.assign(p, { 67768 __abortController: ac, 67769 __staleWhileFetching: v, 67770 __returned: undefined, 67771 }); 67772 if (index === undefined) { 67773 // internal, don't expose status. 67774 this.set(k, bf, { ...fetchOpts.options, status: undefined }); 67775 index = this.#keyMap.get(k); 67776 } 67777 else { 67778 this.#valList[index] = bf; 67779 } 67780 return bf; 67781 } 67782 #isBackgroundFetch(p) { 67783 if (!this.#hasFetchMethod) 67784 return false; 67785 const b = p; 67786 return (!!b && 67787 b instanceof Promise && 67788 b.hasOwnProperty('__staleWhileFetching') && 67789 b.__abortController instanceof AC); 67790 } 67791 async fetch(k, fetchOptions = {}) { 67792 const { 67793 // get options 67794 allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, 67795 // set options 67796 ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, 67797 // fetch exclusive options 67798 noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; 67799 if (!this.#hasFetchMethod) { 67800 if (status) 67801 status.fetch = 'get'; 67802 return this.get(k, { 67803 allowStale, 67804 updateAgeOnGet, 67805 noDeleteOnStaleGet, 67806 status, 67807 }); 67808 } 67809 const options = { 67810 allowStale, 67811 updateAgeOnGet, 67812 noDeleteOnStaleGet, 67813 ttl, 67814 noDisposeOnSet, 67815 size, 67816 sizeCalculation, 67817 noUpdateTTL, 67818 noDeleteOnFetchRejection, 67819 allowStaleOnFetchRejection, 67820 allowStaleOnFetchAbort, 67821 ignoreFetchAbort, 67822 status, 67823 signal, 67824 }; 67825 let index = this.#keyMap.get(k); 67826 if (index === undefined) { 67827 if (status) 67828 status.fetch = 'miss'; 67829 const p = this.#backgroundFetch(k, index, options, context); 67830 return (p.__returned = p); 67831 } 67832 else { 67833 // in cache, maybe already fetching 67834 const v = this.#valList[index]; 67835 if (this.#isBackgroundFetch(v)) { 67836 const stale = allowStale && v.__staleWhileFetching !== undefined; 67837 if (status) { 67838 status.fetch = 'inflight'; 67839 if (stale) 67840 status.returnedStale = true; 67841 } 67842 return stale ? v.__staleWhileFetching : (v.__returned = v); 67843 } 67844 // if we force a refresh, that means do NOT serve the cached value, 67845 // unless we are already in the process of refreshing the cache. 67846 const isStale = this.#isStale(index); 67847 if (!forceRefresh && !isStale) { 67848 if (status) 67849 status.fetch = 'hit'; 67850 this.#moveToTail(index); 67851 if (updateAgeOnGet) { 67852 this.#updateItemAge(index); 67853 } 67854 if (status) 67855 this.#statusTTL(status, index); 67856 return v; 67857 } 67858 // ok, it is stale or a forced refresh, and not already fetching. 67859 // refresh the cache. 67860 const p = this.#backgroundFetch(k, index, options, context); 67861 const hasStale = p.__staleWhileFetching !== undefined; 67862 const staleVal = hasStale && allowStale; 67863 if (status) { 67864 status.fetch = isStale ? 'stale' : 'refresh'; 67865 if (staleVal && isStale) 67866 status.returnedStale = true; 67867 } 67868 return staleVal ? p.__staleWhileFetching : (p.__returned = p); 67869 } 67870 } 67871 /** 67872 * Return a value from the cache. Will update the recency of the cache 67873 * entry found. 67874 * 67875 * If the key is not found, get() will return `undefined`. 67876 */ 67877 get(k, getOptions = {}) { 67878 const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; 67879 const index = this.#keyMap.get(k); 67880 if (index !== undefined) { 67881 const value = this.#valList[index]; 67882 const fetching = this.#isBackgroundFetch(value); 67883 if (status) 67884 this.#statusTTL(status, index); 67885 if (this.#isStale(index)) { 67886 if (status) 67887 status.get = 'stale'; 67888 // delete only if not an in-flight background fetch 67889 if (!fetching) { 67890 if (!noDeleteOnStaleGet) { 67891 this.delete(k); 67892 } 67893 if (status && allowStale) 67894 status.returnedStale = true; 67895 return allowStale ? value : undefined; 67896 } 67897 else { 67898 if (status && 67899 allowStale && 67900 value.__staleWhileFetching !== undefined) { 67901 status.returnedStale = true; 67902 } 67903 return allowStale ? value.__staleWhileFetching : undefined; 67904 } 67905 } 67906 else { 67907 if (status) 67908 status.get = 'hit'; 67909 // if we're currently fetching it, we don't actually have it yet 67910 // it's not stale, which means this isn't a staleWhileRefetching. 67911 // If it's not stale, and fetching, AND has a __staleWhileFetching 67912 // value, then that means the user fetched with {forceRefresh:true}, 67913 // so it's safe to return that value. 67914 if (fetching) { 67915 return value.__staleWhileFetching; 67916 } 67917 this.#moveToTail(index); 67918 if (updateAgeOnGet) { 67919 this.#updateItemAge(index); 67920 } 67921 return value; 67922 } 67923 } 67924 else if (status) { 67925 status.get = 'miss'; 67926 } 67927 } 67928 #connect(p, n) { 67929 this.#prev[n] = p; 67930 this.#next[p] = n; 67931 } 67932 #moveToTail(index) { 67933 // if tail already, nothing to do 67934 // if head, move head to next[index] 67935 // else 67936 // move next[prev[index]] to next[index] (head has no prev) 67937 // move prev[next[index]] to prev[index] 67938 // prev[index] = tail 67939 // next[tail] = index 67940 // tail = index 67941 if (index !== this.#tail) { 67942 if (index === this.#head) { 67943 this.#head = this.#next[index]; 67944 } 67945 else { 67946 this.#connect(this.#prev[index], this.#next[index]); 67947 } 67948 this.#connect(this.#tail, index); 67949 this.#tail = index; 67950 } 67951 } 67952 /** 67953 * Deletes a key out of the cache. 67954 * Returns true if the key was deleted, false otherwise. 67955 */ 67956 delete(k) { 67957 let deleted = false; 67958 if (this.#size !== 0) { 67959 const index = this.#keyMap.get(k); 67960 if (index !== undefined) { 67961 deleted = true; 67962 if (this.#size === 1) { 67963 this.clear(); 67964 } 67965 else { 67966 this.#removeItemSize(index); 67967 const v = this.#valList[index]; 67968 if (this.#isBackgroundFetch(v)) { 67969 v.__abortController.abort(new Error('deleted')); 67970 } 67971 else if (this.#hasDispose || this.#hasDisposeAfter) { 67972 if (this.#hasDispose) { 67973 this.#dispose?.(v, k, 'delete'); 67974 } 67975 if (this.#hasDisposeAfter) { 67976 this.#disposed?.push([v, k, 'delete']); 67977 } 67978 } 67979 this.#keyMap.delete(k); 67980 this.#keyList[index] = undefined; 67981 this.#valList[index] = undefined; 67982 if (index === this.#tail) { 67983 this.#tail = this.#prev[index]; 67984 } 67985 else if (index === this.#head) { 67986 this.#head = this.#next[index]; 67987 } 67988 else { 67989 const pi = this.#prev[index]; 67990 this.#next[pi] = this.#next[index]; 67991 const ni = this.#next[index]; 67992 this.#prev[ni] = this.#prev[index]; 67993 } 67994 this.#size--; 67995 this.#free.push(index); 67996 } 67997 } 67998 } 67999 if (this.#hasDisposeAfter && this.#disposed?.length) { 68000 const dt = this.#disposed; 68001 let task; 68002 while ((task = dt?.shift())) { 68003 this.#disposeAfter?.(...task); 68004 } 68005 } 68006 return deleted; 68007 } 68008 /** 68009 * Clear the cache entirely, throwing away all values. 68010 */ 68011 clear() { 68012 for (const index of this.#rindexes({ allowStale: true })) { 68013 const v = this.#valList[index]; 68014 if (this.#isBackgroundFetch(v)) { 68015 v.__abortController.abort(new Error('deleted')); 68016 } 68017 else { 68018 const k = this.#keyList[index]; 68019 if (this.#hasDispose) { 68020 this.#dispose?.(v, k, 'delete'); 68021 } 68022 if (this.#hasDisposeAfter) { 68023 this.#disposed?.push([v, k, 'delete']); 68024 } 68025 } 68026 } 68027 this.#keyMap.clear(); 68028 this.#valList.fill(undefined); 68029 this.#keyList.fill(undefined); 68030 if (this.#ttls && this.#starts) { 68031 this.#ttls.fill(0); 68032 this.#starts.fill(0); 68033 } 68034 if (this.#sizes) { 68035 this.#sizes.fill(0); 68036 } 68037 this.#head = 0; 68038 this.#tail = 0; 68039 this.#free.length = 0; 68040 this.#calculatedSize = 0; 68041 this.#size = 0; 68042 if (this.#hasDisposeAfter && this.#disposed) { 68043 const dt = this.#disposed; 68044 let task; 68045 while ((task = dt?.shift())) { 68046 this.#disposeAfter?.(...task); 68047 } 68048 } 68049 } 68050 } 68051 exports.LRUCache = LRUCache; 68052 //# sourceMappingURL=index.js.map 68053 68054 /***/ }), 68055 68056 /***/ 3691: 68057 /***/ ((__unused_webpack_module, exports) => { 68058 68059 "use strict"; 68060 68061 Object.defineProperty(exports, "__esModule", ({ value: true })); 68062 exports.assertValidPattern = void 0; 68063 const MAX_PATTERN_LENGTH = 1024 * 64; 68064 const assertValidPattern = (pattern) => { 68065 if (typeof pattern !== 'string') { 68066 throw new TypeError('invalid pattern'); 68067 } 68068 if (pattern.length > MAX_PATTERN_LENGTH) { 68069 throw new TypeError('pattern is too long'); 68070 } 68071 }; 68072 exports.assertValidPattern = assertValidPattern; 68073 //# sourceMappingURL=assert-valid-pattern.js.map 68074 68075 /***/ }), 68076 68077 /***/ 9262: 68078 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 68079 68080 "use strict"; 68081 68082 // parse a single path portion 68083 Object.defineProperty(exports, "__esModule", ({ value: true })); 68084 exports.AST = void 0; 68085 const brace_expressions_js_1 = __nccwpck_require__(3542); 68086 const unescape_js_1 = __nccwpck_require__(3704); 68087 const types = new Set(['!', '?', '+', '*', '@']); 68088 const isExtglobType = (c) => types.has(c); 68089 // Patterns that get prepended to bind to the start of either the 68090 // entire string, or just a single path portion, to prevent dots 68091 // and/or traversal patterns, when needed. 68092 // Exts don't need the ^ or / bit, because the root binds that already. 68093 const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; 68094 const startNoDot = '(?!\\.)'; 68095 // characters that indicate a start of pattern needs the "no dots" bit, 68096 // because a dot *might* be matched. ( is not in the list, because in 68097 // the case of a child extglob, it will handle the prevention itself. 68098 const addPatternStart = new Set(['[', '.']); 68099 // cases where traversal is A-OK, no dot prevention needed 68100 const justDots = new Set(['..', '.']); 68101 const reSpecials = new Set('().*{}+?[]^$\\!'); 68102 const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 68103 // any single thing other than / 68104 const qmark = '[^/]'; 68105 // * => any number of characters 68106 const star = qmark + '*?'; 68107 // use + when we need to ensure that *something* matches, because the * is 68108 // the only thing in the path portion. 68109 const starNoEmpty = qmark + '+?'; 68110 // remove the \ chars that we added if we end up doing a nonmagic compare 68111 // const deslash = (s: string) => s.replace(/\\(.)/g, '$1') 68112 class AST { 68113 type; 68114 #root; 68115 #hasMagic; 68116 #uflag = false; 68117 #parts = []; 68118 #parent; 68119 #parentIndex; 68120 #negs; 68121 #filledNegs = false; 68122 #options; 68123 #toString; 68124 // set to true if it's an extglob with no children 68125 // (which really means one child of '') 68126 #emptyExt = false; 68127 constructor(type, parent, options = {}) { 68128 this.type = type; 68129 // extglobs are inherently magical 68130 if (type) 68131 this.#hasMagic = true; 68132 this.#parent = parent; 68133 this.#root = this.#parent ? this.#parent.#root : this; 68134 this.#options = this.#root === this ? options : this.#root.#options; 68135 this.#negs = this.#root === this ? [] : this.#root.#negs; 68136 if (type === '!' && !this.#root.#filledNegs) 68137 this.#negs.push(this); 68138 this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; 68139 } 68140 get hasMagic() { 68141 /* c8 ignore start */ 68142 if (this.#hasMagic !== undefined) 68143 return this.#hasMagic; 68144 /* c8 ignore stop */ 68145 for (const p of this.#parts) { 68146 if (typeof p === 'string') 68147 continue; 68148 if (p.type || p.hasMagic) 68149 return (this.#hasMagic = true); 68150 } 68151 // note: will be undefined until we generate the regexp src and find out 68152 return this.#hasMagic; 68153 } 68154 // reconstructs the pattern 68155 toString() { 68156 if (this.#toString !== undefined) 68157 return this.#toString; 68158 if (!this.type) { 68159 return (this.#toString = this.#parts.map(p => String(p)).join('')); 68160 } 68161 else { 68162 return (this.#toString = 68163 this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); 68164 } 68165 } 68166 #fillNegs() { 68167 /* c8 ignore start */ 68168 if (this !== this.#root) 68169 throw new Error('should only call on root'); 68170 if (this.#filledNegs) 68171 return this; 68172 /* c8 ignore stop */ 68173 // call toString() once to fill this out 68174 this.toString(); 68175 this.#filledNegs = true; 68176 let n; 68177 while ((n = this.#negs.pop())) { 68178 if (n.type !== '!') 68179 continue; 68180 // walk up the tree, appending everthing that comes AFTER parentIndex 68181 let p = n; 68182 let pp = p.#parent; 68183 while (pp) { 68184 for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { 68185 for (const part of n.#parts) { 68186 /* c8 ignore start */ 68187 if (typeof part === 'string') { 68188 throw new Error('string part in extglob AST??'); 68189 } 68190 /* c8 ignore stop */ 68191 part.copyIn(pp.#parts[i]); 68192 } 68193 } 68194 p = pp; 68195 pp = p.#parent; 68196 } 68197 } 68198 return this; 68199 } 68200 push(...parts) { 68201 for (const p of parts) { 68202 if (p === '') 68203 continue; 68204 /* c8 ignore start */ 68205 if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { 68206 throw new Error('invalid part: ' + p); 68207 } 68208 /* c8 ignore stop */ 68209 this.#parts.push(p); 68210 } 68211 } 68212 toJSON() { 68213 const ret = this.type === null 68214 ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) 68215 : [this.type, ...this.#parts.map(p => p.toJSON())]; 68216 if (this.isStart() && !this.type) 68217 ret.unshift([]); 68218 if (this.isEnd() && 68219 (this === this.#root || 68220 (this.#root.#filledNegs && this.#parent?.type === '!'))) { 68221 ret.push({}); 68222 } 68223 return ret; 68224 } 68225 isStart() { 68226 if (this.#root === this) 68227 return true; 68228 // if (this.type) return !!this.#parent?.isStart() 68229 if (!this.#parent?.isStart()) 68230 return false; 68231 if (this.#parentIndex === 0) 68232 return true; 68233 // if everything AHEAD of this is a negation, then it's still the "start" 68234 const p = this.#parent; 68235 for (let i = 0; i < this.#parentIndex; i++) { 68236 const pp = p.#parts[i]; 68237 if (!(pp instanceof AST && pp.type === '!')) { 68238 return false; 68239 } 68240 } 68241 return true; 68242 } 68243 isEnd() { 68244 if (this.#root === this) 68245 return true; 68246 if (this.#parent?.type === '!') 68247 return true; 68248 if (!this.#parent?.isEnd()) 68249 return false; 68250 if (!this.type) 68251 return this.#parent?.isEnd(); 68252 // if not root, it'll always have a parent 68253 /* c8 ignore start */ 68254 const pl = this.#parent ? this.#parent.#parts.length : 0; 68255 /* c8 ignore stop */ 68256 return this.#parentIndex === pl - 1; 68257 } 68258 copyIn(part) { 68259 if (typeof part === 'string') 68260 this.push(part); 68261 else 68262 this.push(part.clone(this)); 68263 } 68264 clone(parent) { 68265 const c = new AST(this.type, parent); 68266 for (const p of this.#parts) { 68267 c.copyIn(p); 68268 } 68269 return c; 68270 } 68271 static #parseAST(str, ast, pos, opt) { 68272 let escaping = false; 68273 let inBrace = false; 68274 let braceStart = -1; 68275 let braceNeg = false; 68276 if (ast.type === null) { 68277 // outside of a extglob, append until we find a start 68278 let i = pos; 68279 let acc = ''; 68280 while (i < str.length) { 68281 const c = str.charAt(i++); 68282 // still accumulate escapes at this point, but we do ignore 68283 // starts that are escaped 68284 if (escaping || c === '\\') { 68285 escaping = !escaping; 68286 acc += c; 68287 continue; 68288 } 68289 if (inBrace) { 68290 if (i === braceStart + 1) { 68291 if (c === '^' || c === '!') { 68292 braceNeg = true; 68293 } 68294 } 68295 else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { 68296 inBrace = false; 68297 } 68298 acc += c; 68299 continue; 68300 } 68301 else if (c === '[') { 68302 inBrace = true; 68303 braceStart = i; 68304 braceNeg = false; 68305 acc += c; 68306 continue; 68307 } 68308 if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { 68309 ast.push(acc); 68310 acc = ''; 68311 const ext = new AST(c, ast); 68312 i = AST.#parseAST(str, ext, i, opt); 68313 ast.push(ext); 68314 continue; 68315 } 68316 acc += c; 68317 } 68318 ast.push(acc); 68319 return i; 68320 } 68321 // some kind of extglob, pos is at the ( 68322 // find the next | or ) 68323 let i = pos + 1; 68324 let part = new AST(null, ast); 68325 const parts = []; 68326 let acc = ''; 68327 while (i < str.length) { 68328 const c = str.charAt(i++); 68329 // still accumulate escapes at this point, but we do ignore 68330 // starts that are escaped 68331 if (escaping || c === '\\') { 68332 escaping = !escaping; 68333 acc += c; 68334 continue; 68335 } 68336 if (inBrace) { 68337 if (i === braceStart + 1) { 68338 if (c === '^' || c === '!') { 68339 braceNeg = true; 68340 } 68341 } 68342 else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { 68343 inBrace = false; 68344 } 68345 acc += c; 68346 continue; 68347 } 68348 else if (c === '[') { 68349 inBrace = true; 68350 braceStart = i; 68351 braceNeg = false; 68352 acc += c; 68353 continue; 68354 } 68355 if (isExtglobType(c) && str.charAt(i) === '(') { 68356 part.push(acc); 68357 acc = ''; 68358 const ext = new AST(c, part); 68359 part.push(ext); 68360 i = AST.#parseAST(str, ext, i, opt); 68361 continue; 68362 } 68363 if (c === '|') { 68364 part.push(acc); 68365 acc = ''; 68366 parts.push(part); 68367 part = new AST(null, ast); 68368 continue; 68369 } 68370 if (c === ')') { 68371 if (acc === '' && ast.#parts.length === 0) { 68372 ast.#emptyExt = true; 68373 } 68374 part.push(acc); 68375 acc = ''; 68376 ast.push(...parts, part); 68377 return i; 68378 } 68379 acc += c; 68380 } 68381 // unfinished extglob 68382 // if we got here, it was a malformed extglob! not an extglob, but 68383 // maybe something else in there. 68384 ast.type = null; 68385 ast.#hasMagic = undefined; 68386 ast.#parts = [str.substring(pos - 1)]; 68387 return i; 68388 } 68389 static fromGlob(pattern, options = {}) { 68390 const ast = new AST(null, undefined, options); 68391 AST.#parseAST(pattern, ast, 0, options); 68392 return ast; 68393 } 68394 // returns the regular expression if there's magic, or the unescaped 68395 // string if not. 68396 toMMPattern() { 68397 // should only be called on root 68398 /* c8 ignore start */ 68399 if (this !== this.#root) 68400 return this.#root.toMMPattern(); 68401 /* c8 ignore stop */ 68402 const glob = this.toString(); 68403 const [re, body, hasMagic, uflag] = this.toRegExpSource(); 68404 // if we're in nocase mode, and not nocaseMagicOnly, then we do 68405 // still need a regular expression if we have to case-insensitively 68406 // match capital/lowercase characters. 68407 const anyMagic = hasMagic || 68408 this.#hasMagic || 68409 (this.#options.nocase && 68410 !this.#options.nocaseMagicOnly && 68411 glob.toUpperCase() !== glob.toLowerCase()); 68412 if (!anyMagic) { 68413 return body; 68414 } 68415 const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); 68416 return Object.assign(new RegExp(`^${re}$`, flags), { 68417 _src: re, 68418 _glob: glob, 68419 }); 68420 } 68421 // returns the string match, the regexp source, whether there's magic 68422 // in the regexp (so a regular expression is required) and whether or 68423 // not the uflag is needed for the regular expression (for posix classes) 68424 // TODO: instead of injecting the start/end at this point, just return 68425 // the BODY of the regexp, along with the start/end portions suitable 68426 // for binding the start/end in either a joined full-path makeRe context 68427 // (where we bind to (^|/), or a standalone matchPart context (where 68428 // we bind to ^, and not /). Otherwise slashes get duped! 68429 // 68430 // In part-matching mode, the start is: 68431 // - if not isStart: nothing 68432 // - if traversal possible, but not allowed: ^(?!\.\.?$) 68433 // - if dots allowed or not possible: ^ 68434 // - if dots possible and not allowed: ^(?!\.) 68435 // end is: 68436 // - if not isEnd(): nothing 68437 // - else: $ 68438 // 68439 // In full-path matching mode, we put the slash at the START of the 68440 // pattern, so start is: 68441 // - if first pattern: same as part-matching mode 68442 // - if not isStart(): nothing 68443 // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) 68444 // - if dots allowed or not possible: / 68445 // - if dots possible and not allowed: /(?!\.) 68446 // end is: 68447 // - if last pattern, same as part-matching mode 68448 // - else nothing 68449 // 68450 // Always put the (?:$|/) on negated tails, though, because that has to be 68451 // there to bind the end of the negated pattern portion, and it's easier to 68452 // just stick it in now rather than try to inject it later in the middle of 68453 // the pattern. 68454 // 68455 // We can just always return the same end, and leave it up to the caller 68456 // to know whether it's going to be used joined or in parts. 68457 // And, if the start is adjusted slightly, can do the same there: 68458 // - if not isStart: nothing 68459 // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) 68460 // - if dots allowed or not possible: (?:/|^) 68461 // - if dots possible and not allowed: (?:/|^)(?!\.) 68462 // 68463 // But it's better to have a simpler binding without a conditional, for 68464 // performance, so probably better to return both start options. 68465 // 68466 // Then the caller just ignores the end if it's not the first pattern, 68467 // and the start always gets applied. 68468 // 68469 // But that's always going to be $ if it's the ending pattern, or nothing, 68470 // so the caller can just attach $ at the end of the pattern when building. 68471 // 68472 // So the todo is: 68473 // - better detect what kind of start is needed 68474 // - return both flavors of starting pattern 68475 // - attach $ at the end of the pattern when creating the actual RegExp 68476 // 68477 // Ah, but wait, no, that all only applies to the root when the first pattern 68478 // is not an extglob. If the first pattern IS an extglob, then we need all 68479 // that dot prevention biz to live in the extglob portions, because eg 68480 // +(*|.x*) can match .xy but not .yx. 68481 // 68482 // So, return the two flavors if it's #root and the first child is not an 68483 // AST, otherwise leave it to the child AST to handle it, and there, 68484 // use the (?:^|/) style of start binding. 68485 // 68486 // Even simplified further: 68487 // - Since the start for a join is eg /(?!\.) and the start for a part 68488 // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root 68489 // or start or whatever) and prepend ^ or / at the Regexp construction. 68490 toRegExpSource(allowDot) { 68491 const dot = allowDot ?? !!this.#options.dot; 68492 if (this.#root === this) 68493 this.#fillNegs(); 68494 if (!this.type) { 68495 const noEmpty = this.isStart() && this.isEnd(); 68496 const src = this.#parts 68497 .map(p => { 68498 const [re, _, hasMagic, uflag] = typeof p === 'string' 68499 ? AST.#parseGlob(p, this.#hasMagic, noEmpty) 68500 : p.toRegExpSource(allowDot); 68501 this.#hasMagic = this.#hasMagic || hasMagic; 68502 this.#uflag = this.#uflag || uflag; 68503 return re; 68504 }) 68505 .join(''); 68506 let start = ''; 68507 if (this.isStart()) { 68508 if (typeof this.#parts[0] === 'string') { 68509 // this is the string that will match the start of the pattern, 68510 // so we need to protect against dots and such. 68511 // '.' and '..' cannot match unless the pattern is that exactly, 68512 // even if it starts with . or dot:true is set. 68513 const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); 68514 if (!dotTravAllowed) { 68515 const aps = addPatternStart; 68516 // check if we have a possibility of matching . or .., 68517 // and prevent that. 68518 const needNoTrav = 68519 // dots are allowed, and the pattern starts with [ or . 68520 (dot && aps.has(src.charAt(0))) || 68521 // the pattern starts with \., and then [ or . 68522 (src.startsWith('\\.') && aps.has(src.charAt(2))) || 68523 // the pattern starts with \.\., and then [ or . 68524 (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); 68525 // no need to prevent dots if it can't match a dot, or if a 68526 // sub-pattern will be preventing it anyway. 68527 const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); 68528 start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; 68529 } 68530 } 68531 } 68532 // append the "end of path portion" pattern to negation tails 68533 let end = ''; 68534 if (this.isEnd() && 68535 this.#root.#filledNegs && 68536 this.#parent?.type === '!') { 68537 end = '(?:$|\\/)'; 68538 } 68539 const final = start + src + end; 68540 return [ 68541 final, 68542 (0, unescape_js_1.unescape)(src), 68543 (this.#hasMagic = !!this.#hasMagic), 68544 this.#uflag, 68545 ]; 68546 } 68547 // We need to calculate the body *twice* if it's a repeat pattern 68548 // at the start, once in nodot mode, then again in dot mode, so a 68549 // pattern like *(?) can match 'x.y' 68550 const repeated = this.type === '*' || this.type === '+'; 68551 // some kind of extglob 68552 const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; 68553 let body = this.#partsToRegExp(dot); 68554 if (this.isStart() && this.isEnd() && !body && this.type !== '!') { 68555 // invalid extglob, has to at least be *something* present, if it's 68556 // the entire path portion. 68557 const s = this.toString(); 68558 this.#parts = [s]; 68559 this.type = null; 68560 this.#hasMagic = undefined; 68561 return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; 68562 } 68563 // XXX abstract out this map method 68564 let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot 68565 ? '' 68566 : this.#partsToRegExp(true); 68567 if (bodyDotAllowed === body) { 68568 bodyDotAllowed = ''; 68569 } 68570 if (bodyDotAllowed) { 68571 body = `(?:${body})(?:${bodyDotAllowed})*?`; 68572 } 68573 // an empty !() is exactly equivalent to a starNoEmpty 68574 let final = ''; 68575 if (this.type === '!' && this.#emptyExt) { 68576 final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; 68577 } 68578 else { 68579 const close = this.type === '!' 68580 ? // !() must match something,but !(x) can match '' 68581 '))' + 68582 (this.isStart() && !dot && !allowDot ? startNoDot : '') + 68583 star + 68584 ')' 68585 : this.type === '@' 68586 ? ')' 68587 : this.type === '?' 68588 ? ')?' 68589 : this.type === '+' && bodyDotAllowed 68590 ? ')' 68591 : this.type === '*' && bodyDotAllowed 68592 ? `)?` 68593 : `)${this.type}`; 68594 final = start + body + close; 68595 } 68596 return [ 68597 final, 68598 (0, unescape_js_1.unescape)(body), 68599 (this.#hasMagic = !!this.#hasMagic), 68600 this.#uflag, 68601 ]; 68602 } 68603 #partsToRegExp(dot) { 68604 return this.#parts 68605 .map(p => { 68606 // extglob ASTs should only contain parent ASTs 68607 /* c8 ignore start */ 68608 if (typeof p === 'string') { 68609 throw new Error('string type in extglob ast??'); 68610 } 68611 /* c8 ignore stop */ 68612 // can ignore hasMagic, because extglobs are already always magic 68613 const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); 68614 this.#uflag = this.#uflag || uflag; 68615 return re; 68616 }) 68617 .filter(p => !(this.isStart() && this.isEnd()) || !!p) 68618 .join('|'); 68619 } 68620 static #parseGlob(glob, hasMagic, noEmpty = false) { 68621 let escaping = false; 68622 let re = ''; 68623 let uflag = false; 68624 for (let i = 0; i < glob.length; i++) { 68625 const c = glob.charAt(i); 68626 if (escaping) { 68627 escaping = false; 68628 re += (reSpecials.has(c) ? '\\' : '') + c; 68629 continue; 68630 } 68631 if (c === '\\') { 68632 if (i === glob.length - 1) { 68633 re += '\\\\'; 68634 } 68635 else { 68636 escaping = true; 68637 } 68638 continue; 68639 } 68640 if (c === '[') { 68641 const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); 68642 if (consumed) { 68643 re += src; 68644 uflag = uflag || needUflag; 68645 i += consumed - 1; 68646 hasMagic = hasMagic || magic; 68647 continue; 68648 } 68649 } 68650 if (c === '*') { 68651 if (noEmpty && glob === '*') 68652 re += starNoEmpty; 68653 else 68654 re += star; 68655 hasMagic = true; 68656 continue; 68657 } 68658 if (c === '?') { 68659 re += qmark; 68660 hasMagic = true; 68661 continue; 68662 } 68663 re += regExpEscape(c); 68664 } 68665 return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; 68666 } 68667 } 68668 exports.AST = AST; 68669 //# sourceMappingURL=ast.js.map 68670 68671 /***/ }), 68672 68673 /***/ 3542: 68674 /***/ ((__unused_webpack_module, exports) => { 68675 68676 "use strict"; 68677 68678 // translate the various posix character classes into unicode properties 68679 // this works across all unicode locales 68680 Object.defineProperty(exports, "__esModule", ({ value: true })); 68681 exports.parseClass = void 0; 68682 // { <posix class>: [<translation>, /u flag required, negated] 68683 const posixClasses = { 68684 '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], 68685 '[:alpha:]': ['\\p{L}\\p{Nl}', true], 68686 '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], 68687 '[:blank:]': ['\\p{Zs}\\t', true], 68688 '[:cntrl:]': ['\\p{Cc}', true], 68689 '[:digit:]': ['\\p{Nd}', true], 68690 '[:graph:]': ['\\p{Z}\\p{C}', true, true], 68691 '[:lower:]': ['\\p{Ll}', true], 68692 '[:print:]': ['\\p{C}', true], 68693 '[:punct:]': ['\\p{P}', true], 68694 '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], 68695 '[:upper:]': ['\\p{Lu}', true], 68696 '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], 68697 '[:xdigit:]': ['A-Fa-f0-9', false], 68698 }; 68699 // only need to escape a few things inside of brace expressions 68700 // escapes: [ \ ] - 68701 const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); 68702 // escape all regexp magic characters 68703 const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 68704 // everything has already been escaped, we just have to join 68705 const rangesToString = (ranges) => ranges.join(''); 68706 // takes a glob string at a posix brace expression, and returns 68707 // an equivalent regular expression source, and boolean indicating 68708 // whether the /u flag needs to be applied, and the number of chars 68709 // consumed to parse the character class. 68710 // This also removes out of order ranges, and returns ($.) if the 68711 // entire class just no good. 68712 const parseClass = (glob, position) => { 68713 const pos = position; 68714 /* c8 ignore start */ 68715 if (glob.charAt(pos) !== '[') { 68716 throw new Error('not in a brace expression'); 68717 } 68718 /* c8 ignore stop */ 68719 const ranges = []; 68720 const negs = []; 68721 let i = pos + 1; 68722 let sawStart = false; 68723 let uflag = false; 68724 let escaping = false; 68725 let negate = false; 68726 let endPos = pos; 68727 let rangeStart = ''; 68728 WHILE: while (i < glob.length) { 68729 const c = glob.charAt(i); 68730 if ((c === '!' || c === '^') && i === pos + 1) { 68731 negate = true; 68732 i++; 68733 continue; 68734 } 68735 if (c === ']' && sawStart && !escaping) { 68736 endPos = i + 1; 68737 break; 68738 } 68739 sawStart = true; 68740 if (c === '\\') { 68741 if (!escaping) { 68742 escaping = true; 68743 i++; 68744 continue; 68745 } 68746 // escaped \ char, fall through and treat like normal char 68747 } 68748 if (c === '[' && !escaping) { 68749 // either a posix class, a collation equivalent, or just a [ 68750 for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { 68751 if (glob.startsWith(cls, i)) { 68752 // invalid, [a-[] is fine, but not [a-[:alpha]] 68753 if (rangeStart) { 68754 return ['$.', false, glob.length - pos, true]; 68755 } 68756 i += cls.length; 68757 if (neg) 68758 negs.push(unip); 68759 else 68760 ranges.push(unip); 68761 uflag = uflag || u; 68762 continue WHILE; 68763 } 68764 } 68765 } 68766 // now it's just a normal character, effectively 68767 escaping = false; 68768 if (rangeStart) { 68769 // throw this range away if it's not valid, but others 68770 // can still match. 68771 if (c > rangeStart) { 68772 ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); 68773 } 68774 else if (c === rangeStart) { 68775 ranges.push(braceEscape(c)); 68776 } 68777 rangeStart = ''; 68778 i++; 68779 continue; 68780 } 68781 // now might be the start of a range. 68782 // can be either c-d or c-] or c<more...>] or c] at this point 68783 if (glob.startsWith('-]', i + 1)) { 68784 ranges.push(braceEscape(c + '-')); 68785 i += 2; 68786 continue; 68787 } 68788 if (glob.startsWith('-', i + 1)) { 68789 rangeStart = c; 68790 i += 2; 68791 continue; 68792 } 68793 // not the start of a range, just a single character 68794 ranges.push(braceEscape(c)); 68795 i++; 68796 } 68797 if (endPos < i) { 68798 // didn't see the end of the class, not a valid class, 68799 // but might still be valid as a literal match. 68800 return ['', false, 0, false]; 68801 } 68802 // if we got no ranges and no negates, then we have a range that 68803 // cannot possibly match anything, and that poisons the whole glob 68804 if (!ranges.length && !negs.length) { 68805 return ['$.', false, glob.length - pos, true]; 68806 } 68807 // if we got one positive range, and it's a single character, then that's 68808 // not actually a magic pattern, it's just that one literal character. 68809 // we should not treat that as "magic", we should just return the literal 68810 // character. [_] is a perfectly valid way to escape glob magic chars. 68811 if (negs.length === 0 && 68812 ranges.length === 1 && 68813 /^\\?.$/.test(ranges[0]) && 68814 !negate) { 68815 const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; 68816 return [regexpEscape(r), false, endPos - pos, false]; 68817 } 68818 const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; 68819 const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; 68820 const comb = ranges.length && negs.length 68821 ? '(' + sranges + '|' + snegs + ')' 68822 : ranges.length 68823 ? sranges 68824 : snegs; 68825 return [comb, uflag, endPos - pos, true]; 68826 }; 68827 exports.parseClass = parseClass; 68828 //# sourceMappingURL=brace-expressions.js.map 68829 68830 /***/ }), 68831 68832 /***/ 6636: 68833 /***/ ((__unused_webpack_module, exports) => { 68834 68835 "use strict"; 68836 68837 Object.defineProperty(exports, "__esModule", ({ value: true })); 68838 exports.escape = void 0; 68839 /** 68840 * Escape all magic characters in a glob pattern. 68841 * 68842 * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} 68843 * option is used, then characters are escaped by wrapping in `[]`, because 68844 * a magic character wrapped in a character class can only be satisfied by 68845 * that exact character. In this mode, `\` is _not_ escaped, because it is 68846 * not interpreted as a magic character, but instead as a path separator. 68847 */ 68848 const escape = (s, { windowsPathsNoEscape = false, } = {}) => { 68849 // don't need to escape +@! because we escape the parens 68850 // that make those magic, and escaping ! as [!] isn't valid, 68851 // because [!]] is a valid glob class meaning not ']'. 68852 return windowsPathsNoEscape 68853 ? s.replace(/[?*()[\]]/g, '[$&]') 68854 : s.replace(/[?*()[\]\\]/g, '\\$&'); 68855 }; 68856 exports.escape = escape; 68857 //# sourceMappingURL=escape.js.map 68858 68859 /***/ }), 68860 68861 /***/ 7111: 68862 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 68863 68864 "use strict"; 68865 68866 var __importDefault = (this && this.__importDefault) || function (mod) { 68867 return (mod && mod.__esModule) ? mod : { "default": mod }; 68868 }; 68869 Object.defineProperty(exports, "__esModule", ({ value: true })); 68870 exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; 68871 const brace_expansion_1 = __importDefault(__nccwpck_require__(2443)); 68872 const assert_valid_pattern_js_1 = __nccwpck_require__(3691); 68873 const ast_js_1 = __nccwpck_require__(9262); 68874 const escape_js_1 = __nccwpck_require__(6636); 68875 const unescape_js_1 = __nccwpck_require__(3704); 68876 const minimatch = (p, pattern, options = {}) => { 68877 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 68878 // shortcut: comments match nothing. 68879 if (!options.nocomment && pattern.charAt(0) === '#') { 68880 return false; 68881 } 68882 return new Minimatch(pattern, options).match(p); 68883 }; 68884 exports.minimatch = minimatch; 68885 // Optimized checking for the most common glob patterns. 68886 const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; 68887 const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); 68888 const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); 68889 const starDotExtTestNocase = (ext) => { 68890 ext = ext.toLowerCase(); 68891 return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); 68892 }; 68893 const starDotExtTestNocaseDot = (ext) => { 68894 ext = ext.toLowerCase(); 68895 return (f) => f.toLowerCase().endsWith(ext); 68896 }; 68897 const starDotStarRE = /^\*+\.\*+$/; 68898 const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); 68899 const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); 68900 const dotStarRE = /^\.\*+$/; 68901 const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); 68902 const starRE = /^\*+$/; 68903 const starTest = (f) => f.length !== 0 && !f.startsWith('.'); 68904 const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; 68905 const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; 68906 const qmarksTestNocase = ([$0, ext = '']) => { 68907 const noext = qmarksTestNoExt([$0]); 68908 if (!ext) 68909 return noext; 68910 ext = ext.toLowerCase(); 68911 return (f) => noext(f) && f.toLowerCase().endsWith(ext); 68912 }; 68913 const qmarksTestNocaseDot = ([$0, ext = '']) => { 68914 const noext = qmarksTestNoExtDot([$0]); 68915 if (!ext) 68916 return noext; 68917 ext = ext.toLowerCase(); 68918 return (f) => noext(f) && f.toLowerCase().endsWith(ext); 68919 }; 68920 const qmarksTestDot = ([$0, ext = '']) => { 68921 const noext = qmarksTestNoExtDot([$0]); 68922 return !ext ? noext : (f) => noext(f) && f.endsWith(ext); 68923 }; 68924 const qmarksTest = ([$0, ext = '']) => { 68925 const noext = qmarksTestNoExt([$0]); 68926 return !ext ? noext : (f) => noext(f) && f.endsWith(ext); 68927 }; 68928 const qmarksTestNoExt = ([$0]) => { 68929 const len = $0.length; 68930 return (f) => f.length === len && !f.startsWith('.'); 68931 }; 68932 const qmarksTestNoExtDot = ([$0]) => { 68933 const len = $0.length; 68934 return (f) => f.length === len && f !== '.' && f !== '..'; 68935 }; 68936 /* c8 ignore start */ 68937 const defaultPlatform = (typeof process === 'object' && process 68938 ? (typeof process.env === 'object' && 68939 process.env && 68940 process.env.__MINIMATCH_TESTING_PLATFORM__) || 68941 process.platform 68942 : 'posix'); 68943 const path = { 68944 win32: { sep: '\\' }, 68945 posix: { sep: '/' }, 68946 }; 68947 /* c8 ignore stop */ 68948 exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; 68949 exports.minimatch.sep = exports.sep; 68950 exports.GLOBSTAR = Symbol('globstar **'); 68951 exports.minimatch.GLOBSTAR = exports.GLOBSTAR; 68952 // any single thing other than / 68953 // don't need to escape / when using new RegExp() 68954 const qmark = '[^/]'; 68955 // * => any number of characters 68956 const star = qmark + '*?'; 68957 // ** when dots are allowed. Anything goes, except .. and . 68958 // not (^ or / followed by one or two dots followed by $ or /), 68959 // followed by anything, any number of times. 68960 const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; 68961 // not a ^ or / followed by a dot, 68962 // followed by anything, any number of times. 68963 const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; 68964 const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); 68965 exports.filter = filter; 68966 exports.minimatch.filter = exports.filter; 68967 const ext = (a, b = {}) => Object.assign({}, a, b); 68968 const defaults = (def) => { 68969 if (!def || typeof def !== 'object' || !Object.keys(def).length) { 68970 return exports.minimatch; 68971 } 68972 const orig = exports.minimatch; 68973 const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); 68974 return Object.assign(m, { 68975 Minimatch: class Minimatch extends orig.Minimatch { 68976 constructor(pattern, options = {}) { 68977 super(pattern, ext(def, options)); 68978 } 68979 static defaults(options) { 68980 return orig.defaults(ext(def, options)).Minimatch; 68981 } 68982 }, 68983 AST: class AST extends orig.AST { 68984 /* c8 ignore start */ 68985 constructor(type, parent, options = {}) { 68986 super(type, parent, ext(def, options)); 68987 } 68988 /* c8 ignore stop */ 68989 static fromGlob(pattern, options = {}) { 68990 return orig.AST.fromGlob(pattern, ext(def, options)); 68991 } 68992 }, 68993 unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), 68994 escape: (s, options = {}) => orig.escape(s, ext(def, options)), 68995 filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), 68996 defaults: (options) => orig.defaults(ext(def, options)), 68997 makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), 68998 braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), 68999 match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), 69000 sep: orig.sep, 69001 GLOBSTAR: exports.GLOBSTAR, 69002 }); 69003 }; 69004 exports.defaults = defaults; 69005 exports.minimatch.defaults = exports.defaults; 69006 // Brace expansion: 69007 // a{b,c}d -> abd acd 69008 // a{b,}c -> abc ac 69009 // a{0..3}d -> a0d a1d a2d a3d 69010 // a{b,c{d,e}f}g -> abg acdfg acefg 69011 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg 69012 // 69013 // Invalid sets are not expanded. 69014 // a{2..}b -> a{2..}b 69015 // a{b}c -> a{b}c 69016 const braceExpand = (pattern, options = {}) => { 69017 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 69018 // Thanks to Yeting Li <https://github.com/yetingli> for 69019 // improving this regexp to avoid a ReDOS vulnerability. 69020 if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { 69021 // shortcut. no need to expand. 69022 return [pattern]; 69023 } 69024 return (0, brace_expansion_1.default)(pattern); 69025 }; 69026 exports.braceExpand = braceExpand; 69027 exports.minimatch.braceExpand = exports.braceExpand; 69028 // parse a component of the expanded set. 69029 // At this point, no pattern may contain "/" in it 69030 // so we're going to return a 2d array, where each entry is the full 69031 // pattern, split on '/', and then turned into a regular expression. 69032 // A regexp is made at the end which joins each array with an 69033 // escaped /, and another full one which joins each regexp with |. 69034 // 69035 // Following the lead of Bash 4.1, note that "**" only has special meaning 69036 // when it is the *only* thing in a path portion. Otherwise, any series 69037 // of * is equivalent to a single *. Globstar behavior is enabled by 69038 // default, and can be disabled by setting options.noglobstar. 69039 const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); 69040 exports.makeRe = makeRe; 69041 exports.minimatch.makeRe = exports.makeRe; 69042 const match = (list, pattern, options = {}) => { 69043 const mm = new Minimatch(pattern, options); 69044 list = list.filter(f => mm.match(f)); 69045 if (mm.options.nonull && !list.length) { 69046 list.push(pattern); 69047 } 69048 return list; 69049 }; 69050 exports.match = match; 69051 exports.minimatch.match = exports.match; 69052 // replace stuff like \* with * 69053 const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; 69054 const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 69055 class Minimatch { 69056 options; 69057 set; 69058 pattern; 69059 windowsPathsNoEscape; 69060 nonegate; 69061 negate; 69062 comment; 69063 empty; 69064 preserveMultipleSlashes; 69065 partial; 69066 globSet; 69067 globParts; 69068 nocase; 69069 isWindows; 69070 platform; 69071 windowsNoMagicRoot; 69072 regexp; 69073 constructor(pattern, options = {}) { 69074 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 69075 options = options || {}; 69076 this.options = options; 69077 this.pattern = pattern; 69078 this.platform = options.platform || defaultPlatform; 69079 this.isWindows = this.platform === 'win32'; 69080 this.windowsPathsNoEscape = 69081 !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; 69082 if (this.windowsPathsNoEscape) { 69083 this.pattern = this.pattern.replace(/\\/g, '/'); 69084 } 69085 this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; 69086 this.regexp = null; 69087 this.negate = false; 69088 this.nonegate = !!options.nonegate; 69089 this.comment = false; 69090 this.empty = false; 69091 this.partial = !!options.partial; 69092 this.nocase = !!this.options.nocase; 69093 this.windowsNoMagicRoot = 69094 options.windowsNoMagicRoot !== undefined 69095 ? options.windowsNoMagicRoot 69096 : !!(this.isWindows && this.nocase); 69097 this.globSet = []; 69098 this.globParts = []; 69099 this.set = []; 69100 // make the set of regexps etc. 69101 this.make(); 69102 } 69103 hasMagic() { 69104 if (this.options.magicalBraces && this.set.length > 1) { 69105 return true; 69106 } 69107 for (const pattern of this.set) { 69108 for (const part of pattern) { 69109 if (typeof part !== 'string') 69110 return true; 69111 } 69112 } 69113 return false; 69114 } 69115 debug(..._) { } 69116 make() { 69117 const pattern = this.pattern; 69118 const options = this.options; 69119 // empty patterns and comments match nothing. 69120 if (!options.nocomment && pattern.charAt(0) === '#') { 69121 this.comment = true; 69122 return; 69123 } 69124 if (!pattern) { 69125 this.empty = true; 69126 return; 69127 } 69128 // step 1: figure out negation, etc. 69129 this.parseNegate(); 69130 // step 2: expand braces 69131 this.globSet = [...new Set(this.braceExpand())]; 69132 if (options.debug) { 69133 this.debug = (...args) => console.error(...args); 69134 } 69135 this.debug(this.pattern, this.globSet); 69136 // step 3: now we have a set, so turn each one into a series of 69137 // path-portion matching patterns. 69138 // These will be regexps, except in the case of "**", which is 69139 // set to the GLOBSTAR object for globstar behavior, 69140 // and will not contain any / characters 69141 // 69142 // First, we preprocess to make the glob pattern sets a bit simpler 69143 // and deduped. There are some perf-killing patterns that can cause 69144 // problems with a glob walk, but we can simplify them down a bit. 69145 const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); 69146 this.globParts = this.preprocess(rawGlobParts); 69147 this.debug(this.pattern, this.globParts); 69148 // glob --> regexps 69149 let set = this.globParts.map((s, _, __) => { 69150 if (this.isWindows && this.windowsNoMagicRoot) { 69151 // check if it's a drive or unc path. 69152 const isUNC = s[0] === '' && 69153 s[1] === '' && 69154 (s[2] === '?' || !globMagic.test(s[2])) && 69155 !globMagic.test(s[3]); 69156 const isDrive = /^[a-z]:/i.test(s[0]); 69157 if (isUNC) { 69158 return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; 69159 } 69160 else if (isDrive) { 69161 return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; 69162 } 69163 } 69164 return s.map(ss => this.parse(ss)); 69165 }); 69166 this.debug(this.pattern, set); 69167 // filter out everything that didn't compile properly. 69168 this.set = set.filter(s => s.indexOf(false) === -1); 69169 // do not treat the ? in UNC paths as magic 69170 if (this.isWindows) { 69171 for (let i = 0; i < this.set.length; i++) { 69172 const p = this.set[i]; 69173 if (p[0] === '' && 69174 p[1] === '' && 69175 this.globParts[i][2] === '?' && 69176 typeof p[3] === 'string' && 69177 /^[a-z]:$/i.test(p[3])) { 69178 p[2] = '?'; 69179 } 69180 } 69181 } 69182 this.debug(this.pattern, this.set); 69183 } 69184 // various transforms to equivalent pattern sets that are 69185 // faster to process in a filesystem walk. The goal is to 69186 // eliminate what we can, and push all ** patterns as far 69187 // to the right as possible, even if it increases the number 69188 // of patterns that we have to process. 69189 preprocess(globParts) { 69190 // if we're not in globstar mode, then turn all ** into * 69191 if (this.options.noglobstar) { 69192 for (let i = 0; i < globParts.length; i++) { 69193 for (let j = 0; j < globParts[i].length; j++) { 69194 if (globParts[i][j] === '**') { 69195 globParts[i][j] = '*'; 69196 } 69197 } 69198 } 69199 } 69200 const { optimizationLevel = 1 } = this.options; 69201 if (optimizationLevel >= 2) { 69202 // aggressive optimization for the purpose of fs walking 69203 globParts = this.firstPhasePreProcess(globParts); 69204 globParts = this.secondPhasePreProcess(globParts); 69205 } 69206 else if (optimizationLevel >= 1) { 69207 // just basic optimizations to remove some .. parts 69208 globParts = this.levelOneOptimize(globParts); 69209 } 69210 else { 69211 globParts = this.adjascentGlobstarOptimize(globParts); 69212 } 69213 return globParts; 69214 } 69215 // just get rid of adjascent ** portions 69216 adjascentGlobstarOptimize(globParts) { 69217 return globParts.map(parts => { 69218 let gs = -1; 69219 while (-1 !== (gs = parts.indexOf('**', gs + 1))) { 69220 let i = gs; 69221 while (parts[i + 1] === '**') { 69222 i++; 69223 } 69224 if (i !== gs) { 69225 parts.splice(gs, i - gs); 69226 } 69227 } 69228 return parts; 69229 }); 69230 } 69231 // get rid of adjascent ** and resolve .. portions 69232 levelOneOptimize(globParts) { 69233 return globParts.map(parts => { 69234 parts = parts.reduce((set, part) => { 69235 const prev = set[set.length - 1]; 69236 if (part === '**' && prev === '**') { 69237 return set; 69238 } 69239 if (part === '..') { 69240 if (prev && prev !== '..' && prev !== '.' && prev !== '**') { 69241 set.pop(); 69242 return set; 69243 } 69244 } 69245 set.push(part); 69246 return set; 69247 }, []); 69248 return parts.length === 0 ? [''] : parts; 69249 }); 69250 } 69251 levelTwoFileOptimize(parts) { 69252 if (!Array.isArray(parts)) { 69253 parts = this.slashSplit(parts); 69254 } 69255 let didSomething = false; 69256 do { 69257 didSomething = false; 69258 // <pre>/<e>/<rest> -> <pre>/<rest> 69259 if (!this.preserveMultipleSlashes) { 69260 for (let i = 1; i < parts.length - 1; i++) { 69261 const p = parts[i]; 69262 // don't squeeze out UNC patterns 69263 if (i === 1 && p === '' && parts[0] === '') 69264 continue; 69265 if (p === '.' || p === '') { 69266 didSomething = true; 69267 parts.splice(i, 1); 69268 i--; 69269 } 69270 } 69271 if (parts[0] === '.' && 69272 parts.length === 2 && 69273 (parts[1] === '.' || parts[1] === '')) { 69274 didSomething = true; 69275 parts.pop(); 69276 } 69277 } 69278 // <pre>/<p>/../<rest> -> <pre>/<rest> 69279 let dd = 0; 69280 while (-1 !== (dd = parts.indexOf('..', dd + 1))) { 69281 const p = parts[dd - 1]; 69282 if (p && p !== '.' && p !== '..' && p !== '**') { 69283 didSomething = true; 69284 parts.splice(dd - 1, 2); 69285 dd -= 2; 69286 } 69287 } 69288 } while (didSomething); 69289 return parts.length === 0 ? [''] : parts; 69290 } 69291 // First phase: single-pattern processing 69292 // <pre> is 1 or more portions 69293 // <rest> is 1 or more portions 69294 // <p> is any portion other than ., .., '', or ** 69295 // <e> is . or '' 69296 // 69297 // **/.. is *brutal* for filesystem walking performance, because 69298 // it effectively resets the recursive walk each time it occurs, 69299 // and ** cannot be reduced out by a .. pattern part like a regexp 69300 // or most strings (other than .., ., and '') can be. 69301 // 69302 // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>} 69303 // <pre>/<e>/<rest> -> <pre>/<rest> 69304 // <pre>/<p>/../<rest> -> <pre>/<rest> 69305 // **/**/<rest> -> **/<rest> 69306 // 69307 // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow 69308 // this WOULD be allowed if ** did follow symlinks, or * didn't 69309 firstPhasePreProcess(globParts) { 69310 let didSomething = false; 69311 do { 69312 didSomething = false; 69313 // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>} 69314 for (let parts of globParts) { 69315 let gs = -1; 69316 while (-1 !== (gs = parts.indexOf('**', gs + 1))) { 69317 let gss = gs; 69318 while (parts[gss + 1] === '**') { 69319 // <pre>/**/**/<rest> -> <pre>/**/<rest> 69320 gss++; 69321 } 69322 // eg, if gs is 2 and gss is 4, that means we have 3 ** 69323 // parts, and can remove 2 of them. 69324 if (gss > gs) { 69325 parts.splice(gs + 1, gss - gs); 69326 } 69327 let next = parts[gs + 1]; 69328 const p = parts[gs + 2]; 69329 const p2 = parts[gs + 3]; 69330 if (next !== '..') 69331 continue; 69332 if (!p || 69333 p === '.' || 69334 p === '..' || 69335 !p2 || 69336 p2 === '.' || 69337 p2 === '..') { 69338 continue; 69339 } 69340 didSomething = true; 69341 // edit parts in place, and push the new one 69342 parts.splice(gs, 1); 69343 const other = parts.slice(0); 69344 other[gs] = '**'; 69345 globParts.push(other); 69346 gs--; 69347 } 69348 // <pre>/<e>/<rest> -> <pre>/<rest> 69349 if (!this.preserveMultipleSlashes) { 69350 for (let i = 1; i < parts.length - 1; i++) { 69351 const p = parts[i]; 69352 // don't squeeze out UNC patterns 69353 if (i === 1 && p === '' && parts[0] === '') 69354 continue; 69355 if (p === '.' || p === '') { 69356 didSomething = true; 69357 parts.splice(i, 1); 69358 i--; 69359 } 69360 } 69361 if (parts[0] === '.' && 69362 parts.length === 2 && 69363 (parts[1] === '.' || parts[1] === '')) { 69364 didSomething = true; 69365 parts.pop(); 69366 } 69367 } 69368 // <pre>/<p>/../<rest> -> <pre>/<rest> 69369 let dd = 0; 69370 while (-1 !== (dd = parts.indexOf('..', dd + 1))) { 69371 const p = parts[dd - 1]; 69372 if (p && p !== '.' && p !== '..' && p !== '**') { 69373 didSomething = true; 69374 const needDot = dd === 1 && parts[dd + 1] === '**'; 69375 const splin = needDot ? ['.'] : []; 69376 parts.splice(dd - 1, 2, ...splin); 69377 if (parts.length === 0) 69378 parts.push(''); 69379 dd -= 2; 69380 } 69381 } 69382 } 69383 } while (didSomething); 69384 return globParts; 69385 } 69386 // second phase: multi-pattern dedupes 69387 // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest> 69388 // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest> 69389 // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest> 69390 // 69391 // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest> 69392 // ^-- not valid because ** doens't follow symlinks 69393 secondPhasePreProcess(globParts) { 69394 for (let i = 0; i < globParts.length - 1; i++) { 69395 for (let j = i + 1; j < globParts.length; j++) { 69396 const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes); 69397 if (!matched) 69398 continue; 69399 globParts[i] = matched; 69400 globParts[j] = []; 69401 } 69402 } 69403 return globParts.filter(gs => gs.length); 69404 } 69405 partsMatch(a, b, emptyGSMatch = false) { 69406 let ai = 0; 69407 let bi = 0; 69408 let result = []; 69409 let which = ''; 69410 while (ai < a.length && bi < b.length) { 69411 if (a[ai] === b[bi]) { 69412 result.push(which === 'b' ? b[bi] : a[ai]); 69413 ai++; 69414 bi++; 69415 } 69416 else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) { 69417 result.push(a[ai]); 69418 ai++; 69419 } 69420 else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) { 69421 result.push(b[bi]); 69422 bi++; 69423 } 69424 else if (a[ai] === '*' && 69425 b[bi] && 69426 (this.options.dot || !b[bi].startsWith('.')) && 69427 b[bi] !== '**') { 69428 if (which === 'b') 69429 return false; 69430 which = 'a'; 69431 result.push(a[ai]); 69432 ai++; 69433 bi++; 69434 } 69435 else if (b[bi] === '*' && 69436 a[ai] && 69437 (this.options.dot || !a[ai].startsWith('.')) && 69438 a[ai] !== '**') { 69439 if (which === 'a') 69440 return false; 69441 which = 'b'; 69442 result.push(b[bi]); 69443 ai++; 69444 bi++; 69445 } 69446 else { 69447 return false; 69448 } 69449 } 69450 // if we fall out of the loop, it means they two are identical 69451 // as long as their lengths match 69452 return a.length === b.length && result; 69453 } 69454 parseNegate() { 69455 if (this.nonegate) 69456 return; 69457 const pattern = this.pattern; 69458 let negate = false; 69459 let negateOffset = 0; 69460 for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { 69461 negate = !negate; 69462 negateOffset++; 69463 } 69464 if (negateOffset) 69465 this.pattern = pattern.slice(negateOffset); 69466 this.negate = negate; 69467 } 69468 // set partial to true to test if, for example, 69469 // "/a/b" matches the start of "/*/b/*/d" 69470 // Partial means, if you run out of file before you run 69471 // out of pattern, then that's fine, as long as all 69472 // the parts match. 69473 matchOne(file, pattern, partial = false) { 69474 const options = this.options; 69475 // UNC paths like //?/X:/... can match X:/... and vice versa 69476 // Drive letters in absolute drive or unc paths are always compared 69477 // case-insensitively. 69478 if (this.isWindows) { 69479 const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]); 69480 const fileUNC = !fileDrive && 69481 file[0] === '' && 69482 file[1] === '' && 69483 file[2] === '?' && 69484 /^[a-z]:$/i.test(file[3]); 69485 const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]); 69486 const patternUNC = !patternDrive && 69487 pattern[0] === '' && 69488 pattern[1] === '' && 69489 pattern[2] === '?' && 69490 typeof pattern[3] === 'string' && 69491 /^[a-z]:$/i.test(pattern[3]); 69492 const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined; 69493 const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined; 69494 if (typeof fdi === 'number' && typeof pdi === 'number') { 69495 const [fd, pd] = [file[fdi], pattern[pdi]]; 69496 if (fd.toLowerCase() === pd.toLowerCase()) { 69497 pattern[pdi] = fd; 69498 if (pdi > fdi) { 69499 pattern = pattern.slice(pdi); 69500 } 69501 else if (fdi > pdi) { 69502 file = file.slice(fdi); 69503 } 69504 } 69505 } 69506 } 69507 // resolve and reduce . and .. portions in the file as well. 69508 // dont' need to do the second phase, because it's only one string[] 69509 const { optimizationLevel = 1 } = this.options; 69510 if (optimizationLevel >= 2) { 69511 file = this.levelTwoFileOptimize(file); 69512 } 69513 this.debug('matchOne', this, { file, pattern }); 69514 this.debug('matchOne', file.length, pattern.length); 69515 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { 69516 this.debug('matchOne loop'); 69517 var p = pattern[pi]; 69518 var f = file[fi]; 69519 this.debug(pattern, p, f); 69520 // should be impossible. 69521 // some invalid regexp stuff in the set. 69522 /* c8 ignore start */ 69523 if (p === false) { 69524 return false; 69525 } 69526 /* c8 ignore stop */ 69527 if (p === exports.GLOBSTAR) { 69528 this.debug('GLOBSTAR', [pattern, p, f]); 69529 // "**" 69530 // a/**/b/**/c would match the following: 69531 // a/b/x/y/z/c 69532 // a/x/y/z/b/c 69533 // a/b/x/b/x/c 69534 // a/b/c 69535 // To do this, take the rest of the pattern after 69536 // the **, and see if it would match the file remainder. 69537 // If so, return success. 69538 // If not, the ** "swallows" a segment, and try again. 69539 // This is recursively awful. 69540 // 69541 // a/**/b/**/c matching a/b/x/y/z/c 69542 // - a matches a 69543 // - doublestar 69544 // - matchOne(b/x/y/z/c, b/**/c) 69545 // - b matches b 69546 // - doublestar 69547 // - matchOne(x/y/z/c, c) -> no 69548 // - matchOne(y/z/c, c) -> no 69549 // - matchOne(z/c, c) -> no 69550 // - matchOne(c, c) yes, hit 69551 var fr = fi; 69552 var pr = pi + 1; 69553 if (pr === pl) { 69554 this.debug('** at the end'); 69555 // a ** at the end will just swallow the rest. 69556 // We have found a match. 69557 // however, it will not swallow /.x, unless 69558 // options.dot is set. 69559 // . and .. are *never* matched by **, for explosively 69560 // exponential reasons. 69561 for (; fi < fl; fi++) { 69562 if (file[fi] === '.' || 69563 file[fi] === '..' || 69564 (!options.dot && file[fi].charAt(0) === '.')) 69565 return false; 69566 } 69567 return true; 69568 } 69569 // ok, let's see if we can swallow whatever we can. 69570 while (fr < fl) { 69571 var swallowee = file[fr]; 69572 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); 69573 // XXX remove this slice. Just pass the start index. 69574 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { 69575 this.debug('globstar found match!', fr, fl, swallowee); 69576 // found a match. 69577 return true; 69578 } 69579 else { 69580 // can't swallow "." or ".." ever. 69581 // can only swallow ".foo" when explicitly asked. 69582 if (swallowee === '.' || 69583 swallowee === '..' || 69584 (!options.dot && swallowee.charAt(0) === '.')) { 69585 this.debug('dot detected!', file, fr, pattern, pr); 69586 break; 69587 } 69588 // ** swallows a segment, and continue. 69589 this.debug('globstar swallow a segment, and continue'); 69590 fr++; 69591 } 69592 } 69593 // no match was found. 69594 // However, in partial mode, we can't say this is necessarily over. 69595 /* c8 ignore start */ 69596 if (partial) { 69597 // ran out of file 69598 this.debug('\n>>> no match, partial?', file, fr, pattern, pr); 69599 if (fr === fl) { 69600 return true; 69601 } 69602 } 69603 /* c8 ignore stop */ 69604 return false; 69605 } 69606 // something other than ** 69607 // non-magic patterns just have to match exactly 69608 // patterns with magic have been turned into regexps. 69609 let hit; 69610 if (typeof p === 'string') { 69611 hit = f === p; 69612 this.debug('string match', p, f, hit); 69613 } 69614 else { 69615 hit = p.test(f); 69616 this.debug('pattern match', p, f, hit); 69617 } 69618 if (!hit) 69619 return false; 69620 } 69621 // Note: ending in / means that we'll get a final "" 69622 // at the end of the pattern. This can only match a 69623 // corresponding "" at the end of the file. 69624 // If the file ends in /, then it can only match a 69625 // a pattern that ends in /, unless the pattern just 69626 // doesn't have any more for it. But, a/b/ should *not* 69627 // match "a/b/*", even though "" matches against the 69628 // [^/]*? pattern, except in partial mode, where it might 69629 // simply not be reached yet. 69630 // However, a/b/ should still satisfy a/* 69631 // now either we fell off the end of the pattern, or we're done. 69632 if (fi === fl && pi === pl) { 69633 // ran out of pattern and filename at the same time. 69634 // an exact hit! 69635 return true; 69636 } 69637 else if (fi === fl) { 69638 // ran out of file, but still had pattern left. 69639 // this is ok if we're doing the match as part of 69640 // a glob fs traversal. 69641 return partial; 69642 } 69643 else if (pi === pl) { 69644 // ran out of pattern, still have file left. 69645 // this is only acceptable if we're on the very last 69646 // empty segment of a file with a trailing slash. 69647 // a/* should match a/b/ 69648 return fi === fl - 1 && file[fi] === ''; 69649 /* c8 ignore start */ 69650 } 69651 else { 69652 // should be unreachable. 69653 throw new Error('wtf?'); 69654 } 69655 /* c8 ignore stop */ 69656 } 69657 braceExpand() { 69658 return (0, exports.braceExpand)(this.pattern, this.options); 69659 } 69660 parse(pattern) { 69661 (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); 69662 const options = this.options; 69663 // shortcuts 69664 if (pattern === '**') 69665 return exports.GLOBSTAR; 69666 if (pattern === '') 69667 return ''; 69668 // far and away, the most common glob pattern parts are 69669 // *, *.*, and *.<ext> Add a fast check method for those. 69670 let m; 69671 let fastTest = null; 69672 if ((m = pattern.match(starRE))) { 69673 fastTest = options.dot ? starTestDot : starTest; 69674 } 69675 else if ((m = pattern.match(starDotExtRE))) { 69676 fastTest = (options.nocase 69677 ? options.dot 69678 ? starDotExtTestNocaseDot 69679 : starDotExtTestNocase 69680 : options.dot 69681 ? starDotExtTestDot 69682 : starDotExtTest)(m[1]); 69683 } 69684 else if ((m = pattern.match(qmarksRE))) { 69685 fastTest = (options.nocase 69686 ? options.dot 69687 ? qmarksTestNocaseDot 69688 : qmarksTestNocase 69689 : options.dot 69690 ? qmarksTestDot 69691 : qmarksTest)(m); 69692 } 69693 else if ((m = pattern.match(starDotStarRE))) { 69694 fastTest = options.dot ? starDotStarTestDot : starDotStarTest; 69695 } 69696 else if ((m = pattern.match(dotStarRE))) { 69697 fastTest = dotStarTest; 69698 } 69699 const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern(); 69700 return fastTest ? Object.assign(re, { test: fastTest }) : re; 69701 } 69702 makeRe() { 69703 if (this.regexp || this.regexp === false) 69704 return this.regexp; 69705 // at this point, this.set is a 2d array of partial 69706 // pattern strings, or "**". 69707 // 69708 // It's better to use .match(). This function shouldn't 69709 // be used, really, but it's pretty convenient sometimes, 69710 // when you just want to work with a regex. 69711 const set = this.set; 69712 if (!set.length) { 69713 this.regexp = false; 69714 return this.regexp; 69715 } 69716 const options = this.options; 69717 const twoStar = options.noglobstar 69718 ? star 69719 : options.dot 69720 ? twoStarDot 69721 : twoStarNoDot; 69722 const flags = new Set(options.nocase ? ['i'] : []); 69723 // regexpify non-globstar patterns 69724 // if ** is only item, then we just do one twoStar 69725 // if ** is first, and there are more, prepend (\/|twoStar\/)? to next 69726 // if ** is last, append (\/twoStar|) to previous 69727 // if ** is in the middle, append (\/|\/twoStar\/) to previous 69728 // then filter out GLOBSTAR symbols 69729 let re = set 69730 .map(pattern => { 69731 const pp = pattern.map(p => { 69732 if (p instanceof RegExp) { 69733 for (const f of p.flags.split('')) 69734 flags.add(f); 69735 } 69736 return typeof p === 'string' 69737 ? regExpEscape(p) 69738 : p === exports.GLOBSTAR 69739 ? exports.GLOBSTAR 69740 : p._src; 69741 }); 69742 pp.forEach((p, i) => { 69743 const next = pp[i + 1]; 69744 const prev = pp[i - 1]; 69745 if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) { 69746 return; 69747 } 69748 if (prev === undefined) { 69749 if (next !== undefined && next !== exports.GLOBSTAR) { 69750 pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next; 69751 } 69752 else { 69753 pp[i] = twoStar; 69754 } 69755 } 69756 else if (next === undefined) { 69757 pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; 69758 } 69759 else if (next !== exports.GLOBSTAR) { 69760 pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next; 69761 pp[i + 1] = exports.GLOBSTAR; 69762 } 69763 }); 69764 return pp.filter(p => p !== exports.GLOBSTAR).join('/'); 69765 }) 69766 .join('|'); 69767 // need to wrap in parens if we had more than one thing with |, 69768 // otherwise only the first will be anchored to ^ and the last to $ 69769 const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']; 69770 // must match entire pattern 69771 // ending in a * or ** will make it less strict. 69772 re = '^' + open + re + close + '$'; 69773 // can match anything, as long as it's not this. 69774 if (this.negate) 69775 re = '^(?!' + re + ').+$'; 69776 try { 69777 this.regexp = new RegExp(re, [...flags].join('')); 69778 /* c8 ignore start */ 69779 } 69780 catch (ex) { 69781 // should be impossible 69782 this.regexp = false; 69783 } 69784 /* c8 ignore stop */ 69785 return this.regexp; 69786 } 69787 slashSplit(p) { 69788 // if p starts with // on windows, we preserve that 69789 // so that UNC paths aren't broken. Otherwise, any number of 69790 // / characters are coalesced into one, unless 69791 // preserveMultipleSlashes is set to true. 69792 if (this.preserveMultipleSlashes) { 69793 return p.split('/'); 69794 } 69795 else if (this.isWindows && /^\/\/[^\/]+/.test(p)) { 69796 // add an extra '' for the one we lose 69797 return ['', ...p.split(/\/+/)]; 69798 } 69799 else { 69800 return p.split(/\/+/); 69801 } 69802 } 69803 match(f, partial = this.partial) { 69804 this.debug('match', f, this.pattern); 69805 // short-circuit in the case of busted things. 69806 // comments, etc. 69807 if (this.comment) { 69808 return false; 69809 } 69810 if (this.empty) { 69811 return f === ''; 69812 } 69813 if (f === '/' && partial) { 69814 return true; 69815 } 69816 const options = this.options; 69817 // windows: need to use /, not \ 69818 if (this.isWindows) { 69819 f = f.split('\\').join('/'); 69820 } 69821 // treat the test path as a set of pathparts. 69822 const ff = this.slashSplit(f); 69823 this.debug(this.pattern, 'split', ff); 69824 // just ONE of the pattern sets in this.set needs to match 69825 // in order for it to be valid. If negating, then just one 69826 // match means that we have failed. 69827 // Either way, return on the first hit. 69828 const set = this.set; 69829 this.debug(this.pattern, 'set', set); 69830 // Find the basename of the path by looking for the last non-empty segment 69831 let filename = ff[ff.length - 1]; 69832 if (!filename) { 69833 for (let i = ff.length - 2; !filename && i >= 0; i--) { 69834 filename = ff[i]; 69835 } 69836 } 69837 for (let i = 0; i < set.length; i++) { 69838 const pattern = set[i]; 69839 let file = ff; 69840 if (options.matchBase && pattern.length === 1) { 69841 file = [filename]; 69842 } 69843 const hit = this.matchOne(file, pattern, partial); 69844 if (hit) { 69845 if (options.flipNegate) { 69846 return true; 69847 } 69848 return !this.negate; 69849 } 69850 } 69851 // didn't get any hits. this is success if it's a negative 69852 // pattern, failure otherwise. 69853 if (options.flipNegate) { 69854 return false; 69855 } 69856 return this.negate; 69857 } 69858 static defaults(def) { 69859 return exports.minimatch.defaults(def).Minimatch; 69860 } 69861 } 69862 exports.Minimatch = Minimatch; 69863 /* c8 ignore start */ 69864 var ast_js_2 = __nccwpck_require__(9262); 69865 Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } })); 69866 var escape_js_2 = __nccwpck_require__(6636); 69867 Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } })); 69868 var unescape_js_2 = __nccwpck_require__(3704); 69869 Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } })); 69870 /* c8 ignore stop */ 69871 exports.minimatch.AST = ast_js_1.AST; 69872 exports.minimatch.Minimatch = Minimatch; 69873 exports.minimatch.escape = escape_js_1.escape; 69874 exports.minimatch.unescape = unescape_js_1.unescape; 69875 //# sourceMappingURL=index.js.map 69876 69877 /***/ }), 69878 69879 /***/ 3704: 69880 /***/ ((__unused_webpack_module, exports) => { 69881 69882 "use strict"; 69883 69884 Object.defineProperty(exports, "__esModule", ({ value: true })); 69885 exports.unescape = void 0; 69886 /** 69887 * Un-escape a string that has been escaped with {@link escape}. 69888 * 69889 * If the {@link windowsPathsNoEscape} option is used, then square-brace 69890 * escapes are removed, but not backslash escapes. For example, it will turn 69891 * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`, 69892 * becuase `\` is a path separator in `windowsPathsNoEscape` mode. 69893 * 69894 * When `windowsPathsNoEscape` is not set, then both brace escapes and 69895 * backslash escapes are removed. 69896 * 69897 * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped 69898 * or unescaped. 69899 */ 69900 const unescape = (s, { windowsPathsNoEscape = false, } = {}) => { 69901 return windowsPathsNoEscape 69902 ? s.replace(/\[([^\/\\])\]/g, '$1') 69903 : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1'); 69904 }; 69905 exports.unescape = unescape; 69906 //# sourceMappingURL=unescape.js.map 69907 69908 /***/ }), 69909 69910 /***/ 4968: 69911 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 69912 69913 "use strict"; 69914 69915 var __importDefault = (this && this.__importDefault) || function (mod) { 69916 return (mod && mod.__esModule) ? mod : { "default": mod }; 69917 }; 69918 Object.defineProperty(exports, "__esModule", ({ value: true })); 69919 exports.Minipass = exports.isWritable = exports.isReadable = exports.isStream = void 0; 69920 const proc = typeof process === 'object' && process 69921 ? process 69922 : { 69923 stdout: null, 69924 stderr: null, 69925 }; 69926 const events_1 = __nccwpck_require__(2361); 69927 const stream_1 = __importDefault(__nccwpck_require__(2781)); 69928 const string_decoder_1 = __nccwpck_require__(1576); 69929 /** 69930 * Return true if the argument is a Minipass stream, Node stream, or something 69931 * else that Minipass can interact with. 69932 */ 69933 const isStream = (s) => !!s && 69934 typeof s === 'object' && 69935 (s instanceof Minipass || 69936 s instanceof stream_1.default || 69937 (0, exports.isReadable)(s) || 69938 (0, exports.isWritable)(s)); 69939 exports.isStream = isStream; 69940 /** 69941 * Return true if the argument is a valid {@link Minipass.Readable} 69942 */ 69943 const isReadable = (s) => !!s && 69944 typeof s === 'object' && 69945 s instanceof events_1.EventEmitter && 69946 typeof s.pipe === 'function' && 69947 // node core Writable streams have a pipe() method, but it throws 69948 s.pipe !== stream_1.default.Writable.prototype.pipe; 69949 exports.isReadable = isReadable; 69950 /** 69951 * Return true if the argument is a valid {@link Minipass.Writable} 69952 */ 69953 const isWritable = (s) => !!s && 69954 typeof s === 'object' && 69955 s instanceof events_1.EventEmitter && 69956 typeof s.write === 'function' && 69957 typeof s.end === 'function'; 69958 exports.isWritable = isWritable; 69959 const EOF = Symbol('EOF'); 69960 const MAYBE_EMIT_END = Symbol('maybeEmitEnd'); 69961 const EMITTED_END = Symbol('emittedEnd'); 69962 const EMITTING_END = Symbol('emittingEnd'); 69963 const EMITTED_ERROR = Symbol('emittedError'); 69964 const CLOSED = Symbol('closed'); 69965 const READ = Symbol('read'); 69966 const FLUSH = Symbol('flush'); 69967 const FLUSHCHUNK = Symbol('flushChunk'); 69968 const ENCODING = Symbol('encoding'); 69969 const DECODER = Symbol('decoder'); 69970 const FLOWING = Symbol('flowing'); 69971 const PAUSED = Symbol('paused'); 69972 const RESUME = Symbol('resume'); 69973 const BUFFER = Symbol('buffer'); 69974 const PIPES = Symbol('pipes'); 69975 const BUFFERLENGTH = Symbol('bufferLength'); 69976 const BUFFERPUSH = Symbol('bufferPush'); 69977 const BUFFERSHIFT = Symbol('bufferShift'); 69978 const OBJECTMODE = Symbol('objectMode'); 69979 // internal event when stream is destroyed 69980 const DESTROYED = Symbol('destroyed'); 69981 // internal event when stream has an error 69982 const ERROR = Symbol('error'); 69983 const EMITDATA = Symbol('emitData'); 69984 const EMITEND = Symbol('emitEnd'); 69985 const EMITEND2 = Symbol('emitEnd2'); 69986 const ASYNC = Symbol('async'); 69987 const ABORT = Symbol('abort'); 69988 const ABORTED = Symbol('aborted'); 69989 const SIGNAL = Symbol('signal'); 69990 const DATALISTENERS = Symbol('dataListeners'); 69991 const DISCARDED = Symbol('discarded'); 69992 const defer = (fn) => Promise.resolve().then(fn); 69993 const nodefer = (fn) => fn(); 69994 const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish'; 69995 const isArrayBufferLike = (b) => b instanceof ArrayBuffer || 69996 (!!b && 69997 typeof b === 'object' && 69998 b.constructor && 69999 b.constructor.name === 'ArrayBuffer' && 70000 b.byteLength >= 0); 70001 const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b); 70002 /** 70003 * Internal class representing a pipe to a destination stream. 70004 * 70005 * @internal 70006 */ 70007 class Pipe { 70008 src; 70009 dest; 70010 opts; 70011 ondrain; 70012 constructor(src, dest, opts) { 70013 this.src = src; 70014 this.dest = dest; 70015 this.opts = opts; 70016 this.ondrain = () => src[RESUME](); 70017 this.dest.on('drain', this.ondrain); 70018 } 70019 unpipe() { 70020 this.dest.removeListener('drain', this.ondrain); 70021 } 70022 // only here for the prototype 70023 /* c8 ignore start */ 70024 proxyErrors(_er) { } 70025 /* c8 ignore stop */ 70026 end() { 70027 this.unpipe(); 70028 if (this.opts.end) 70029 this.dest.end(); 70030 } 70031 } 70032 /** 70033 * Internal class representing a pipe to a destination stream where 70034 * errors are proxied. 70035 * 70036 * @internal 70037 */ 70038 class PipeProxyErrors extends Pipe { 70039 unpipe() { 70040 this.src.removeListener('error', this.proxyErrors); 70041 super.unpipe(); 70042 } 70043 constructor(src, dest, opts) { 70044 super(src, dest, opts); 70045 this.proxyErrors = er => dest.emit('error', er); 70046 src.on('error', this.proxyErrors); 70047 } 70048 } 70049 const isObjectModeOptions = (o) => !!o.objectMode; 70050 const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer'; 70051 /** 70052 * Main export, the Minipass class 70053 * 70054 * `RType` is the type of data emitted, defaults to Buffer 70055 * 70056 * `WType` is the type of data to be written, if RType is buffer or string, 70057 * then any {@link Minipass.ContiguousData} is allowed. 70058 * 70059 * `Events` is the set of event handler signatures that this object 70060 * will emit, see {@link Minipass.Events} 70061 */ 70062 class Minipass extends events_1.EventEmitter { 70063 [FLOWING] = false; 70064 [PAUSED] = false; 70065 [PIPES] = []; 70066 [BUFFER] = []; 70067 [OBJECTMODE]; 70068 [ENCODING]; 70069 [ASYNC]; 70070 [DECODER]; 70071 [EOF] = false; 70072 [EMITTED_END] = false; 70073 [EMITTING_END] = false; 70074 [CLOSED] = false; 70075 [EMITTED_ERROR] = null; 70076 [BUFFERLENGTH] = 0; 70077 [DESTROYED] = false; 70078 [SIGNAL]; 70079 [ABORTED] = false; 70080 [DATALISTENERS] = 0; 70081 [DISCARDED] = false; 70082 /** 70083 * true if the stream can be written 70084 */ 70085 writable = true; 70086 /** 70087 * true if the stream can be read 70088 */ 70089 readable = true; 70090 /** 70091 * If `RType` is Buffer, then options do not need to be provided. 70092 * Otherwise, an options object must be provided to specify either 70093 * {@link Minipass.SharedOptions.objectMode} or 70094 * {@link Minipass.SharedOptions.encoding}, as appropriate. 70095 */ 70096 constructor(...args) { 70097 const options = (args[0] || 70098 {}); 70099 super(); 70100 if (options.objectMode && typeof options.encoding === 'string') { 70101 throw new TypeError('Encoding and objectMode may not be used together'); 70102 } 70103 if (isObjectModeOptions(options)) { 70104 this[OBJECTMODE] = true; 70105 this[ENCODING] = null; 70106 } 70107 else if (isEncodingOptions(options)) { 70108 this[ENCODING] = options.encoding; 70109 this[OBJECTMODE] = false; 70110 } 70111 else { 70112 this[OBJECTMODE] = false; 70113 this[ENCODING] = null; 70114 } 70115 this[ASYNC] = !!options.async; 70116 this[DECODER] = this[ENCODING] 70117 ? new string_decoder_1.StringDecoder(this[ENCODING]) 70118 : null; 70119 //@ts-ignore - private option for debugging and testing 70120 if (options && options.debugExposeBuffer === true) { 70121 Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }); 70122 } 70123 //@ts-ignore - private option for debugging and testing 70124 if (options && options.debugExposePipes === true) { 70125 Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }); 70126 } 70127 const { signal } = options; 70128 if (signal) { 70129 this[SIGNAL] = signal; 70130 if (signal.aborted) { 70131 this[ABORT](); 70132 } 70133 else { 70134 signal.addEventListener('abort', () => this[ABORT]()); 70135 } 70136 } 70137 } 70138 /** 70139 * The amount of data stored in the buffer waiting to be read. 70140 * 70141 * For Buffer strings, this will be the total byte length. 70142 * For string encoding streams, this will be the string character length, 70143 * according to JavaScript's `string.length` logic. 70144 * For objectMode streams, this is a count of the items waiting to be 70145 * emitted. 70146 */ 70147 get bufferLength() { 70148 return this[BUFFERLENGTH]; 70149 } 70150 /** 70151 * The `BufferEncoding` currently in use, or `null` 70152 */ 70153 get encoding() { 70154 return this[ENCODING]; 70155 } 70156 /** 70157 * @deprecated - This is a read only property 70158 */ 70159 set encoding(_enc) { 70160 throw new Error('Encoding must be set at instantiation time'); 70161 } 70162 /** 70163 * @deprecated - Encoding may only be set at instantiation time 70164 */ 70165 setEncoding(_enc) { 70166 throw new Error('Encoding must be set at instantiation time'); 70167 } 70168 /** 70169 * True if this is an objectMode stream 70170 */ 70171 get objectMode() { 70172 return this[OBJECTMODE]; 70173 } 70174 /** 70175 * @deprecated - This is a read-only property 70176 */ 70177 set objectMode(_om) { 70178 throw new Error('objectMode must be set at instantiation time'); 70179 } 70180 /** 70181 * true if this is an async stream 70182 */ 70183 get ['async']() { 70184 return this[ASYNC]; 70185 } 70186 /** 70187 * Set to true to make this stream async. 70188 * 70189 * Once set, it cannot be unset, as this would potentially cause incorrect 70190 * behavior. Ie, a sync stream can be made async, but an async stream 70191 * cannot be safely made sync. 70192 */ 70193 set ['async'](a) { 70194 this[ASYNC] = this[ASYNC] || !!a; 70195 } 70196 // drop everything and get out of the flow completely 70197 [ABORT]() { 70198 this[ABORTED] = true; 70199 this.emit('abort', this[SIGNAL]?.reason); 70200 this.destroy(this[SIGNAL]?.reason); 70201 } 70202 /** 70203 * True if the stream has been aborted. 70204 */ 70205 get aborted() { 70206 return this[ABORTED]; 70207 } 70208 /** 70209 * No-op setter. Stream aborted status is set via the AbortSignal provided 70210 * in the constructor options. 70211 */ 70212 set aborted(_) { } 70213 write(chunk, encoding, cb) { 70214 if (this[ABORTED]) 70215 return false; 70216 if (this[EOF]) 70217 throw new Error('write after end'); 70218 if (this[DESTROYED]) { 70219 this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' })); 70220 return true; 70221 } 70222 if (typeof encoding === 'function') { 70223 cb = encoding; 70224 encoding = 'utf8'; 70225 } 70226 if (!encoding) 70227 encoding = 'utf8'; 70228 const fn = this[ASYNC] ? defer : nodefer; 70229 // convert array buffers and typed array views into buffers 70230 // at some point in the future, we may want to do the opposite! 70231 // leave strings and buffers as-is 70232 // anything is only allowed if in object mode, so throw 70233 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { 70234 if (isArrayBufferView(chunk)) { 70235 //@ts-ignore - sinful unsafe type changing 70236 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); 70237 } 70238 else if (isArrayBufferLike(chunk)) { 70239 //@ts-ignore - sinful unsafe type changing 70240 chunk = Buffer.from(chunk); 70241 } 70242 else if (typeof chunk !== 'string') { 70243 throw new Error('Non-contiguous data written to non-objectMode stream'); 70244 } 70245 } 70246 // handle object mode up front, since it's simpler 70247 // this yields better performance, fewer checks later. 70248 if (this[OBJECTMODE]) { 70249 // maybe impossible? 70250 /* c8 ignore start */ 70251 if (this[FLOWING] && this[BUFFERLENGTH] !== 0) 70252 this[FLUSH](true); 70253 /* c8 ignore stop */ 70254 if (this[FLOWING]) 70255 this.emit('data', chunk); 70256 else 70257 this[BUFFERPUSH](chunk); 70258 if (this[BUFFERLENGTH] !== 0) 70259 this.emit('readable'); 70260 if (cb) 70261 fn(cb); 70262 return this[FLOWING]; 70263 } 70264 // at this point the chunk is a buffer or string 70265 // don't buffer it up or send it to the decoder 70266 if (!chunk.length) { 70267 if (this[BUFFERLENGTH] !== 0) 70268 this.emit('readable'); 70269 if (cb) 70270 fn(cb); 70271 return this[FLOWING]; 70272 } 70273 // fast-path writing strings of same encoding to a stream with 70274 // an empty buffer, skipping the buffer/decoder dance 70275 if (typeof chunk === 'string' && 70276 // unless it is a string already ready for us to use 70277 !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) { 70278 //@ts-ignore - sinful unsafe type change 70279 chunk = Buffer.from(chunk, encoding); 70280 } 70281 if (Buffer.isBuffer(chunk) && this[ENCODING]) { 70282 //@ts-ignore - sinful unsafe type change 70283 chunk = this[DECODER].write(chunk); 70284 } 70285 // Note: flushing CAN potentially switch us into not-flowing mode 70286 if (this[FLOWING] && this[BUFFERLENGTH] !== 0) 70287 this[FLUSH](true); 70288 if (this[FLOWING]) 70289 this.emit('data', chunk); 70290 else 70291 this[BUFFERPUSH](chunk); 70292 if (this[BUFFERLENGTH] !== 0) 70293 this.emit('readable'); 70294 if (cb) 70295 fn(cb); 70296 return this[FLOWING]; 70297 } 70298 /** 70299 * Low-level explicit read method. 70300 * 70301 * In objectMode, the argument is ignored, and one item is returned if 70302 * available. 70303 * 70304 * `n` is the number of bytes (or in the case of encoding streams, 70305 * characters) to consume. If `n` is not provided, then the entire buffer 70306 * is returned, or `null` is returned if no data is available. 70307 * 70308 * If `n` is greater that the amount of data in the internal buffer, 70309 * then `null` is returned. 70310 */ 70311 read(n) { 70312 if (this[DESTROYED]) 70313 return null; 70314 this[DISCARDED] = false; 70315 if (this[BUFFERLENGTH] === 0 || 70316 n === 0 || 70317 (n && n > this[BUFFERLENGTH])) { 70318 this[MAYBE_EMIT_END](); 70319 return null; 70320 } 70321 if (this[OBJECTMODE]) 70322 n = null; 70323 if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { 70324 // not object mode, so if we have an encoding, then RType is string 70325 // otherwise, must be Buffer 70326 this[BUFFER] = [ 70327 (this[ENCODING] 70328 ? this[BUFFER].join('') 70329 : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])), 70330 ]; 70331 } 70332 const ret = this[READ](n || null, this[BUFFER][0]); 70333 this[MAYBE_EMIT_END](); 70334 return ret; 70335 } 70336 [READ](n, chunk) { 70337 if (this[OBJECTMODE]) 70338 this[BUFFERSHIFT](); 70339 else { 70340 const c = chunk; 70341 if (n === c.length || n === null) 70342 this[BUFFERSHIFT](); 70343 else if (typeof c === 'string') { 70344 this[BUFFER][0] = c.slice(n); 70345 chunk = c.slice(0, n); 70346 this[BUFFERLENGTH] -= n; 70347 } 70348 else { 70349 this[BUFFER][0] = c.subarray(n); 70350 chunk = c.subarray(0, n); 70351 this[BUFFERLENGTH] -= n; 70352 } 70353 } 70354 this.emit('data', chunk); 70355 if (!this[BUFFER].length && !this[EOF]) 70356 this.emit('drain'); 70357 return chunk; 70358 } 70359 end(chunk, encoding, cb) { 70360 if (typeof chunk === 'function') { 70361 cb = chunk; 70362 chunk = undefined; 70363 } 70364 if (typeof encoding === 'function') { 70365 cb = encoding; 70366 encoding = 'utf8'; 70367 } 70368 if (chunk !== undefined) 70369 this.write(chunk, encoding); 70370 if (cb) 70371 this.once('end', cb); 70372 this[EOF] = true; 70373 this.writable = false; 70374 // if we haven't written anything, then go ahead and emit, 70375 // even if we're not reading. 70376 // we'll re-emit if a new 'end' listener is added anyway. 70377 // This makes MP more suitable to write-only use cases. 70378 if (this[FLOWING] || !this[PAUSED]) 70379 this[MAYBE_EMIT_END](); 70380 return this; 70381 } 70382 // don't let the internal resume be overwritten 70383 [RESUME]() { 70384 if (this[DESTROYED]) 70385 return; 70386 if (!this[DATALISTENERS] && !this[PIPES].length) { 70387 this[DISCARDED] = true; 70388 } 70389 this[PAUSED] = false; 70390 this[FLOWING] = true; 70391 this.emit('resume'); 70392 if (this[BUFFER].length) 70393 this[FLUSH](); 70394 else if (this[EOF]) 70395 this[MAYBE_EMIT_END](); 70396 else 70397 this.emit('drain'); 70398 } 70399 /** 70400 * Resume the stream if it is currently in a paused state 70401 * 70402 * If called when there are no pipe destinations or `data` event listeners, 70403 * this will place the stream in a "discarded" state, where all data will 70404 * be thrown away. The discarded state is removed if a pipe destination or 70405 * data handler is added, if pause() is called, or if any synchronous or 70406 * asynchronous iteration is started. 70407 */ 70408 resume() { 70409 return this[RESUME](); 70410 } 70411 /** 70412 * Pause the stream 70413 */ 70414 pause() { 70415 this[FLOWING] = false; 70416 this[PAUSED] = true; 70417 this[DISCARDED] = false; 70418 } 70419 /** 70420 * true if the stream has been forcibly destroyed 70421 */ 70422 get destroyed() { 70423 return this[DESTROYED]; 70424 } 70425 /** 70426 * true if the stream is currently in a flowing state, meaning that 70427 * any writes will be immediately emitted. 70428 */ 70429 get flowing() { 70430 return this[FLOWING]; 70431 } 70432 /** 70433 * true if the stream is currently in a paused state 70434 */ 70435 get paused() { 70436 return this[PAUSED]; 70437 } 70438 [BUFFERPUSH](chunk) { 70439 if (this[OBJECTMODE]) 70440 this[BUFFERLENGTH] += 1; 70441 else 70442 this[BUFFERLENGTH] += chunk.length; 70443 this[BUFFER].push(chunk); 70444 } 70445 [BUFFERSHIFT]() { 70446 if (this[OBJECTMODE]) 70447 this[BUFFERLENGTH] -= 1; 70448 else 70449 this[BUFFERLENGTH] -= this[BUFFER][0].length; 70450 return this[BUFFER].shift(); 70451 } 70452 [FLUSH](noDrain = false) { 70453 do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && 70454 this[BUFFER].length); 70455 if (!noDrain && !this[BUFFER].length && !this[EOF]) 70456 this.emit('drain'); 70457 } 70458 [FLUSHCHUNK](chunk) { 70459 this.emit('data', chunk); 70460 return this[FLOWING]; 70461 } 70462 /** 70463 * Pipe all data emitted by this stream into the destination provided. 70464 * 70465 * Triggers the flow of data. 70466 */ 70467 pipe(dest, opts) { 70468 if (this[DESTROYED]) 70469 return dest; 70470 this[DISCARDED] = false; 70471 const ended = this[EMITTED_END]; 70472 opts = opts || {}; 70473 if (dest === proc.stdout || dest === proc.stderr) 70474 opts.end = false; 70475 else 70476 opts.end = opts.end !== false; 70477 opts.proxyErrors = !!opts.proxyErrors; 70478 // piping an ended stream ends immediately 70479 if (ended) { 70480 if (opts.end) 70481 dest.end(); 70482 } 70483 else { 70484 // "as" here just ignores the WType, which pipes don't care about, 70485 // since they're only consuming from us, and writing to the dest 70486 this[PIPES].push(!opts.proxyErrors 70487 ? new Pipe(this, dest, opts) 70488 : new PipeProxyErrors(this, dest, opts)); 70489 if (this[ASYNC]) 70490 defer(() => this[RESUME]()); 70491 else 70492 this[RESUME](); 70493 } 70494 return dest; 70495 } 70496 /** 70497 * Fully unhook a piped destination stream. 70498 * 70499 * If the destination stream was the only consumer of this stream (ie, 70500 * there are no other piped destinations or `'data'` event listeners) 70501 * then the flow of data will stop until there is another consumer or 70502 * {@link Minipass#resume} is explicitly called. 70503 */ 70504 unpipe(dest) { 70505 const p = this[PIPES].find(p => p.dest === dest); 70506 if (p) { 70507 if (this[PIPES].length === 1) { 70508 if (this[FLOWING] && this[DATALISTENERS] === 0) { 70509 this[FLOWING] = false; 70510 } 70511 this[PIPES] = []; 70512 } 70513 else 70514 this[PIPES].splice(this[PIPES].indexOf(p), 1); 70515 p.unpipe(); 70516 } 70517 } 70518 /** 70519 * Alias for {@link Minipass#on} 70520 */ 70521 addListener(ev, handler) { 70522 return this.on(ev, handler); 70523 } 70524 /** 70525 * Mostly identical to `EventEmitter.on`, with the following 70526 * behavior differences to prevent data loss and unnecessary hangs: 70527 * 70528 * - Adding a 'data' event handler will trigger the flow of data 70529 * 70530 * - Adding a 'readable' event handler when there is data waiting to be read 70531 * will cause 'readable' to be emitted immediately. 70532 * 70533 * - Adding an 'endish' event handler ('end', 'finish', etc.) which has 70534 * already passed will cause the event to be emitted immediately and all 70535 * handlers removed. 70536 * 70537 * - Adding an 'error' event handler after an error has been emitted will 70538 * cause the event to be re-emitted immediately with the error previously 70539 * raised. 70540 */ 70541 on(ev, handler) { 70542 const ret = super.on(ev, handler); 70543 if (ev === 'data') { 70544 this[DISCARDED] = false; 70545 this[DATALISTENERS]++; 70546 if (!this[PIPES].length && !this[FLOWING]) { 70547 this[RESUME](); 70548 } 70549 } 70550 else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) { 70551 super.emit('readable'); 70552 } 70553 else if (isEndish(ev) && this[EMITTED_END]) { 70554 super.emit(ev); 70555 this.removeAllListeners(ev); 70556 } 70557 else if (ev === 'error' && this[EMITTED_ERROR]) { 70558 const h = handler; 70559 if (this[ASYNC]) 70560 defer(() => h.call(this, this[EMITTED_ERROR])); 70561 else 70562 h.call(this, this[EMITTED_ERROR]); 70563 } 70564 return ret; 70565 } 70566 /** 70567 * Alias for {@link Minipass#off} 70568 */ 70569 removeListener(ev, handler) { 70570 return this.off(ev, handler); 70571 } 70572 /** 70573 * Mostly identical to `EventEmitter.off` 70574 * 70575 * If a 'data' event handler is removed, and it was the last consumer 70576 * (ie, there are no pipe destinations or other 'data' event listeners), 70577 * then the flow of data will stop until there is another consumer or 70578 * {@link Minipass#resume} is explicitly called. 70579 */ 70580 off(ev, handler) { 70581 const ret = super.off(ev, handler); 70582 // if we previously had listeners, and now we don't, and we don't 70583 // have any pipes, then stop the flow, unless it's been explicitly 70584 // put in a discarded flowing state via stream.resume(). 70585 if (ev === 'data') { 70586 this[DATALISTENERS] = this.listeners('data').length; 70587 if (this[DATALISTENERS] === 0 && 70588 !this[DISCARDED] && 70589 !this[PIPES].length) { 70590 this[FLOWING] = false; 70591 } 70592 } 70593 return ret; 70594 } 70595 /** 70596 * Mostly identical to `EventEmitter.removeAllListeners` 70597 * 70598 * If all 'data' event handlers are removed, and they were the last consumer 70599 * (ie, there are no pipe destinations), then the flow of data will stop 70600 * until there is another consumer or {@link Minipass#resume} is explicitly 70601 * called. 70602 */ 70603 removeAllListeners(ev) { 70604 const ret = super.removeAllListeners(ev); 70605 if (ev === 'data' || ev === undefined) { 70606 this[DATALISTENERS] = 0; 70607 if (!this[DISCARDED] && !this[PIPES].length) { 70608 this[FLOWING] = false; 70609 } 70610 } 70611 return ret; 70612 } 70613 /** 70614 * true if the 'end' event has been emitted 70615 */ 70616 get emittedEnd() { 70617 return this[EMITTED_END]; 70618 } 70619 [MAYBE_EMIT_END]() { 70620 if (!this[EMITTING_END] && 70621 !this[EMITTED_END] && 70622 !this[DESTROYED] && 70623 this[BUFFER].length === 0 && 70624 this[EOF]) { 70625 this[EMITTING_END] = true; 70626 this.emit('end'); 70627 this.emit('prefinish'); 70628 this.emit('finish'); 70629 if (this[CLOSED]) 70630 this.emit('close'); 70631 this[EMITTING_END] = false; 70632 } 70633 } 70634 /** 70635 * Mostly identical to `EventEmitter.emit`, with the following 70636 * behavior differences to prevent data loss and unnecessary hangs: 70637 * 70638 * If the stream has been destroyed, and the event is something other 70639 * than 'close' or 'error', then `false` is returned and no handlers 70640 * are called. 70641 * 70642 * If the event is 'end', and has already been emitted, then the event 70643 * is ignored. If the stream is in a paused or non-flowing state, then 70644 * the event will be deferred until data flow resumes. If the stream is 70645 * async, then handlers will be called on the next tick rather than 70646 * immediately. 70647 * 70648 * If the event is 'close', and 'end' has not yet been emitted, then 70649 * the event will be deferred until after 'end' is emitted. 70650 * 70651 * If the event is 'error', and an AbortSignal was provided for the stream, 70652 * and there are no listeners, then the event is ignored, matching the 70653 * behavior of node core streams in the presense of an AbortSignal. 70654 * 70655 * If the event is 'finish' or 'prefinish', then all listeners will be 70656 * removed after emitting the event, to prevent double-firing. 70657 */ 70658 emit(ev, ...args) { 70659 const data = args[0]; 70660 // error and close are only events allowed after calling destroy() 70661 if (ev !== 'error' && 70662 ev !== 'close' && 70663 ev !== DESTROYED && 70664 this[DESTROYED]) { 70665 return false; 70666 } 70667 else if (ev === 'data') { 70668 return !this[OBJECTMODE] && !data 70669 ? false 70670 : this[ASYNC] 70671 ? (defer(() => this[EMITDATA](data)), true) 70672 : this[EMITDATA](data); 70673 } 70674 else if (ev === 'end') { 70675 return this[EMITEND](); 70676 } 70677 else if (ev === 'close') { 70678 this[CLOSED] = true; 70679 // don't emit close before 'end' and 'finish' 70680 if (!this[EMITTED_END] && !this[DESTROYED]) 70681 return false; 70682 const ret = super.emit('close'); 70683 this.removeAllListeners('close'); 70684 return ret; 70685 } 70686 else if (ev === 'error') { 70687 this[EMITTED_ERROR] = data; 70688 super.emit(ERROR, data); 70689 const ret = !this[SIGNAL] || this.listeners('error').length 70690 ? super.emit('error', data) 70691 : false; 70692 this[MAYBE_EMIT_END](); 70693 return ret; 70694 } 70695 else if (ev === 'resume') { 70696 const ret = super.emit('resume'); 70697 this[MAYBE_EMIT_END](); 70698 return ret; 70699 } 70700 else if (ev === 'finish' || ev === 'prefinish') { 70701 const ret = super.emit(ev); 70702 this.removeAllListeners(ev); 70703 return ret; 70704 } 70705 // Some other unknown event 70706 const ret = super.emit(ev, ...args); 70707 this[MAYBE_EMIT_END](); 70708 return ret; 70709 } 70710 [EMITDATA](data) { 70711 for (const p of this[PIPES]) { 70712 if (p.dest.write(data) === false) 70713 this.pause(); 70714 } 70715 const ret = this[DISCARDED] ? false : super.emit('data', data); 70716 this[MAYBE_EMIT_END](); 70717 return ret; 70718 } 70719 [EMITEND]() { 70720 if (this[EMITTED_END]) 70721 return false; 70722 this[EMITTED_END] = true; 70723 this.readable = false; 70724 return this[ASYNC] 70725 ? (defer(() => this[EMITEND2]()), true) 70726 : this[EMITEND2](); 70727 } 70728 [EMITEND2]() { 70729 if (this[DECODER]) { 70730 const data = this[DECODER].end(); 70731 if (data) { 70732 for (const p of this[PIPES]) { 70733 p.dest.write(data); 70734 } 70735 if (!this[DISCARDED]) 70736 super.emit('data', data); 70737 } 70738 } 70739 for (const p of this[PIPES]) { 70740 p.end(); 70741 } 70742 const ret = super.emit('end'); 70743 this.removeAllListeners('end'); 70744 return ret; 70745 } 70746 /** 70747 * Return a Promise that resolves to an array of all emitted data once 70748 * the stream ends. 70749 */ 70750 async collect() { 70751 const buf = Object.assign([], { 70752 dataLength: 0, 70753 }); 70754 if (!this[OBJECTMODE]) 70755 buf.dataLength = 0; 70756 // set the promise first, in case an error is raised 70757 // by triggering the flow here. 70758 const p = this.promise(); 70759 this.on('data', c => { 70760 buf.push(c); 70761 if (!this[OBJECTMODE]) 70762 buf.dataLength += c.length; 70763 }); 70764 await p; 70765 return buf; 70766 } 70767 /** 70768 * Return a Promise that resolves to the concatenation of all emitted data 70769 * once the stream ends. 70770 * 70771 * Not allowed on objectMode streams. 70772 */ 70773 async concat() { 70774 if (this[OBJECTMODE]) { 70775 throw new Error('cannot concat in objectMode'); 70776 } 70777 const buf = await this.collect(); 70778 return (this[ENCODING] 70779 ? buf.join('') 70780 : Buffer.concat(buf, buf.dataLength)); 70781 } 70782 /** 70783 * Return a void Promise that resolves once the stream ends. 70784 */ 70785 async promise() { 70786 return new Promise((resolve, reject) => { 70787 this.on(DESTROYED, () => reject(new Error('stream destroyed'))); 70788 this.on('error', er => reject(er)); 70789 this.on('end', () => resolve()); 70790 }); 70791 } 70792 /** 70793 * Asynchronous `for await of` iteration. 70794 * 70795 * This will continue emitting all chunks until the stream terminates. 70796 */ 70797 [Symbol.asyncIterator]() { 70798 // set this up front, in case the consumer doesn't call next() 70799 // right away. 70800 this[DISCARDED] = false; 70801 let stopped = false; 70802 const stop = async () => { 70803 this.pause(); 70804 stopped = true; 70805 return { value: undefined, done: true }; 70806 }; 70807 const next = () => { 70808 if (stopped) 70809 return stop(); 70810 const res = this.read(); 70811 if (res !== null) 70812 return Promise.resolve({ done: false, value: res }); 70813 if (this[EOF]) 70814 return stop(); 70815 let resolve; 70816 let reject; 70817 const onerr = (er) => { 70818 this.off('data', ondata); 70819 this.off('end', onend); 70820 this.off(DESTROYED, ondestroy); 70821 stop(); 70822 reject(er); 70823 }; 70824 const ondata = (value) => { 70825 this.off('error', onerr); 70826 this.off('end', onend); 70827 this.off(DESTROYED, ondestroy); 70828 this.pause(); 70829 resolve({ value, done: !!this[EOF] }); 70830 }; 70831 const onend = () => { 70832 this.off('error', onerr); 70833 this.off('data', ondata); 70834 this.off(DESTROYED, ondestroy); 70835 stop(); 70836 resolve({ done: true, value: undefined }); 70837 }; 70838 const ondestroy = () => onerr(new Error('stream destroyed')); 70839 return new Promise((res, rej) => { 70840 reject = rej; 70841 resolve = res; 70842 this.once(DESTROYED, ondestroy); 70843 this.once('error', onerr); 70844 this.once('end', onend); 70845 this.once('data', ondata); 70846 }); 70847 }; 70848 return { 70849 next, 70850 throw: stop, 70851 return: stop, 70852 [Symbol.asyncIterator]() { 70853 return this; 70854 }, 70855 }; 70856 } 70857 /** 70858 * Synchronous `for of` iteration. 70859 * 70860 * The iteration will terminate when the internal buffer runs out, even 70861 * if the stream has not yet terminated. 70862 */ 70863 [Symbol.iterator]() { 70864 // set this up front, in case the consumer doesn't call next() 70865 // right away. 70866 this[DISCARDED] = false; 70867 let stopped = false; 70868 const stop = () => { 70869 this.pause(); 70870 this.off(ERROR, stop); 70871 this.off(DESTROYED, stop); 70872 this.off('end', stop); 70873 stopped = true; 70874 return { done: true, value: undefined }; 70875 }; 70876 const next = () => { 70877 if (stopped) 70878 return stop(); 70879 const value = this.read(); 70880 return value === null ? stop() : { done: false, value }; 70881 }; 70882 this.once('end', stop); 70883 this.once(ERROR, stop); 70884 this.once(DESTROYED, stop); 70885 return { 70886 next, 70887 throw: stop, 70888 return: stop, 70889 [Symbol.iterator]() { 70890 return this; 70891 }, 70892 }; 70893 } 70894 /** 70895 * Destroy a stream, preventing it from being used for any further purpose. 70896 * 70897 * If the stream has a `close()` method, then it will be called on 70898 * destruction. 70899 * 70900 * After destruction, any attempt to write data, read data, or emit most 70901 * events will be ignored. 70902 * 70903 * If an error argument is provided, then it will be emitted in an 70904 * 'error' event. 70905 */ 70906 destroy(er) { 70907 if (this[DESTROYED]) { 70908 if (er) 70909 this.emit('error', er); 70910 else 70911 this.emit(DESTROYED); 70912 return this; 70913 } 70914 this[DESTROYED] = true; 70915 this[DISCARDED] = true; 70916 // throw away all buffered data, it's never coming out 70917 this[BUFFER].length = 0; 70918 this[BUFFERLENGTH] = 0; 70919 const wc = this; 70920 if (typeof wc.close === 'function' && !this[CLOSED]) 70921 wc.close(); 70922 if (er) 70923 this.emit('error', er); 70924 // if no error to emit, still reject pending promises 70925 else 70926 this.emit(DESTROYED); 70927 return this; 70928 } 70929 /** 70930 * Alias for {@link isStream} 70931 * 70932 * Former export location, maintained for backwards compatibility. 70933 * 70934 * @deprecated 70935 */ 70936 static get isStream() { 70937 return exports.isStream; 70938 } 70939 } 70940 exports.Minipass = Minipass; 70941 //# sourceMappingURL=index.js.map 70942 70943 /***/ }), 70944 70945 /***/ 1081: 70946 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 70947 70948 "use strict"; 70949 70950 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 70951 if (k2 === undefined) k2 = k; 70952 var desc = Object.getOwnPropertyDescriptor(m, k); 70953 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 70954 desc = { enumerable: true, get: function() { return m[k]; } }; 70955 } 70956 Object.defineProperty(o, k2, desc); 70957 }) : (function(o, m, k, k2) { 70958 if (k2 === undefined) k2 = k; 70959 o[k2] = m[k]; 70960 })); 70961 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 70962 Object.defineProperty(o, "default", { enumerable: true, value: v }); 70963 }) : function(o, v) { 70964 o["default"] = v; 70965 }); 70966 var __importStar = (this && this.__importStar) || function (mod) { 70967 if (mod && mod.__esModule) return mod; 70968 var result = {}; 70969 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 70970 __setModuleDefault(result, mod); 70971 return result; 70972 }; 70973 Object.defineProperty(exports, "__esModule", ({ value: true })); 70974 exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = void 0; 70975 const lru_cache_1 = __nccwpck_require__(6091); 70976 const path_1 = __nccwpck_require__(1017); 70977 const url_1 = __nccwpck_require__(7310); 70978 const actualFS = __importStar(__nccwpck_require__(7147)); 70979 const fs_1 = __nccwpck_require__(7147); 70980 const realpathSync = fs_1.realpathSync.native; 70981 // TODO: test perf of fs/promises realpath vs realpathCB, 70982 // since the promises one uses realpath.native 70983 const promises_1 = __nccwpck_require__(3292); 70984 const minipass_1 = __nccwpck_require__(4968); 70985 const defaultFS = { 70986 lstatSync: fs_1.lstatSync, 70987 readdir: fs_1.readdir, 70988 readdirSync: fs_1.readdirSync, 70989 readlinkSync: fs_1.readlinkSync, 70990 realpathSync, 70991 promises: { 70992 lstat: promises_1.lstat, 70993 readdir: promises_1.readdir, 70994 readlink: promises_1.readlink, 70995 realpath: promises_1.realpath, 70996 }, 70997 }; 70998 // if they just gave us require('fs') then use our default 70999 const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS 71000 ? defaultFS 71001 : { 71002 ...defaultFS, 71003 ...fsOption, 71004 promises: { 71005 ...defaultFS.promises, 71006 ...(fsOption.promises || {}), 71007 }, 71008 }; 71009 // turn something like //?/c:/ into c:\ 71010 const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i; 71011 const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\'); 71012 // windows paths are separated by either / or \ 71013 const eitherSep = /[\\\/]/; 71014 const UNKNOWN = 0; // may not even exist, for all we know 71015 const IFIFO = 0b0001; 71016 const IFCHR = 0b0010; 71017 const IFDIR = 0b0100; 71018 const IFBLK = 0b0110; 71019 const IFREG = 0b1000; 71020 const IFLNK = 0b1010; 71021 const IFSOCK = 0b1100; 71022 const IFMT = 0b1111; 71023 // mask to unset low 4 bits 71024 const IFMT_UNKNOWN = ~IFMT; 71025 // set after successfully calling readdir() and getting entries. 71026 const READDIR_CALLED = 0b0000_0001_0000; 71027 // set after a successful lstat() 71028 const LSTAT_CALLED = 0b0000_0010_0000; 71029 // set if an entry (or one of its parents) is definitely not a dir 71030 const ENOTDIR = 0b0000_0100_0000; 71031 // set if an entry (or one of its parents) does not exist 71032 // (can also be set on lstat errors like EACCES or ENAMETOOLONG) 71033 const ENOENT = 0b0000_1000_0000; 71034 // cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK 71035 // set if we fail to readlink 71036 const ENOREADLINK = 0b0001_0000_0000; 71037 // set if we know realpath() will fail 71038 const ENOREALPATH = 0b0010_0000_0000; 71039 const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH; 71040 const TYPEMASK = 0b0011_1111_1111; 71041 const entToType = (s) => s.isFile() 71042 ? IFREG 71043 : s.isDirectory() 71044 ? IFDIR 71045 : s.isSymbolicLink() 71046 ? IFLNK 71047 : s.isCharacterDevice() 71048 ? IFCHR 71049 : s.isBlockDevice() 71050 ? IFBLK 71051 : s.isSocket() 71052 ? IFSOCK 71053 : s.isFIFO() 71054 ? IFIFO 71055 : UNKNOWN; 71056 // normalize unicode path names 71057 const normalizeCache = new Map(); 71058 const normalize = (s) => { 71059 const c = normalizeCache.get(s); 71060 if (c) 71061 return c; 71062 const n = s.normalize('NFKD'); 71063 normalizeCache.set(s, n); 71064 return n; 71065 }; 71066 const normalizeNocaseCache = new Map(); 71067 const normalizeNocase = (s) => { 71068 const c = normalizeNocaseCache.get(s); 71069 if (c) 71070 return c; 71071 const n = normalize(s.toLowerCase()); 71072 normalizeNocaseCache.set(s, n); 71073 return n; 71074 }; 71075 /** 71076 * An LRUCache for storing resolved path strings or Path objects. 71077 * @internal 71078 */ 71079 class ResolveCache extends lru_cache_1.LRUCache { 71080 constructor() { 71081 super({ max: 256 }); 71082 } 71083 } 71084 exports.ResolveCache = ResolveCache; 71085 // In order to prevent blowing out the js heap by allocating hundreds of 71086 // thousands of Path entries when walking extremely large trees, the "children" 71087 // in this tree are represented by storing an array of Path entries in an 71088 // LRUCache, indexed by the parent. At any time, Path.children() may return an 71089 // empty array, indicating that it doesn't know about any of its children, and 71090 // thus has to rebuild that cache. This is fine, it just means that we don't 71091 // benefit as much from having the cached entries, but huge directory walks 71092 // don't blow out the stack, and smaller ones are still as fast as possible. 71093 // 71094 //It does impose some complexity when building up the readdir data, because we 71095 //need to pass a reference to the children array that we started with. 71096 /** 71097 * an LRUCache for storing child entries. 71098 * @internal 71099 */ 71100 class ChildrenCache extends lru_cache_1.LRUCache { 71101 constructor(maxSize = 16 * 1024) { 71102 super({ 71103 maxSize, 71104 // parent + children 71105 sizeCalculation: a => a.length + 1, 71106 }); 71107 } 71108 } 71109 exports.ChildrenCache = ChildrenCache; 71110 const setAsCwd = Symbol('PathScurry setAsCwd'); 71111 /** 71112 * Path objects are sort of like a super-powered 71113 * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} 71114 * 71115 * Each one represents a single filesystem entry on disk, which may or may not 71116 * exist. It includes methods for reading various types of information via 71117 * lstat, readlink, and readdir, and caches all information to the greatest 71118 * degree possible. 71119 * 71120 * Note that fs operations that would normally throw will instead return an 71121 * "empty" value. This is in order to prevent excessive overhead from error 71122 * stack traces. 71123 */ 71124 class PathBase { 71125 /** 71126 * the basename of this path 71127 * 71128 * **Important**: *always* test the path name against any test string 71129 * usingthe {@link isNamed} method, and not by directly comparing this 71130 * string. Otherwise, unicode path strings that the system sees as identical 71131 * will not be properly treated as the same path, leading to incorrect 71132 * behavior and possible security issues. 71133 */ 71134 name; 71135 /** 71136 * the Path entry corresponding to the path root. 71137 * 71138 * @internal 71139 */ 71140 root; 71141 /** 71142 * All roots found within the current PathScurry family 71143 * 71144 * @internal 71145 */ 71146 roots; 71147 /** 71148 * a reference to the parent path, or undefined in the case of root entries 71149 * 71150 * @internal 71151 */ 71152 parent; 71153 /** 71154 * boolean indicating whether paths are compared case-insensitively 71155 * @internal 71156 */ 71157 nocase; 71158 // potential default fs override 71159 #fs; 71160 // Stats fields 71161 #dev; 71162 get dev() { 71163 return this.#dev; 71164 } 71165 #mode; 71166 get mode() { 71167 return this.#mode; 71168 } 71169 #nlink; 71170 get nlink() { 71171 return this.#nlink; 71172 } 71173 #uid; 71174 get uid() { 71175 return this.#uid; 71176 } 71177 #gid; 71178 get gid() { 71179 return this.#gid; 71180 } 71181 #rdev; 71182 get rdev() { 71183 return this.#rdev; 71184 } 71185 #blksize; 71186 get blksize() { 71187 return this.#blksize; 71188 } 71189 #ino; 71190 get ino() { 71191 return this.#ino; 71192 } 71193 #size; 71194 get size() { 71195 return this.#size; 71196 } 71197 #blocks; 71198 get blocks() { 71199 return this.#blocks; 71200 } 71201 #atimeMs; 71202 get atimeMs() { 71203 return this.#atimeMs; 71204 } 71205 #mtimeMs; 71206 get mtimeMs() { 71207 return this.#mtimeMs; 71208 } 71209 #ctimeMs; 71210 get ctimeMs() { 71211 return this.#ctimeMs; 71212 } 71213 #birthtimeMs; 71214 get birthtimeMs() { 71215 return this.#birthtimeMs; 71216 } 71217 #atime; 71218 get atime() { 71219 return this.#atime; 71220 } 71221 #mtime; 71222 get mtime() { 71223 return this.#mtime; 71224 } 71225 #ctime; 71226 get ctime() { 71227 return this.#ctime; 71228 } 71229 #birthtime; 71230 get birthtime() { 71231 return this.#birthtime; 71232 } 71233 #matchName; 71234 #depth; 71235 #fullpath; 71236 #fullpathPosix; 71237 #relative; 71238 #relativePosix; 71239 #type; 71240 #children; 71241 #linkTarget; 71242 #realpath; 71243 /** 71244 * This property is for compatibility with the Dirent class as of 71245 * Node v20, where Dirent['path'] refers to the path of the directory 71246 * that was passed to readdir. So, somewhat counterintuitively, this 71247 * property refers to the *parent* path, not the path object itself. 71248 * For root entries, it's the path to the entry itself. 71249 */ 71250 get path() { 71251 return (this.parent || this).fullpath(); 71252 } 71253 /** 71254 * Do not create new Path objects directly. They should always be accessed 71255 * via the PathScurry class or other methods on the Path class. 71256 * 71257 * @internal 71258 */ 71259 constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { 71260 this.name = name; 71261 this.#matchName = nocase ? normalizeNocase(name) : normalize(name); 71262 this.#type = type & TYPEMASK; 71263 this.nocase = nocase; 71264 this.roots = roots; 71265 this.root = root || this; 71266 this.#children = children; 71267 this.#fullpath = opts.fullpath; 71268 this.#relative = opts.relative; 71269 this.#relativePosix = opts.relativePosix; 71270 this.parent = opts.parent; 71271 if (this.parent) { 71272 this.#fs = this.parent.#fs; 71273 } 71274 else { 71275 this.#fs = fsFromOption(opts.fs); 71276 } 71277 } 71278 /** 71279 * Returns the depth of the Path object from its root. 71280 * 71281 * For example, a path at `/foo/bar` would have a depth of 2. 71282 */ 71283 depth() { 71284 if (this.#depth !== undefined) 71285 return this.#depth; 71286 if (!this.parent) 71287 return (this.#depth = 0); 71288 return (this.#depth = this.parent.depth() + 1); 71289 } 71290 /** 71291 * @internal 71292 */ 71293 childrenCache() { 71294 return this.#children; 71295 } 71296 /** 71297 * Get the Path object referenced by the string path, resolved from this Path 71298 */ 71299 resolve(path) { 71300 if (!path) { 71301 return this; 71302 } 71303 const rootPath = this.getRootString(path); 71304 const dir = path.substring(rootPath.length); 71305 const dirParts = dir.split(this.splitSep); 71306 const result = rootPath 71307 ? this.getRoot(rootPath).#resolveParts(dirParts) 71308 : this.#resolveParts(dirParts); 71309 return result; 71310 } 71311 #resolveParts(dirParts) { 71312 let p = this; 71313 for (const part of dirParts) { 71314 p = p.child(part); 71315 } 71316 return p; 71317 } 71318 /** 71319 * Returns the cached children Path objects, if still available. If they 71320 * have fallen out of the cache, then returns an empty array, and resets the 71321 * READDIR_CALLED bit, so that future calls to readdir() will require an fs 71322 * lookup. 71323 * 71324 * @internal 71325 */ 71326 children() { 71327 const cached = this.#children.get(this); 71328 if (cached) { 71329 return cached; 71330 } 71331 const children = Object.assign([], { provisional: 0 }); 71332 this.#children.set(this, children); 71333 this.#type &= ~READDIR_CALLED; 71334 return children; 71335 } 71336 /** 71337 * Resolves a path portion and returns or creates the child Path. 71338 * 71339 * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is 71340 * `'..'`. 71341 * 71342 * This should not be called directly. If `pathPart` contains any path 71343 * separators, it will lead to unsafe undefined behavior. 71344 * 71345 * Use `Path.resolve()` instead. 71346 * 71347 * @internal 71348 */ 71349 child(pathPart, opts) { 71350 if (pathPart === '' || pathPart === '.') { 71351 return this; 71352 } 71353 if (pathPart === '..') { 71354 return this.parent || this; 71355 } 71356 // find the child 71357 const children = this.children(); 71358 const name = this.nocase 71359 ? normalizeNocase(pathPart) 71360 : normalize(pathPart); 71361 for (const p of children) { 71362 if (p.#matchName === name) { 71363 return p; 71364 } 71365 } 71366 // didn't find it, create provisional child, since it might not 71367 // actually exist. If we know the parent isn't a dir, then 71368 // in fact it CAN'T exist. 71369 const s = this.parent ? this.sep : ''; 71370 const fullpath = this.#fullpath 71371 ? this.#fullpath + s + pathPart 71372 : undefined; 71373 const pchild = this.newChild(pathPart, UNKNOWN, { 71374 ...opts, 71375 parent: this, 71376 fullpath, 71377 }); 71378 if (!this.canReaddir()) { 71379 pchild.#type |= ENOENT; 71380 } 71381 // don't have to update provisional, because if we have real children, 71382 // then provisional is set to children.length, otherwise a lower number 71383 children.push(pchild); 71384 return pchild; 71385 } 71386 /** 71387 * The relative path from the cwd. If it does not share an ancestor with 71388 * the cwd, then this ends up being equivalent to the fullpath() 71389 */ 71390 relative() { 71391 if (this.#relative !== undefined) { 71392 return this.#relative; 71393 } 71394 const name = this.name; 71395 const p = this.parent; 71396 if (!p) { 71397 return (this.#relative = this.name); 71398 } 71399 const pv = p.relative(); 71400 return pv + (!pv || !p.parent ? '' : this.sep) + name; 71401 } 71402 /** 71403 * The relative path from the cwd, using / as the path separator. 71404 * If it does not share an ancestor with 71405 * the cwd, then this ends up being equivalent to the fullpathPosix() 71406 * On posix systems, this is identical to relative(). 71407 */ 71408 relativePosix() { 71409 if (this.sep === '/') 71410 return this.relative(); 71411 if (this.#relativePosix !== undefined) 71412 return this.#relativePosix; 71413 const name = this.name; 71414 const p = this.parent; 71415 if (!p) { 71416 return (this.#relativePosix = this.fullpathPosix()); 71417 } 71418 const pv = p.relativePosix(); 71419 return pv + (!pv || !p.parent ? '' : '/') + name; 71420 } 71421 /** 71422 * The fully resolved path string for this Path entry 71423 */ 71424 fullpath() { 71425 if (this.#fullpath !== undefined) { 71426 return this.#fullpath; 71427 } 71428 const name = this.name; 71429 const p = this.parent; 71430 if (!p) { 71431 return (this.#fullpath = this.name); 71432 } 71433 const pv = p.fullpath(); 71434 const fp = pv + (!p.parent ? '' : this.sep) + name; 71435 return (this.#fullpath = fp); 71436 } 71437 /** 71438 * On platforms other than windows, this is identical to fullpath. 71439 * 71440 * On windows, this is overridden to return the forward-slash form of the 71441 * full UNC path. 71442 */ 71443 fullpathPosix() { 71444 if (this.#fullpathPosix !== undefined) 71445 return this.#fullpathPosix; 71446 if (this.sep === '/') 71447 return (this.#fullpathPosix = this.fullpath()); 71448 if (!this.parent) { 71449 const p = this.fullpath().replace(/\\/g, '/'); 71450 if (/^[a-z]:\//i.test(p)) { 71451 return (this.#fullpathPosix = `//?/${p}`); 71452 } 71453 else { 71454 return (this.#fullpathPosix = p); 71455 } 71456 } 71457 const p = this.parent; 71458 const pfpp = p.fullpathPosix(); 71459 const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name; 71460 return (this.#fullpathPosix = fpp); 71461 } 71462 /** 71463 * Is the Path of an unknown type? 71464 * 71465 * Note that we might know *something* about it if there has been a previous 71466 * filesystem operation, for example that it does not exist, or is not a 71467 * link, or whether it has child entries. 71468 */ 71469 isUnknown() { 71470 return (this.#type & IFMT) === UNKNOWN; 71471 } 71472 isType(type) { 71473 return this[`is${type}`](); 71474 } 71475 getType() { 71476 return this.isUnknown() 71477 ? 'Unknown' 71478 : this.isDirectory() 71479 ? 'Directory' 71480 : this.isFile() 71481 ? 'File' 71482 : this.isSymbolicLink() 71483 ? 'SymbolicLink' 71484 : this.isFIFO() 71485 ? 'FIFO' 71486 : this.isCharacterDevice() 71487 ? 'CharacterDevice' 71488 : this.isBlockDevice() 71489 ? 'BlockDevice' 71490 : /* c8 ignore start */ this.isSocket() 71491 ? 'Socket' 71492 : 'Unknown'; 71493 /* c8 ignore stop */ 71494 } 71495 /** 71496 * Is the Path a regular file? 71497 */ 71498 isFile() { 71499 return (this.#type & IFMT) === IFREG; 71500 } 71501 /** 71502 * Is the Path a directory? 71503 */ 71504 isDirectory() { 71505 return (this.#type & IFMT) === IFDIR; 71506 } 71507 /** 71508 * Is the path a character device? 71509 */ 71510 isCharacterDevice() { 71511 return (this.#type & IFMT) === IFCHR; 71512 } 71513 /** 71514 * Is the path a block device? 71515 */ 71516 isBlockDevice() { 71517 return (this.#type & IFMT) === IFBLK; 71518 } 71519 /** 71520 * Is the path a FIFO pipe? 71521 */ 71522 isFIFO() { 71523 return (this.#type & IFMT) === IFIFO; 71524 } 71525 /** 71526 * Is the path a socket? 71527 */ 71528 isSocket() { 71529 return (this.#type & IFMT) === IFSOCK; 71530 } 71531 /** 71532 * Is the path a symbolic link? 71533 */ 71534 isSymbolicLink() { 71535 return (this.#type & IFLNK) === IFLNK; 71536 } 71537 /** 71538 * Return the entry if it has been subject of a successful lstat, or 71539 * undefined otherwise. 71540 * 71541 * Does not read the filesystem, so an undefined result *could* simply 71542 * mean that we haven't called lstat on it. 71543 */ 71544 lstatCached() { 71545 return this.#type & LSTAT_CALLED ? this : undefined; 71546 } 71547 /** 71548 * Return the cached link target if the entry has been the subject of a 71549 * successful readlink, or undefined otherwise. 71550 * 71551 * Does not read the filesystem, so an undefined result *could* just mean we 71552 * don't have any cached data. Only use it if you are very sure that a 71553 * readlink() has been called at some point. 71554 */ 71555 readlinkCached() { 71556 return this.#linkTarget; 71557 } 71558 /** 71559 * Returns the cached realpath target if the entry has been the subject 71560 * of a successful realpath, or undefined otherwise. 71561 * 71562 * Does not read the filesystem, so an undefined result *could* just mean we 71563 * don't have any cached data. Only use it if you are very sure that a 71564 * realpath() has been called at some point. 71565 */ 71566 realpathCached() { 71567 return this.#realpath; 71568 } 71569 /** 71570 * Returns the cached child Path entries array if the entry has been the 71571 * subject of a successful readdir(), or [] otherwise. 71572 * 71573 * Does not read the filesystem, so an empty array *could* just mean we 71574 * don't have any cached data. Only use it if you are very sure that a 71575 * readdir() has been called recently enough to still be valid. 71576 */ 71577 readdirCached() { 71578 const children = this.children(); 71579 return children.slice(0, children.provisional); 71580 } 71581 /** 71582 * Return true if it's worth trying to readlink. Ie, we don't (yet) have 71583 * any indication that readlink will definitely fail. 71584 * 71585 * Returns false if the path is known to not be a symlink, if a previous 71586 * readlink failed, or if the entry does not exist. 71587 */ 71588 canReadlink() { 71589 if (this.#linkTarget) 71590 return true; 71591 if (!this.parent) 71592 return false; 71593 // cases where it cannot possibly succeed 71594 const ifmt = this.#type & IFMT; 71595 return !((ifmt !== UNKNOWN && ifmt !== IFLNK) || 71596 this.#type & ENOREADLINK || 71597 this.#type & ENOENT); 71598 } 71599 /** 71600 * Return true if readdir has previously been successfully called on this 71601 * path, indicating that cachedReaddir() is likely valid. 71602 */ 71603 calledReaddir() { 71604 return !!(this.#type & READDIR_CALLED); 71605 } 71606 /** 71607 * Returns true if the path is known to not exist. That is, a previous lstat 71608 * or readdir failed to verify its existence when that would have been 71609 * expected, or a parent entry was marked either enoent or enotdir. 71610 */ 71611 isENOENT() { 71612 return !!(this.#type & ENOENT); 71613 } 71614 /** 71615 * Return true if the path is a match for the given path name. This handles 71616 * case sensitivity and unicode normalization. 71617 * 71618 * Note: even on case-sensitive systems, it is **not** safe to test the 71619 * equality of the `.name` property to determine whether a given pathname 71620 * matches, due to unicode normalization mismatches. 71621 * 71622 * Always use this method instead of testing the `path.name` property 71623 * directly. 71624 */ 71625 isNamed(n) { 71626 return !this.nocase 71627 ? this.#matchName === normalize(n) 71628 : this.#matchName === normalizeNocase(n); 71629 } 71630 /** 71631 * Return the Path object corresponding to the target of a symbolic link. 71632 * 71633 * If the Path is not a symbolic link, or if the readlink call fails for any 71634 * reason, `undefined` is returned. 71635 * 71636 * Result is cached, and thus may be outdated if the filesystem is mutated. 71637 */ 71638 async readlink() { 71639 const target = this.#linkTarget; 71640 if (target) { 71641 return target; 71642 } 71643 if (!this.canReadlink()) { 71644 return undefined; 71645 } 71646 /* c8 ignore start */ 71647 // already covered by the canReadlink test, here for ts grumples 71648 if (!this.parent) { 71649 return undefined; 71650 } 71651 /* c8 ignore stop */ 71652 try { 71653 const read = await this.#fs.promises.readlink(this.fullpath()); 71654 const linkTarget = (await this.parent.realpath())?.resolve(read); 71655 if (linkTarget) { 71656 return (this.#linkTarget = linkTarget); 71657 } 71658 } 71659 catch (er) { 71660 this.#readlinkFail(er.code); 71661 return undefined; 71662 } 71663 } 71664 /** 71665 * Synchronous {@link PathBase.readlink} 71666 */ 71667 readlinkSync() { 71668 const target = this.#linkTarget; 71669 if (target) { 71670 return target; 71671 } 71672 if (!this.canReadlink()) { 71673 return undefined; 71674 } 71675 /* c8 ignore start */ 71676 // already covered by the canReadlink test, here for ts grumples 71677 if (!this.parent) { 71678 return undefined; 71679 } 71680 /* c8 ignore stop */ 71681 try { 71682 const read = this.#fs.readlinkSync(this.fullpath()); 71683 const linkTarget = (this.parent.realpathSync())?.resolve(read); 71684 if (linkTarget) { 71685 return (this.#linkTarget = linkTarget); 71686 } 71687 } 71688 catch (er) { 71689 this.#readlinkFail(er.code); 71690 return undefined; 71691 } 71692 } 71693 #readdirSuccess(children) { 71694 // succeeded, mark readdir called bit 71695 this.#type |= READDIR_CALLED; 71696 // mark all remaining provisional children as ENOENT 71697 for (let p = children.provisional; p < children.length; p++) { 71698 const c = children[p]; 71699 if (c) 71700 c.#markENOENT(); 71701 } 71702 } 71703 #markENOENT() { 71704 // mark as UNKNOWN and ENOENT 71705 if (this.#type & ENOENT) 71706 return; 71707 this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN; 71708 this.#markChildrenENOENT(); 71709 } 71710 #markChildrenENOENT() { 71711 // all children are provisional and do not exist 71712 const children = this.children(); 71713 children.provisional = 0; 71714 for (const p of children) { 71715 p.#markENOENT(); 71716 } 71717 } 71718 #markENOREALPATH() { 71719 this.#type |= ENOREALPATH; 71720 this.#markENOTDIR(); 71721 } 71722 // save the information when we know the entry is not a dir 71723 #markENOTDIR() { 71724 // entry is not a directory, so any children can't exist. 71725 // this *should* be impossible, since any children created 71726 // after it's been marked ENOTDIR should be marked ENOENT, 71727 // so it won't even get to this point. 71728 /* c8 ignore start */ 71729 if (this.#type & ENOTDIR) 71730 return; 71731 /* c8 ignore stop */ 71732 let t = this.#type; 71733 // this could happen if we stat a dir, then delete it, 71734 // then try to read it or one of its children. 71735 if ((t & IFMT) === IFDIR) 71736 t &= IFMT_UNKNOWN; 71737 this.#type = t | ENOTDIR; 71738 this.#markChildrenENOENT(); 71739 } 71740 #readdirFail(code = '') { 71741 // markENOTDIR and markENOENT also set provisional=0 71742 if (code === 'ENOTDIR' || code === 'EPERM') { 71743 this.#markENOTDIR(); 71744 } 71745 else if (code === 'ENOENT') { 71746 this.#markENOENT(); 71747 } 71748 else { 71749 this.children().provisional = 0; 71750 } 71751 } 71752 #lstatFail(code = '') { 71753 // Windows just raises ENOENT in this case, disable for win CI 71754 /* c8 ignore start */ 71755 if (code === 'ENOTDIR') { 71756 // already know it has a parent by this point 71757 const p = this.parent; 71758 p.#markENOTDIR(); 71759 } 71760 else if (code === 'ENOENT') { 71761 /* c8 ignore stop */ 71762 this.#markENOENT(); 71763 } 71764 } 71765 #readlinkFail(code = '') { 71766 let ter = this.#type; 71767 ter |= ENOREADLINK; 71768 if (code === 'ENOENT') 71769 ter |= ENOENT; 71770 // windows gets a weird error when you try to readlink a file 71771 if (code === 'EINVAL' || code === 'UNKNOWN') { 71772 // exists, but not a symlink, we don't know WHAT it is, so remove 71773 // all IFMT bits. 71774 ter &= IFMT_UNKNOWN; 71775 } 71776 this.#type = ter; 71777 // windows just gets ENOENT in this case. We do cover the case, 71778 // just disabled because it's impossible on Windows CI 71779 /* c8 ignore start */ 71780 if (code === 'ENOTDIR' && this.parent) { 71781 this.parent.#markENOTDIR(); 71782 } 71783 /* c8 ignore stop */ 71784 } 71785 #readdirAddChild(e, c) { 71786 return (this.#readdirMaybePromoteChild(e, c) || 71787 this.#readdirAddNewChild(e, c)); 71788 } 71789 #readdirAddNewChild(e, c) { 71790 // alloc new entry at head, so it's never provisional 71791 const type = entToType(e); 71792 const child = this.newChild(e.name, type, { parent: this }); 71793 const ifmt = child.#type & IFMT; 71794 if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) { 71795 child.#type |= ENOTDIR; 71796 } 71797 c.unshift(child); 71798 c.provisional++; 71799 return child; 71800 } 71801 #readdirMaybePromoteChild(e, c) { 71802 for (let p = c.provisional; p < c.length; p++) { 71803 const pchild = c[p]; 71804 const name = this.nocase 71805 ? normalizeNocase(e.name) 71806 : normalize(e.name); 71807 if (name !== pchild.#matchName) { 71808 continue; 71809 } 71810 return this.#readdirPromoteChild(e, pchild, p, c); 71811 } 71812 } 71813 #readdirPromoteChild(e, p, index, c) { 71814 const v = p.name; 71815 // retain any other flags, but set ifmt from dirent 71816 p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e); 71817 // case sensitivity fixing when we learn the true name. 71818 if (v !== e.name) 71819 p.name = e.name; 71820 // just advance provisional index (potentially off the list), 71821 // otherwise we have to splice/pop it out and re-insert at head 71822 if (index !== c.provisional) { 71823 if (index === c.length - 1) 71824 c.pop(); 71825 else 71826 c.splice(index, 1); 71827 c.unshift(p); 71828 } 71829 c.provisional++; 71830 return p; 71831 } 71832 /** 71833 * Call lstat() on this Path, and update all known information that can be 71834 * determined. 71835 * 71836 * Note that unlike `fs.lstat()`, the returned value does not contain some 71837 * information, such as `mode`, `dev`, `nlink`, and `ino`. If that 71838 * information is required, you will need to call `fs.lstat` yourself. 71839 * 71840 * If the Path refers to a nonexistent file, or if the lstat call fails for 71841 * any reason, `undefined` is returned. Otherwise the updated Path object is 71842 * returned. 71843 * 71844 * Results are cached, and thus may be out of date if the filesystem is 71845 * mutated. 71846 */ 71847 async lstat() { 71848 if ((this.#type & ENOENT) === 0) { 71849 try { 71850 this.#applyStat(await this.#fs.promises.lstat(this.fullpath())); 71851 return this; 71852 } 71853 catch (er) { 71854 this.#lstatFail(er.code); 71855 } 71856 } 71857 } 71858 /** 71859 * synchronous {@link PathBase.lstat} 71860 */ 71861 lstatSync() { 71862 if ((this.#type & ENOENT) === 0) { 71863 try { 71864 this.#applyStat(this.#fs.lstatSync(this.fullpath())); 71865 return this; 71866 } 71867 catch (er) { 71868 this.#lstatFail(er.code); 71869 } 71870 } 71871 } 71872 #applyStat(st) { 71873 const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st; 71874 this.#atime = atime; 71875 this.#atimeMs = atimeMs; 71876 this.#birthtime = birthtime; 71877 this.#birthtimeMs = birthtimeMs; 71878 this.#blksize = blksize; 71879 this.#blocks = blocks; 71880 this.#ctime = ctime; 71881 this.#ctimeMs = ctimeMs; 71882 this.#dev = dev; 71883 this.#gid = gid; 71884 this.#ino = ino; 71885 this.#mode = mode; 71886 this.#mtime = mtime; 71887 this.#mtimeMs = mtimeMs; 71888 this.#nlink = nlink; 71889 this.#rdev = rdev; 71890 this.#size = size; 71891 this.#uid = uid; 71892 const ifmt = entToType(st); 71893 // retain any other flags, but set the ifmt 71894 this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED; 71895 if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) { 71896 this.#type |= ENOTDIR; 71897 } 71898 } 71899 #onReaddirCB = []; 71900 #readdirCBInFlight = false; 71901 #callOnReaddirCB(children) { 71902 this.#readdirCBInFlight = false; 71903 const cbs = this.#onReaddirCB.slice(); 71904 this.#onReaddirCB.length = 0; 71905 cbs.forEach(cb => cb(null, children)); 71906 } 71907 /** 71908 * Standard node-style callback interface to get list of directory entries. 71909 * 71910 * If the Path cannot or does not contain any children, then an empty array 71911 * is returned. 71912 * 71913 * Results are cached, and thus may be out of date if the filesystem is 71914 * mutated. 71915 * 71916 * @param cb The callback called with (er, entries). Note that the `er` 71917 * param is somewhat extraneous, as all readdir() errors are handled and 71918 * simply result in an empty set of entries being returned. 71919 * @param allowZalgo Boolean indicating that immediately known results should 71920 * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release 71921 * zalgo at your peril, the dark pony lord is devious and unforgiving. 71922 */ 71923 readdirCB(cb, allowZalgo = false) { 71924 if (!this.canReaddir()) { 71925 if (allowZalgo) 71926 cb(null, []); 71927 else 71928 queueMicrotask(() => cb(null, [])); 71929 return; 71930 } 71931 const children = this.children(); 71932 if (this.calledReaddir()) { 71933 const c = children.slice(0, children.provisional); 71934 if (allowZalgo) 71935 cb(null, c); 71936 else 71937 queueMicrotask(() => cb(null, c)); 71938 return; 71939 } 71940 // don't have to worry about zalgo at this point. 71941 this.#onReaddirCB.push(cb); 71942 if (this.#readdirCBInFlight) { 71943 return; 71944 } 71945 this.#readdirCBInFlight = true; 71946 // else read the directory, fill up children 71947 // de-provisionalize any provisional children. 71948 const fullpath = this.fullpath(); 71949 this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => { 71950 if (er) { 71951 this.#readdirFail(er.code); 71952 children.provisional = 0; 71953 } 71954 else { 71955 // if we didn't get an error, we always get entries. 71956 //@ts-ignore 71957 for (const e of entries) { 71958 this.#readdirAddChild(e, children); 71959 } 71960 this.#readdirSuccess(children); 71961 } 71962 this.#callOnReaddirCB(children.slice(0, children.provisional)); 71963 return; 71964 }); 71965 } 71966 #asyncReaddirInFlight; 71967 /** 71968 * Return an array of known child entries. 71969 * 71970 * If the Path cannot or does not contain any children, then an empty array 71971 * is returned. 71972 * 71973 * Results are cached, and thus may be out of date if the filesystem is 71974 * mutated. 71975 */ 71976 async readdir() { 71977 if (!this.canReaddir()) { 71978 return []; 71979 } 71980 const children = this.children(); 71981 if (this.calledReaddir()) { 71982 return children.slice(0, children.provisional); 71983 } 71984 // else read the directory, fill up children 71985 // de-provisionalize any provisional children. 71986 const fullpath = this.fullpath(); 71987 if (this.#asyncReaddirInFlight) { 71988 await this.#asyncReaddirInFlight; 71989 } 71990 else { 71991 /* c8 ignore start */ 71992 let resolve = () => { }; 71993 /* c8 ignore stop */ 71994 this.#asyncReaddirInFlight = new Promise(res => (resolve = res)); 71995 try { 71996 for (const e of await this.#fs.promises.readdir(fullpath, { 71997 withFileTypes: true, 71998 })) { 71999 this.#readdirAddChild(e, children); 72000 } 72001 this.#readdirSuccess(children); 72002 } 72003 catch (er) { 72004 this.#readdirFail(er.code); 72005 children.provisional = 0; 72006 } 72007 this.#asyncReaddirInFlight = undefined; 72008 resolve(); 72009 } 72010 return children.slice(0, children.provisional); 72011 } 72012 /** 72013 * synchronous {@link PathBase.readdir} 72014 */ 72015 readdirSync() { 72016 if (!this.canReaddir()) { 72017 return []; 72018 } 72019 const children = this.children(); 72020 if (this.calledReaddir()) { 72021 return children.slice(0, children.provisional); 72022 } 72023 // else read the directory, fill up children 72024 // de-provisionalize any provisional children. 72025 const fullpath = this.fullpath(); 72026 try { 72027 for (const e of this.#fs.readdirSync(fullpath, { 72028 withFileTypes: true, 72029 })) { 72030 this.#readdirAddChild(e, children); 72031 } 72032 this.#readdirSuccess(children); 72033 } 72034 catch (er) { 72035 this.#readdirFail(er.code); 72036 children.provisional = 0; 72037 } 72038 return children.slice(0, children.provisional); 72039 } 72040 canReaddir() { 72041 if (this.#type & ENOCHILD) 72042 return false; 72043 const ifmt = IFMT & this.#type; 72044 // we always set ENOTDIR when setting IFMT, so should be impossible 72045 /* c8 ignore start */ 72046 if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) { 72047 return false; 72048 } 72049 /* c8 ignore stop */ 72050 return true; 72051 } 72052 shouldWalk(dirs, walkFilter) { 72053 return ((this.#type & IFDIR) === IFDIR && 72054 !(this.#type & ENOCHILD) && 72055 !dirs.has(this) && 72056 (!walkFilter || walkFilter(this))); 72057 } 72058 /** 72059 * Return the Path object corresponding to path as resolved 72060 * by realpath(3). 72061 * 72062 * If the realpath call fails for any reason, `undefined` is returned. 72063 * 72064 * Result is cached, and thus may be outdated if the filesystem is mutated. 72065 * On success, returns a Path object. 72066 */ 72067 async realpath() { 72068 if (this.#realpath) 72069 return this.#realpath; 72070 if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) 72071 return undefined; 72072 try { 72073 const rp = await this.#fs.promises.realpath(this.fullpath()); 72074 return (this.#realpath = this.resolve(rp)); 72075 } 72076 catch (_) { 72077 this.#markENOREALPATH(); 72078 } 72079 } 72080 /** 72081 * Synchronous {@link realpath} 72082 */ 72083 realpathSync() { 72084 if (this.#realpath) 72085 return this.#realpath; 72086 if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) 72087 return undefined; 72088 try { 72089 const rp = this.#fs.realpathSync(this.fullpath()); 72090 return (this.#realpath = this.resolve(rp)); 72091 } 72092 catch (_) { 72093 this.#markENOREALPATH(); 72094 } 72095 } 72096 /** 72097 * Internal method to mark this Path object as the scurry cwd, 72098 * called by {@link PathScurry#chdir} 72099 * 72100 * @internal 72101 */ 72102 [setAsCwd](oldCwd) { 72103 if (oldCwd === this) 72104 return; 72105 const changed = new Set([]); 72106 let rp = []; 72107 let p = this; 72108 while (p && p.parent) { 72109 changed.add(p); 72110 p.#relative = rp.join(this.sep); 72111 p.#relativePosix = rp.join('/'); 72112 p = p.parent; 72113 rp.push('..'); 72114 } 72115 // now un-memoize parents of old cwd 72116 p = oldCwd; 72117 while (p && p.parent && !changed.has(p)) { 72118 p.#relative = undefined; 72119 p.#relativePosix = undefined; 72120 p = p.parent; 72121 } 72122 } 72123 } 72124 exports.PathBase = PathBase; 72125 /** 72126 * Path class used on win32 systems 72127 * 72128 * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` 72129 * as the path separator for parsing paths. 72130 */ 72131 class PathWin32 extends PathBase { 72132 /** 72133 * Separator for generating path strings. 72134 */ 72135 sep = '\\'; 72136 /** 72137 * Separator for parsing path strings. 72138 */ 72139 splitSep = eitherSep; 72140 /** 72141 * Do not create new Path objects directly. They should always be accessed 72142 * via the PathScurry class or other methods on the Path class. 72143 * 72144 * @internal 72145 */ 72146 constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { 72147 super(name, type, root, roots, nocase, children, opts); 72148 } 72149 /** 72150 * @internal 72151 */ 72152 newChild(name, type = UNKNOWN, opts = {}) { 72153 return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); 72154 } 72155 /** 72156 * @internal 72157 */ 72158 getRootString(path) { 72159 return path_1.win32.parse(path).root; 72160 } 72161 /** 72162 * @internal 72163 */ 72164 getRoot(rootPath) { 72165 rootPath = uncToDrive(rootPath.toUpperCase()); 72166 if (rootPath === this.root.name) { 72167 return this.root; 72168 } 72169 // ok, not that one, check if it matches another we know about 72170 for (const [compare, root] of Object.entries(this.roots)) { 72171 if (this.sameRoot(rootPath, compare)) { 72172 return (this.roots[rootPath] = root); 72173 } 72174 } 72175 // otherwise, have to create a new one. 72176 return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root); 72177 } 72178 /** 72179 * @internal 72180 */ 72181 sameRoot(rootPath, compare = this.root.name) { 72182 // windows can (rarely) have case-sensitive filesystem, but 72183 // UNC and drive letters are always case-insensitive, and canonically 72184 // represented uppercase. 72185 rootPath = rootPath 72186 .toUpperCase() 72187 .replace(/\//g, '\\') 72188 .replace(uncDriveRegexp, '$1\\'); 72189 return rootPath === compare; 72190 } 72191 } 72192 exports.PathWin32 = PathWin32; 72193 /** 72194 * Path class used on all posix systems. 72195 * 72196 * Uses `'/'` as the path separator. 72197 */ 72198 class PathPosix extends PathBase { 72199 /** 72200 * separator for parsing path strings 72201 */ 72202 splitSep = '/'; 72203 /** 72204 * separator for generating path strings 72205 */ 72206 sep = '/'; 72207 /** 72208 * Do not create new Path objects directly. They should always be accessed 72209 * via the PathScurry class or other methods on the Path class. 72210 * 72211 * @internal 72212 */ 72213 constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { 72214 super(name, type, root, roots, nocase, children, opts); 72215 } 72216 /** 72217 * @internal 72218 */ 72219 getRootString(path) { 72220 return path.startsWith('/') ? '/' : ''; 72221 } 72222 /** 72223 * @internal 72224 */ 72225 getRoot(_rootPath) { 72226 return this.root; 72227 } 72228 /** 72229 * @internal 72230 */ 72231 newChild(name, type = UNKNOWN, opts = {}) { 72232 return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); 72233 } 72234 } 72235 exports.PathPosix = PathPosix; 72236 /** 72237 * The base class for all PathScurry classes, providing the interface for path 72238 * resolution and filesystem operations. 72239 * 72240 * Typically, you should *not* instantiate this class directly, but rather one 72241 * of the platform-specific classes, or the exported {@link PathScurry} which 72242 * defaults to the current platform. 72243 */ 72244 class PathScurryBase { 72245 /** 72246 * The root Path entry for the current working directory of this Scurry 72247 */ 72248 root; 72249 /** 72250 * The string path for the root of this Scurry's current working directory 72251 */ 72252 rootPath; 72253 /** 72254 * A collection of all roots encountered, referenced by rootPath 72255 */ 72256 roots; 72257 /** 72258 * The Path entry corresponding to this PathScurry's current working directory. 72259 */ 72260 cwd; 72261 #resolveCache; 72262 #resolvePosixCache; 72263 #children; 72264 /** 72265 * Perform path comparisons case-insensitively. 72266 * 72267 * Defaults true on Darwin and Windows systems, false elsewhere. 72268 */ 72269 nocase; 72270 #fs; 72271 /** 72272 * This class should not be instantiated directly. 72273 * 72274 * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry 72275 * 72276 * @internal 72277 */ 72278 constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) { 72279 this.#fs = fsFromOption(fs); 72280 if (cwd instanceof URL || cwd.startsWith('file://')) { 72281 cwd = (0, url_1.fileURLToPath)(cwd); 72282 } 72283 // resolve and split root, and then add to the store. 72284 // this is the only time we call path.resolve() 72285 const cwdPath = pathImpl.resolve(cwd); 72286 this.roots = Object.create(null); 72287 this.rootPath = this.parseRootPath(cwdPath); 72288 this.#resolveCache = new ResolveCache(); 72289 this.#resolvePosixCache = new ResolveCache(); 72290 this.#children = new ChildrenCache(childrenCacheSize); 72291 const split = cwdPath.substring(this.rootPath.length).split(sep); 72292 // resolve('/') leaves '', splits to [''], we don't want that. 72293 if (split.length === 1 && !split[0]) { 72294 split.pop(); 72295 } 72296 /* c8 ignore start */ 72297 if (nocase === undefined) { 72298 throw new TypeError('must provide nocase setting to PathScurryBase ctor'); 72299 } 72300 /* c8 ignore stop */ 72301 this.nocase = nocase; 72302 this.root = this.newRoot(this.#fs); 72303 this.roots[this.rootPath] = this.root; 72304 let prev = this.root; 72305 let len = split.length - 1; 72306 const joinSep = pathImpl.sep; 72307 let abs = this.rootPath; 72308 let sawFirst = false; 72309 for (const part of split) { 72310 const l = len--; 72311 prev = prev.child(part, { 72312 relative: new Array(l).fill('..').join(joinSep), 72313 relativePosix: new Array(l).fill('..').join('/'), 72314 fullpath: (abs += (sawFirst ? '' : joinSep) + part), 72315 }); 72316 sawFirst = true; 72317 } 72318 this.cwd = prev; 72319 } 72320 /** 72321 * Get the depth of a provided path, string, or the cwd 72322 */ 72323 depth(path = this.cwd) { 72324 if (typeof path === 'string') { 72325 path = this.cwd.resolve(path); 72326 } 72327 return path.depth(); 72328 } 72329 /** 72330 * Return the cache of child entries. Exposed so subclasses can create 72331 * child Path objects in a platform-specific way. 72332 * 72333 * @internal 72334 */ 72335 childrenCache() { 72336 return this.#children; 72337 } 72338 /** 72339 * Resolve one or more path strings to a resolved string 72340 * 72341 * Same interface as require('path').resolve. 72342 * 72343 * Much faster than path.resolve() when called multiple times for the same 72344 * path, because the resolved Path objects are cached. Much slower 72345 * otherwise. 72346 */ 72347 resolve(...paths) { 72348 // first figure out the minimum number of paths we have to test 72349 // we always start at cwd, but any absolutes will bump the start 72350 let r = ''; 72351 for (let i = paths.length - 1; i >= 0; i--) { 72352 const p = paths[i]; 72353 if (!p || p === '.') 72354 continue; 72355 r = r ? `${p}/${r}` : p; 72356 if (this.isAbsolute(p)) { 72357 break; 72358 } 72359 } 72360 const cached = this.#resolveCache.get(r); 72361 if (cached !== undefined) { 72362 return cached; 72363 } 72364 const result = this.cwd.resolve(r).fullpath(); 72365 this.#resolveCache.set(r, result); 72366 return result; 72367 } 72368 /** 72369 * Resolve one or more path strings to a resolved string, returning 72370 * the posix path. Identical to .resolve() on posix systems, but on 72371 * windows will return a forward-slash separated UNC path. 72372 * 72373 * Same interface as require('path').resolve. 72374 * 72375 * Much faster than path.resolve() when called multiple times for the same 72376 * path, because the resolved Path objects are cached. Much slower 72377 * otherwise. 72378 */ 72379 resolvePosix(...paths) { 72380 // first figure out the minimum number of paths we have to test 72381 // we always start at cwd, but any absolutes will bump the start 72382 let r = ''; 72383 for (let i = paths.length - 1; i >= 0; i--) { 72384 const p = paths[i]; 72385 if (!p || p === '.') 72386 continue; 72387 r = r ? `${p}/${r}` : p; 72388 if (this.isAbsolute(p)) { 72389 break; 72390 } 72391 } 72392 const cached = this.#resolvePosixCache.get(r); 72393 if (cached !== undefined) { 72394 return cached; 72395 } 72396 const result = this.cwd.resolve(r).fullpathPosix(); 72397 this.#resolvePosixCache.set(r, result); 72398 return result; 72399 } 72400 /** 72401 * find the relative path from the cwd to the supplied path string or entry 72402 */ 72403 relative(entry = this.cwd) { 72404 if (typeof entry === 'string') { 72405 entry = this.cwd.resolve(entry); 72406 } 72407 return entry.relative(); 72408 } 72409 /** 72410 * find the relative path from the cwd to the supplied path string or 72411 * entry, using / as the path delimiter, even on Windows. 72412 */ 72413 relativePosix(entry = this.cwd) { 72414 if (typeof entry === 'string') { 72415 entry = this.cwd.resolve(entry); 72416 } 72417 return entry.relativePosix(); 72418 } 72419 /** 72420 * Return the basename for the provided string or Path object 72421 */ 72422 basename(entry = this.cwd) { 72423 if (typeof entry === 'string') { 72424 entry = this.cwd.resolve(entry); 72425 } 72426 return entry.name; 72427 } 72428 /** 72429 * Return the dirname for the provided string or Path object 72430 */ 72431 dirname(entry = this.cwd) { 72432 if (typeof entry === 'string') { 72433 entry = this.cwd.resolve(entry); 72434 } 72435 return (entry.parent || entry).fullpath(); 72436 } 72437 async readdir(entry = this.cwd, opts = { 72438 withFileTypes: true, 72439 }) { 72440 if (typeof entry === 'string') { 72441 entry = this.cwd.resolve(entry); 72442 } 72443 else if (!(entry instanceof PathBase)) { 72444 opts = entry; 72445 entry = this.cwd; 72446 } 72447 const { withFileTypes } = opts; 72448 if (!entry.canReaddir()) { 72449 return []; 72450 } 72451 else { 72452 const p = await entry.readdir(); 72453 return withFileTypes ? p : p.map(e => e.name); 72454 } 72455 } 72456 readdirSync(entry = this.cwd, opts = { 72457 withFileTypes: true, 72458 }) { 72459 if (typeof entry === 'string') { 72460 entry = this.cwd.resolve(entry); 72461 } 72462 else if (!(entry instanceof PathBase)) { 72463 opts = entry; 72464 entry = this.cwd; 72465 } 72466 const { withFileTypes = true } = opts; 72467 if (!entry.canReaddir()) { 72468 return []; 72469 } 72470 else if (withFileTypes) { 72471 return entry.readdirSync(); 72472 } 72473 else { 72474 return entry.readdirSync().map(e => e.name); 72475 } 72476 } 72477 /** 72478 * Call lstat() on the string or Path object, and update all known 72479 * information that can be determined. 72480 * 72481 * Note that unlike `fs.lstat()`, the returned value does not contain some 72482 * information, such as `mode`, `dev`, `nlink`, and `ino`. If that 72483 * information is required, you will need to call `fs.lstat` yourself. 72484 * 72485 * If the Path refers to a nonexistent file, or if the lstat call fails for 72486 * any reason, `undefined` is returned. Otherwise the updated Path object is 72487 * returned. 72488 * 72489 * Results are cached, and thus may be out of date if the filesystem is 72490 * mutated. 72491 */ 72492 async lstat(entry = this.cwd) { 72493 if (typeof entry === 'string') { 72494 entry = this.cwd.resolve(entry); 72495 } 72496 return entry.lstat(); 72497 } 72498 /** 72499 * synchronous {@link PathScurryBase.lstat} 72500 */ 72501 lstatSync(entry = this.cwd) { 72502 if (typeof entry === 'string') { 72503 entry = this.cwd.resolve(entry); 72504 } 72505 return entry.lstatSync(); 72506 } 72507 async readlink(entry = this.cwd, { withFileTypes } = { 72508 withFileTypes: false, 72509 }) { 72510 if (typeof entry === 'string') { 72511 entry = this.cwd.resolve(entry); 72512 } 72513 else if (!(entry instanceof PathBase)) { 72514 withFileTypes = entry.withFileTypes; 72515 entry = this.cwd; 72516 } 72517 const e = await entry.readlink(); 72518 return withFileTypes ? e : e?.fullpath(); 72519 } 72520 readlinkSync(entry = this.cwd, { withFileTypes } = { 72521 withFileTypes: false, 72522 }) { 72523 if (typeof entry === 'string') { 72524 entry = this.cwd.resolve(entry); 72525 } 72526 else if (!(entry instanceof PathBase)) { 72527 withFileTypes = entry.withFileTypes; 72528 entry = this.cwd; 72529 } 72530 const e = entry.readlinkSync(); 72531 return withFileTypes ? e : e?.fullpath(); 72532 } 72533 async realpath(entry = this.cwd, { withFileTypes } = { 72534 withFileTypes: false, 72535 }) { 72536 if (typeof entry === 'string') { 72537 entry = this.cwd.resolve(entry); 72538 } 72539 else if (!(entry instanceof PathBase)) { 72540 withFileTypes = entry.withFileTypes; 72541 entry = this.cwd; 72542 } 72543 const e = await entry.realpath(); 72544 return withFileTypes ? e : e?.fullpath(); 72545 } 72546 realpathSync(entry = this.cwd, { withFileTypes } = { 72547 withFileTypes: false, 72548 }) { 72549 if (typeof entry === 'string') { 72550 entry = this.cwd.resolve(entry); 72551 } 72552 else if (!(entry instanceof PathBase)) { 72553 withFileTypes = entry.withFileTypes; 72554 entry = this.cwd; 72555 } 72556 const e = entry.realpathSync(); 72557 return withFileTypes ? e : e?.fullpath(); 72558 } 72559 async walk(entry = this.cwd, opts = {}) { 72560 if (typeof entry === 'string') { 72561 entry = this.cwd.resolve(entry); 72562 } 72563 else if (!(entry instanceof PathBase)) { 72564 opts = entry; 72565 entry = this.cwd; 72566 } 72567 const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; 72568 const results = []; 72569 if (!filter || filter(entry)) { 72570 results.push(withFileTypes ? entry : entry.fullpath()); 72571 } 72572 const dirs = new Set(); 72573 const walk = (dir, cb) => { 72574 dirs.add(dir); 72575 dir.readdirCB((er, entries) => { 72576 /* c8 ignore start */ 72577 if (er) { 72578 return cb(er); 72579 } 72580 /* c8 ignore stop */ 72581 let len = entries.length; 72582 if (!len) 72583 return cb(); 72584 const next = () => { 72585 if (--len === 0) { 72586 cb(); 72587 } 72588 }; 72589 for (const e of entries) { 72590 if (!filter || filter(e)) { 72591 results.push(withFileTypes ? e : e.fullpath()); 72592 } 72593 if (follow && e.isSymbolicLink()) { 72594 e.realpath() 72595 .then(r => (r?.isUnknown() ? r.lstat() : r)) 72596 .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()); 72597 } 72598 else { 72599 if (e.shouldWalk(dirs, walkFilter)) { 72600 walk(e, next); 72601 } 72602 else { 72603 next(); 72604 } 72605 } 72606 } 72607 }, true); // zalgooooooo 72608 }; 72609 const start = entry; 72610 return new Promise((res, rej) => { 72611 walk(start, er => { 72612 /* c8 ignore start */ 72613 if (er) 72614 return rej(er); 72615 /* c8 ignore stop */ 72616 res(results); 72617 }); 72618 }); 72619 } 72620 walkSync(entry = this.cwd, opts = {}) { 72621 if (typeof entry === 'string') { 72622 entry = this.cwd.resolve(entry); 72623 } 72624 else if (!(entry instanceof PathBase)) { 72625 opts = entry; 72626 entry = this.cwd; 72627 } 72628 const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; 72629 const results = []; 72630 if (!filter || filter(entry)) { 72631 results.push(withFileTypes ? entry : entry.fullpath()); 72632 } 72633 const dirs = new Set([entry]); 72634 for (const dir of dirs) { 72635 const entries = dir.readdirSync(); 72636 for (const e of entries) { 72637 if (!filter || filter(e)) { 72638 results.push(withFileTypes ? e : e.fullpath()); 72639 } 72640 let r = e; 72641 if (e.isSymbolicLink()) { 72642 if (!(follow && (r = e.realpathSync()))) 72643 continue; 72644 if (r.isUnknown()) 72645 r.lstatSync(); 72646 } 72647 if (r.shouldWalk(dirs, walkFilter)) { 72648 dirs.add(r); 72649 } 72650 } 72651 } 72652 return results; 72653 } 72654 /** 72655 * Support for `for await` 72656 * 72657 * Alias for {@link PathScurryBase.iterate} 72658 * 72659 * Note: As of Node 19, this is very slow, compared to other methods of 72660 * walking. Consider using {@link PathScurryBase.stream} if memory overhead 72661 * and backpressure are concerns, or {@link PathScurryBase.walk} if not. 72662 */ 72663 [Symbol.asyncIterator]() { 72664 return this.iterate(); 72665 } 72666 iterate(entry = this.cwd, options = {}) { 72667 // iterating async over the stream is significantly more performant, 72668 // especially in the warm-cache scenario, because it buffers up directory 72669 // entries in the background instead of waiting for a yield for each one. 72670 if (typeof entry === 'string') { 72671 entry = this.cwd.resolve(entry); 72672 } 72673 else if (!(entry instanceof PathBase)) { 72674 options = entry; 72675 entry = this.cwd; 72676 } 72677 return this.stream(entry, options)[Symbol.asyncIterator](); 72678 } 72679 /** 72680 * Iterating over a PathScurry performs a synchronous walk. 72681 * 72682 * Alias for {@link PathScurryBase.iterateSync} 72683 */ 72684 [Symbol.iterator]() { 72685 return this.iterateSync(); 72686 } 72687 *iterateSync(entry = this.cwd, opts = {}) { 72688 if (typeof entry === 'string') { 72689 entry = this.cwd.resolve(entry); 72690 } 72691 else if (!(entry instanceof PathBase)) { 72692 opts = entry; 72693 entry = this.cwd; 72694 } 72695 const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; 72696 if (!filter || filter(entry)) { 72697 yield withFileTypes ? entry : entry.fullpath(); 72698 } 72699 const dirs = new Set([entry]); 72700 for (const dir of dirs) { 72701 const entries = dir.readdirSync(); 72702 for (const e of entries) { 72703 if (!filter || filter(e)) { 72704 yield withFileTypes ? e : e.fullpath(); 72705 } 72706 let r = e; 72707 if (e.isSymbolicLink()) { 72708 if (!(follow && (r = e.realpathSync()))) 72709 continue; 72710 if (r.isUnknown()) 72711 r.lstatSync(); 72712 } 72713 if (r.shouldWalk(dirs, walkFilter)) { 72714 dirs.add(r); 72715 } 72716 } 72717 } 72718 } 72719 stream(entry = this.cwd, opts = {}) { 72720 if (typeof entry === 'string') { 72721 entry = this.cwd.resolve(entry); 72722 } 72723 else if (!(entry instanceof PathBase)) { 72724 opts = entry; 72725 entry = this.cwd; 72726 } 72727 const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; 72728 const results = new minipass_1.Minipass({ objectMode: true }); 72729 if (!filter || filter(entry)) { 72730 results.write(withFileTypes ? entry : entry.fullpath()); 72731 } 72732 const dirs = new Set(); 72733 const queue = [entry]; 72734 let processing = 0; 72735 const process = () => { 72736 let paused = false; 72737 while (!paused) { 72738 const dir = queue.shift(); 72739 if (!dir) { 72740 if (processing === 0) 72741 results.end(); 72742 return; 72743 } 72744 processing++; 72745 dirs.add(dir); 72746 const onReaddir = (er, entries, didRealpaths = false) => { 72747 /* c8 ignore start */ 72748 if (er) 72749 return results.emit('error', er); 72750 /* c8 ignore stop */ 72751 if (follow && !didRealpaths) { 72752 const promises = []; 72753 for (const e of entries) { 72754 if (e.isSymbolicLink()) { 72755 promises.push(e 72756 .realpath() 72757 .then((r) => r?.isUnknown() ? r.lstat() : r)); 72758 } 72759 } 72760 if (promises.length) { 72761 Promise.all(promises).then(() => onReaddir(null, entries, true)); 72762 return; 72763 } 72764 } 72765 for (const e of entries) { 72766 if (e && (!filter || filter(e))) { 72767 if (!results.write(withFileTypes ? e : e.fullpath())) { 72768 paused = true; 72769 } 72770 } 72771 } 72772 processing--; 72773 for (const e of entries) { 72774 const r = e.realpathCached() || e; 72775 if (r.shouldWalk(dirs, walkFilter)) { 72776 queue.push(r); 72777 } 72778 } 72779 if (paused && !results.flowing) { 72780 results.once('drain', process); 72781 } 72782 else if (!sync) { 72783 process(); 72784 } 72785 }; 72786 // zalgo containment 72787 let sync = true; 72788 dir.readdirCB(onReaddir, true); 72789 sync = false; 72790 } 72791 }; 72792 process(); 72793 return results; 72794 } 72795 streamSync(entry = this.cwd, opts = {}) { 72796 if (typeof entry === 'string') { 72797 entry = this.cwd.resolve(entry); 72798 } 72799 else if (!(entry instanceof PathBase)) { 72800 opts = entry; 72801 entry = this.cwd; 72802 } 72803 const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; 72804 const results = new minipass_1.Minipass({ objectMode: true }); 72805 const dirs = new Set(); 72806 if (!filter || filter(entry)) { 72807 results.write(withFileTypes ? entry : entry.fullpath()); 72808 } 72809 const queue = [entry]; 72810 let processing = 0; 72811 const process = () => { 72812 let paused = false; 72813 while (!paused) { 72814 const dir = queue.shift(); 72815 if (!dir) { 72816 if (processing === 0) 72817 results.end(); 72818 return; 72819 } 72820 processing++; 72821 dirs.add(dir); 72822 const entries = dir.readdirSync(); 72823 for (const e of entries) { 72824 if (!filter || filter(e)) { 72825 if (!results.write(withFileTypes ? e : e.fullpath())) { 72826 paused = true; 72827 } 72828 } 72829 } 72830 processing--; 72831 for (const e of entries) { 72832 let r = e; 72833 if (e.isSymbolicLink()) { 72834 if (!(follow && (r = e.realpathSync()))) 72835 continue; 72836 if (r.isUnknown()) 72837 r.lstatSync(); 72838 } 72839 if (r.shouldWalk(dirs, walkFilter)) { 72840 queue.push(r); 72841 } 72842 } 72843 } 72844 if (paused && !results.flowing) 72845 results.once('drain', process); 72846 }; 72847 process(); 72848 return results; 72849 } 72850 chdir(path = this.cwd) { 72851 const oldCwd = this.cwd; 72852 this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path; 72853 this.cwd[setAsCwd](oldCwd); 72854 } 72855 } 72856 exports.PathScurryBase = PathScurryBase; 72857 /** 72858 * Windows implementation of {@link PathScurryBase} 72859 * 72860 * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses 72861 * {@link PathWin32} for Path objects. 72862 */ 72863 class PathScurryWin32 extends PathScurryBase { 72864 /** 72865 * separator for generating path strings 72866 */ 72867 sep = '\\'; 72868 constructor(cwd = process.cwd(), opts = {}) { 72869 const { nocase = true } = opts; 72870 super(cwd, path_1.win32, '\\', { ...opts, nocase }); 72871 this.nocase = nocase; 72872 for (let p = this.cwd; p; p = p.parent) { 72873 p.nocase = this.nocase; 72874 } 72875 } 72876 /** 72877 * @internal 72878 */ 72879 parseRootPath(dir) { 72880 // if the path starts with a single separator, it's not a UNC, and we'll 72881 // just get separator as the root, and driveFromUNC will return \ 72882 // In that case, mount \ on the root from the cwd. 72883 return path_1.win32.parse(dir).root.toUpperCase(); 72884 } 72885 /** 72886 * @internal 72887 */ 72888 newRoot(fs) { 72889 return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); 72890 } 72891 /** 72892 * Return true if the provided path string is an absolute path 72893 */ 72894 isAbsolute(p) { 72895 return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p)); 72896 } 72897 } 72898 exports.PathScurryWin32 = PathScurryWin32; 72899 /** 72900 * {@link PathScurryBase} implementation for all posix systems other than Darwin. 72901 * 72902 * Defaults to case-sensitive matching, uses `'/'` to generate path strings. 72903 * 72904 * Uses {@link PathPosix} for Path objects. 72905 */ 72906 class PathScurryPosix extends PathScurryBase { 72907 /** 72908 * separator for generating path strings 72909 */ 72910 sep = '/'; 72911 constructor(cwd = process.cwd(), opts = {}) { 72912 const { nocase = false } = opts; 72913 super(cwd, path_1.posix, '/', { ...opts, nocase }); 72914 this.nocase = nocase; 72915 } 72916 /** 72917 * @internal 72918 */ 72919 parseRootPath(_dir) { 72920 return '/'; 72921 } 72922 /** 72923 * @internal 72924 */ 72925 newRoot(fs) { 72926 return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); 72927 } 72928 /** 72929 * Return true if the provided path string is an absolute path 72930 */ 72931 isAbsolute(p) { 72932 return p.startsWith('/'); 72933 } 72934 } 72935 exports.PathScurryPosix = PathScurryPosix; 72936 /** 72937 * {@link PathScurryBase} implementation for Darwin (macOS) systems. 72938 * 72939 * Defaults to case-insensitive matching, uses `'/'` for generating path 72940 * strings. 72941 * 72942 * Uses {@link PathPosix} for Path objects. 72943 */ 72944 class PathScurryDarwin extends PathScurryPosix { 72945 constructor(cwd = process.cwd(), opts = {}) { 72946 const { nocase = true } = opts; 72947 super(cwd, { ...opts, nocase }); 72948 } 72949 } 72950 exports.PathScurryDarwin = PathScurryDarwin; 72951 /** 72952 * Default {@link PathBase} implementation for the current platform. 72953 * 72954 * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. 72955 */ 72956 exports.Path = process.platform === 'win32' ? PathWin32 : PathPosix; 72957 /** 72958 * Default {@link PathScurryBase} implementation for the current platform. 72959 * 72960 * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on 72961 * Darwin (macOS) systems, {@link PathScurryPosix} on all others. 72962 */ 72963 exports.PathScurry = process.platform === 'win32' 72964 ? PathScurryWin32 72965 : process.platform === 'darwin' 72966 ? PathScurryDarwin 72967 : PathScurryPosix; 72968 //# sourceMappingURL=index.js.map 72969 72970 /***/ }), 72971 72972 /***/ 6091: 72973 /***/ ((__unused_webpack_module, exports) => { 72974 72975 "use strict"; 72976 72977 /** 72978 * @module LRUCache 72979 */ 72980 Object.defineProperty(exports, "__esModule", ({ value: true })); 72981 exports.LRUCache = void 0; 72982 const perf = typeof performance === 'object' && 72983 performance && 72984 typeof performance.now === 'function' 72985 ? performance 72986 : Date; 72987 const warned = new Set(); 72988 /* c8 ignore start */ 72989 const PROCESS = (typeof process === 'object' && !!process ? process : {}); 72990 /* c8 ignore start */ 72991 const emitWarning = (msg, type, code, fn) => { 72992 typeof PROCESS.emitWarning === 'function' 72993 ? PROCESS.emitWarning(msg, type, code, fn) 72994 : console.error(`[${code}] ${type}: ${msg}`); 72995 }; 72996 let AC = globalThis.AbortController; 72997 let AS = globalThis.AbortSignal; 72998 /* c8 ignore start */ 72999 if (typeof AC === 'undefined') { 73000 //@ts-ignore 73001 AS = class AbortSignal { 73002 onabort; 73003 _onabort = []; 73004 reason; 73005 aborted = false; 73006 addEventListener(_, fn) { 73007 this._onabort.push(fn); 73008 } 73009 }; 73010 //@ts-ignore 73011 AC = class AbortController { 73012 constructor() { 73013 warnACPolyfill(); 73014 } 73015 signal = new AS(); 73016 abort(reason) { 73017 if (this.signal.aborted) 73018 return; 73019 //@ts-ignore 73020 this.signal.reason = reason; 73021 //@ts-ignore 73022 this.signal.aborted = true; 73023 //@ts-ignore 73024 for (const fn of this.signal._onabort) { 73025 fn(reason); 73026 } 73027 this.signal.onabort?.(reason); 73028 } 73029 }; 73030 let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; 73031 const warnACPolyfill = () => { 73032 if (!printACPolyfillWarning) 73033 return; 73034 printACPolyfillWarning = false; 73035 emitWarning('AbortController is not defined. If using lru-cache in ' + 73036 'node 14, load an AbortController polyfill from the ' + 73037 '`node-abort-controller` package. A minimal polyfill is ' + 73038 'provided for use by LRUCache.fetch(), but it should not be ' + 73039 'relied upon in other contexts (eg, passing it to other APIs that ' + 73040 'use AbortController/AbortSignal might have undesirable effects). ' + 73041 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); 73042 }; 73043 } 73044 /* c8 ignore stop */ 73045 const shouldWarn = (code) => !warned.has(code); 73046 const TYPE = Symbol('type'); 73047 const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); 73048 /* c8 ignore start */ 73049 // This is a little bit ridiculous, tbh. 73050 // The maximum array length is 2^32-1 or thereabouts on most JS impls. 73051 // And well before that point, you're caching the entire world, I mean, 73052 // that's ~32GB of just integers for the next/prev links, plus whatever 73053 // else to hold that many keys and values. Just filling the memory with 73054 // zeroes at init time is brutal when you get that big. 73055 // But why not be complete? 73056 // Maybe in the future, these limits will have expanded. 73057 const getUintArray = (max) => !isPosInt(max) 73058 ? null 73059 : max <= Math.pow(2, 8) 73060 ? Uint8Array 73061 : max <= Math.pow(2, 16) 73062 ? Uint16Array 73063 : max <= Math.pow(2, 32) 73064 ? Uint32Array 73065 : max <= Number.MAX_SAFE_INTEGER 73066 ? ZeroArray 73067 : null; 73068 /* c8 ignore stop */ 73069 class ZeroArray extends Array { 73070 constructor(size) { 73071 super(size); 73072 this.fill(0); 73073 } 73074 } 73075 class Stack { 73076 heap; 73077 length; 73078 // private constructor 73079 static #constructing = false; 73080 static create(max) { 73081 const HeapCls = getUintArray(max); 73082 if (!HeapCls) 73083 return []; 73084 Stack.#constructing = true; 73085 const s = new Stack(max, HeapCls); 73086 Stack.#constructing = false; 73087 return s; 73088 } 73089 constructor(max, HeapCls) { 73090 /* c8 ignore start */ 73091 if (!Stack.#constructing) { 73092 throw new TypeError('instantiate Stack using Stack.create(n)'); 73093 } 73094 /* c8 ignore stop */ 73095 this.heap = new HeapCls(max); 73096 this.length = 0; 73097 } 73098 push(n) { 73099 this.heap[this.length++] = n; 73100 } 73101 pop() { 73102 return this.heap[--this.length]; 73103 } 73104 } 73105 /** 73106 * Default export, the thing you're using this module to get. 73107 * 73108 * All properties from the options object (with the exception of 73109 * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as 73110 * normal public members. (`max` and `maxBase` are read-only getters.) 73111 * Changing any of these will alter the defaults for subsequent method calls, 73112 * but is otherwise safe. 73113 */ 73114 class LRUCache { 73115 // properties coming in from the options of these, only max and maxSize 73116 // really *need* to be protected. The rest can be modified, as they just 73117 // set defaults for various methods. 73118 #max; 73119 #maxSize; 73120 #dispose; 73121 #disposeAfter; 73122 #fetchMethod; 73123 /** 73124 * {@link LRUCache.OptionsBase.ttl} 73125 */ 73126 ttl; 73127 /** 73128 * {@link LRUCache.OptionsBase.ttlResolution} 73129 */ 73130 ttlResolution; 73131 /** 73132 * {@link LRUCache.OptionsBase.ttlAutopurge} 73133 */ 73134 ttlAutopurge; 73135 /** 73136 * {@link LRUCache.OptionsBase.updateAgeOnGet} 73137 */ 73138 updateAgeOnGet; 73139 /** 73140 * {@link LRUCache.OptionsBase.updateAgeOnHas} 73141 */ 73142 updateAgeOnHas; 73143 /** 73144 * {@link LRUCache.OptionsBase.allowStale} 73145 */ 73146 allowStale; 73147 /** 73148 * {@link LRUCache.OptionsBase.noDisposeOnSet} 73149 */ 73150 noDisposeOnSet; 73151 /** 73152 * {@link LRUCache.OptionsBase.noUpdateTTL} 73153 */ 73154 noUpdateTTL; 73155 /** 73156 * {@link LRUCache.OptionsBase.maxEntrySize} 73157 */ 73158 maxEntrySize; 73159 /** 73160 * {@link LRUCache.OptionsBase.sizeCalculation} 73161 */ 73162 sizeCalculation; 73163 /** 73164 * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} 73165 */ 73166 noDeleteOnFetchRejection; 73167 /** 73168 * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} 73169 */ 73170 noDeleteOnStaleGet; 73171 /** 73172 * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} 73173 */ 73174 allowStaleOnFetchAbort; 73175 /** 73176 * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} 73177 */ 73178 allowStaleOnFetchRejection; 73179 /** 73180 * {@link LRUCache.OptionsBase.ignoreFetchAbort} 73181 */ 73182 ignoreFetchAbort; 73183 // computed properties 73184 #size; 73185 #calculatedSize; 73186 #keyMap; 73187 #keyList; 73188 #valList; 73189 #next; 73190 #prev; 73191 #head; 73192 #tail; 73193 #free; 73194 #disposed; 73195 #sizes; 73196 #starts; 73197 #ttls; 73198 #hasDispose; 73199 #hasFetchMethod; 73200 #hasDisposeAfter; 73201 /** 73202 * Do not call this method unless you need to inspect the 73203 * inner workings of the cache. If anything returned by this 73204 * object is modified in any way, strange breakage may occur. 73205 * 73206 * These fields are private for a reason! 73207 * 73208 * @internal 73209 */ 73210 static unsafeExposeInternals(c) { 73211 return { 73212 // properties 73213 starts: c.#starts, 73214 ttls: c.#ttls, 73215 sizes: c.#sizes, 73216 keyMap: c.#keyMap, 73217 keyList: c.#keyList, 73218 valList: c.#valList, 73219 next: c.#next, 73220 prev: c.#prev, 73221 get head() { 73222 return c.#head; 73223 }, 73224 get tail() { 73225 return c.#tail; 73226 }, 73227 free: c.#free, 73228 // methods 73229 isBackgroundFetch: (p) => c.#isBackgroundFetch(p), 73230 backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), 73231 moveToTail: (index) => c.#moveToTail(index), 73232 indexes: (options) => c.#indexes(options), 73233 rindexes: (options) => c.#rindexes(options), 73234 isStale: (index) => c.#isStale(index), 73235 }; 73236 } 73237 // Protected read-only members 73238 /** 73239 * {@link LRUCache.OptionsBase.max} (read-only) 73240 */ 73241 get max() { 73242 return this.#max; 73243 } 73244 /** 73245 * {@link LRUCache.OptionsBase.maxSize} (read-only) 73246 */ 73247 get maxSize() { 73248 return this.#maxSize; 73249 } 73250 /** 73251 * The total computed size of items in the cache (read-only) 73252 */ 73253 get calculatedSize() { 73254 return this.#calculatedSize; 73255 } 73256 /** 73257 * The number of items stored in the cache (read-only) 73258 */ 73259 get size() { 73260 return this.#size; 73261 } 73262 /** 73263 * {@link LRUCache.OptionsBase.fetchMethod} (read-only) 73264 */ 73265 get fetchMethod() { 73266 return this.#fetchMethod; 73267 } 73268 /** 73269 * {@link LRUCache.OptionsBase.dispose} (read-only) 73270 */ 73271 get dispose() { 73272 return this.#dispose; 73273 } 73274 /** 73275 * {@link LRUCache.OptionsBase.disposeAfter} (read-only) 73276 */ 73277 get disposeAfter() { 73278 return this.#disposeAfter; 73279 } 73280 constructor(options) { 73281 const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; 73282 if (max !== 0 && !isPosInt(max)) { 73283 throw new TypeError('max option must be a nonnegative integer'); 73284 } 73285 const UintArray = max ? getUintArray(max) : Array; 73286 if (!UintArray) { 73287 throw new Error('invalid max value: ' + max); 73288 } 73289 this.#max = max; 73290 this.#maxSize = maxSize; 73291 this.maxEntrySize = maxEntrySize || this.#maxSize; 73292 this.sizeCalculation = sizeCalculation; 73293 if (this.sizeCalculation) { 73294 if (!this.#maxSize && !this.maxEntrySize) { 73295 throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); 73296 } 73297 if (typeof this.sizeCalculation !== 'function') { 73298 throw new TypeError('sizeCalculation set to non-function'); 73299 } 73300 } 73301 if (fetchMethod !== undefined && 73302 typeof fetchMethod !== 'function') { 73303 throw new TypeError('fetchMethod must be a function if specified'); 73304 } 73305 this.#fetchMethod = fetchMethod; 73306 this.#hasFetchMethod = !!fetchMethod; 73307 this.#keyMap = new Map(); 73308 this.#keyList = new Array(max).fill(undefined); 73309 this.#valList = new Array(max).fill(undefined); 73310 this.#next = new UintArray(max); 73311 this.#prev = new UintArray(max); 73312 this.#head = 0; 73313 this.#tail = 0; 73314 this.#free = Stack.create(max); 73315 this.#size = 0; 73316 this.#calculatedSize = 0; 73317 if (typeof dispose === 'function') { 73318 this.#dispose = dispose; 73319 } 73320 if (typeof disposeAfter === 'function') { 73321 this.#disposeAfter = disposeAfter; 73322 this.#disposed = []; 73323 } 73324 else { 73325 this.#disposeAfter = undefined; 73326 this.#disposed = undefined; 73327 } 73328 this.#hasDispose = !!this.#dispose; 73329 this.#hasDisposeAfter = !!this.#disposeAfter; 73330 this.noDisposeOnSet = !!noDisposeOnSet; 73331 this.noUpdateTTL = !!noUpdateTTL; 73332 this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; 73333 this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; 73334 this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; 73335 this.ignoreFetchAbort = !!ignoreFetchAbort; 73336 // NB: maxEntrySize is set to maxSize if it's set 73337 if (this.maxEntrySize !== 0) { 73338 if (this.#maxSize !== 0) { 73339 if (!isPosInt(this.#maxSize)) { 73340 throw new TypeError('maxSize must be a positive integer if specified'); 73341 } 73342 } 73343 if (!isPosInt(this.maxEntrySize)) { 73344 throw new TypeError('maxEntrySize must be a positive integer if specified'); 73345 } 73346 this.#initializeSizeTracking(); 73347 } 73348 this.allowStale = !!allowStale; 73349 this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; 73350 this.updateAgeOnGet = !!updateAgeOnGet; 73351 this.updateAgeOnHas = !!updateAgeOnHas; 73352 this.ttlResolution = 73353 isPosInt(ttlResolution) || ttlResolution === 0 73354 ? ttlResolution 73355 : 1; 73356 this.ttlAutopurge = !!ttlAutopurge; 73357 this.ttl = ttl || 0; 73358 if (this.ttl) { 73359 if (!isPosInt(this.ttl)) { 73360 throw new TypeError('ttl must be a positive integer if specified'); 73361 } 73362 this.#initializeTTLTracking(); 73363 } 73364 // do not allow completely unbounded caches 73365 if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { 73366 throw new TypeError('At least one of max, maxSize, or ttl is required'); 73367 } 73368 if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { 73369 const code = 'LRU_CACHE_UNBOUNDED'; 73370 if (shouldWarn(code)) { 73371 warned.add(code); 73372 const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 73373 'result in unbounded memory consumption.'; 73374 emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); 73375 } 73376 } 73377 } 73378 /** 73379 * Return the remaining TTL time for a given entry key 73380 */ 73381 getRemainingTTL(key) { 73382 return this.#keyMap.has(key) ? Infinity : 0; 73383 } 73384 #initializeTTLTracking() { 73385 const ttls = new ZeroArray(this.#max); 73386 const starts = new ZeroArray(this.#max); 73387 this.#ttls = ttls; 73388 this.#starts = starts; 73389 this.#setItemTTL = (index, ttl, start = perf.now()) => { 73390 starts[index] = ttl !== 0 ? start : 0; 73391 ttls[index] = ttl; 73392 if (ttl !== 0 && this.ttlAutopurge) { 73393 const t = setTimeout(() => { 73394 if (this.#isStale(index)) { 73395 this.delete(this.#keyList[index]); 73396 } 73397 }, ttl + 1); 73398 // unref() not supported on all platforms 73399 /* c8 ignore start */ 73400 if (t.unref) { 73401 t.unref(); 73402 } 73403 /* c8 ignore stop */ 73404 } 73405 }; 73406 this.#updateItemAge = index => { 73407 starts[index] = ttls[index] !== 0 ? perf.now() : 0; 73408 }; 73409 this.#statusTTL = (status, index) => { 73410 if (ttls[index]) { 73411 const ttl = ttls[index]; 73412 const start = starts[index]; 73413 /* c8 ignore next */ 73414 if (!ttl || !start) 73415 return; 73416 status.ttl = ttl; 73417 status.start = start; 73418 status.now = cachedNow || getNow(); 73419 const age = status.now - start; 73420 status.remainingTTL = ttl - age; 73421 } 73422 }; 73423 // debounce calls to perf.now() to 1s so we're not hitting 73424 // that costly call repeatedly. 73425 let cachedNow = 0; 73426 const getNow = () => { 73427 const n = perf.now(); 73428 if (this.ttlResolution > 0) { 73429 cachedNow = n; 73430 const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); 73431 // not available on all platforms 73432 /* c8 ignore start */ 73433 if (t.unref) { 73434 t.unref(); 73435 } 73436 /* c8 ignore stop */ 73437 } 73438 return n; 73439 }; 73440 this.getRemainingTTL = key => { 73441 const index = this.#keyMap.get(key); 73442 if (index === undefined) { 73443 return 0; 73444 } 73445 const ttl = ttls[index]; 73446 const start = starts[index]; 73447 if (!ttl || !start) { 73448 return Infinity; 73449 } 73450 const age = (cachedNow || getNow()) - start; 73451 return ttl - age; 73452 }; 73453 this.#isStale = index => { 73454 const s = starts[index]; 73455 const t = ttls[index]; 73456 return !!t && !!s && (cachedNow || getNow()) - s > t; 73457 }; 73458 } 73459 // conditionally set private methods related to TTL 73460 #updateItemAge = () => { }; 73461 #statusTTL = () => { }; 73462 #setItemTTL = () => { }; 73463 /* c8 ignore stop */ 73464 #isStale = () => false; 73465 #initializeSizeTracking() { 73466 const sizes = new ZeroArray(this.#max); 73467 this.#calculatedSize = 0; 73468 this.#sizes = sizes; 73469 this.#removeItemSize = index => { 73470 this.#calculatedSize -= sizes[index]; 73471 sizes[index] = 0; 73472 }; 73473 this.#requireSize = (k, v, size, sizeCalculation) => { 73474 // provisionally accept background fetches. 73475 // actual value size will be checked when they return. 73476 if (this.#isBackgroundFetch(v)) { 73477 return 0; 73478 } 73479 if (!isPosInt(size)) { 73480 if (sizeCalculation) { 73481 if (typeof sizeCalculation !== 'function') { 73482 throw new TypeError('sizeCalculation must be a function'); 73483 } 73484 size = sizeCalculation(v, k); 73485 if (!isPosInt(size)) { 73486 throw new TypeError('sizeCalculation return invalid (expect positive integer)'); 73487 } 73488 } 73489 else { 73490 throw new TypeError('invalid size value (must be positive integer). ' + 73491 'When maxSize or maxEntrySize is used, sizeCalculation ' + 73492 'or size must be set.'); 73493 } 73494 } 73495 return size; 73496 }; 73497 this.#addItemSize = (index, size, status) => { 73498 sizes[index] = size; 73499 if (this.#maxSize) { 73500 const maxSize = this.#maxSize - sizes[index]; 73501 while (this.#calculatedSize > maxSize) { 73502 this.#evict(true); 73503 } 73504 } 73505 this.#calculatedSize += sizes[index]; 73506 if (status) { 73507 status.entrySize = size; 73508 status.totalCalculatedSize = this.#calculatedSize; 73509 } 73510 }; 73511 } 73512 #removeItemSize = _i => { }; 73513 #addItemSize = (_i, _s, _st) => { }; 73514 #requireSize = (_k, _v, size, sizeCalculation) => { 73515 if (size || sizeCalculation) { 73516 throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); 73517 } 73518 return 0; 73519 }; 73520 *#indexes({ allowStale = this.allowStale } = {}) { 73521 if (this.#size) { 73522 for (let i = this.#tail; true;) { 73523 if (!this.#isValidIndex(i)) { 73524 break; 73525 } 73526 if (allowStale || !this.#isStale(i)) { 73527 yield i; 73528 } 73529 if (i === this.#head) { 73530 break; 73531 } 73532 else { 73533 i = this.#prev[i]; 73534 } 73535 } 73536 } 73537 } 73538 *#rindexes({ allowStale = this.allowStale } = {}) { 73539 if (this.#size) { 73540 for (let i = this.#head; true;) { 73541 if (!this.#isValidIndex(i)) { 73542 break; 73543 } 73544 if (allowStale || !this.#isStale(i)) { 73545 yield i; 73546 } 73547 if (i === this.#tail) { 73548 break; 73549 } 73550 else { 73551 i = this.#next[i]; 73552 } 73553 } 73554 } 73555 } 73556 #isValidIndex(index) { 73557 return (index !== undefined && 73558 this.#keyMap.get(this.#keyList[index]) === index); 73559 } 73560 /** 73561 * Return a generator yielding `[key, value]` pairs, 73562 * in order from most recently used to least recently used. 73563 */ 73564 *entries() { 73565 for (const i of this.#indexes()) { 73566 if (this.#valList[i] !== undefined && 73567 this.#keyList[i] !== undefined && 73568 !this.#isBackgroundFetch(this.#valList[i])) { 73569 yield [this.#keyList[i], this.#valList[i]]; 73570 } 73571 } 73572 } 73573 /** 73574 * Inverse order version of {@link LRUCache.entries} 73575 * 73576 * Return a generator yielding `[key, value]` pairs, 73577 * in order from least recently used to most recently used. 73578 */ 73579 *rentries() { 73580 for (const i of this.#rindexes()) { 73581 if (this.#valList[i] !== undefined && 73582 this.#keyList[i] !== undefined && 73583 !this.#isBackgroundFetch(this.#valList[i])) { 73584 yield [this.#keyList[i], this.#valList[i]]; 73585 } 73586 } 73587 } 73588 /** 73589 * Return a generator yielding the keys in the cache, 73590 * in order from most recently used to least recently used. 73591 */ 73592 *keys() { 73593 for (const i of this.#indexes()) { 73594 const k = this.#keyList[i]; 73595 if (k !== undefined && 73596 !this.#isBackgroundFetch(this.#valList[i])) { 73597 yield k; 73598 } 73599 } 73600 } 73601 /** 73602 * Inverse order version of {@link LRUCache.keys} 73603 * 73604 * Return a generator yielding the keys in the cache, 73605 * in order from least recently used to most recently used. 73606 */ 73607 *rkeys() { 73608 for (const i of this.#rindexes()) { 73609 const k = this.#keyList[i]; 73610 if (k !== undefined && 73611 !this.#isBackgroundFetch(this.#valList[i])) { 73612 yield k; 73613 } 73614 } 73615 } 73616 /** 73617 * Return a generator yielding the values in the cache, 73618 * in order from most recently used to least recently used. 73619 */ 73620 *values() { 73621 for (const i of this.#indexes()) { 73622 const v = this.#valList[i]; 73623 if (v !== undefined && 73624 !this.#isBackgroundFetch(this.#valList[i])) { 73625 yield this.#valList[i]; 73626 } 73627 } 73628 } 73629 /** 73630 * Inverse order version of {@link LRUCache.values} 73631 * 73632 * Return a generator yielding the values in the cache, 73633 * in order from least recently used to most recently used. 73634 */ 73635 *rvalues() { 73636 for (const i of this.#rindexes()) { 73637 const v = this.#valList[i]; 73638 if (v !== undefined && 73639 !this.#isBackgroundFetch(this.#valList[i])) { 73640 yield this.#valList[i]; 73641 } 73642 } 73643 } 73644 /** 73645 * Iterating over the cache itself yields the same results as 73646 * {@link LRUCache.entries} 73647 */ 73648 [Symbol.iterator]() { 73649 return this.entries(); 73650 } 73651 /** 73652 * A String value that is used in the creation of the default string description of an object. 73653 * Called by the built-in method Object.prototype.toString. 73654 */ 73655 [Symbol.toStringTag] = 'LRUCache'; 73656 /** 73657 * Find a value for which the supplied fn method returns a truthy value, 73658 * similar to Array.find(). fn is called as fn(value, key, cache). 73659 */ 73660 find(fn, getOptions = {}) { 73661 for (const i of this.#indexes()) { 73662 const v = this.#valList[i]; 73663 const value = this.#isBackgroundFetch(v) 73664 ? v.__staleWhileFetching 73665 : v; 73666 if (value === undefined) 73667 continue; 73668 if (fn(value, this.#keyList[i], this)) { 73669 return this.get(this.#keyList[i], getOptions); 73670 } 73671 } 73672 } 73673 /** 73674 * Call the supplied function on each item in the cache, in order from 73675 * most recently used to least recently used. fn is called as 73676 * fn(value, key, cache). Does not update age or recenty of use. 73677 * Does not iterate over stale values. 73678 */ 73679 forEach(fn, thisp = this) { 73680 for (const i of this.#indexes()) { 73681 const v = this.#valList[i]; 73682 const value = this.#isBackgroundFetch(v) 73683 ? v.__staleWhileFetching 73684 : v; 73685 if (value === undefined) 73686 continue; 73687 fn.call(thisp, value, this.#keyList[i], this); 73688 } 73689 } 73690 /** 73691 * The same as {@link LRUCache.forEach} but items are iterated over in 73692 * reverse order. (ie, less recently used items are iterated over first.) 73693 */ 73694 rforEach(fn, thisp = this) { 73695 for (const i of this.#rindexes()) { 73696 const v = this.#valList[i]; 73697 const value = this.#isBackgroundFetch(v) 73698 ? v.__staleWhileFetching 73699 : v; 73700 if (value === undefined) 73701 continue; 73702 fn.call(thisp, value, this.#keyList[i], this); 73703 } 73704 } 73705 /** 73706 * Delete any stale entries. Returns true if anything was removed, 73707 * false otherwise. 73708 */ 73709 purgeStale() { 73710 let deleted = false; 73711 for (const i of this.#rindexes({ allowStale: true })) { 73712 if (this.#isStale(i)) { 73713 this.delete(this.#keyList[i]); 73714 deleted = true; 73715 } 73716 } 73717 return deleted; 73718 } 73719 /** 73720 * Get the extended info about a given entry, to get its value, size, and 73721 * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a 73722 * single key. Always returns stale values, if their info is found in the 73723 * cache, so be sure to check for expired TTLs if relevant. 73724 */ 73725 info(key) { 73726 const i = this.#keyMap.get(key); 73727 if (i === undefined) 73728 return undefined; 73729 const v = this.#valList[i]; 73730 const value = this.#isBackgroundFetch(v) 73731 ? v.__staleWhileFetching 73732 : v; 73733 if (value === undefined) 73734 return undefined; 73735 const entry = { value }; 73736 if (this.#ttls && this.#starts) { 73737 const ttl = this.#ttls[i]; 73738 const start = this.#starts[i]; 73739 if (ttl && start) { 73740 const remain = ttl - (perf.now() - start); 73741 entry.ttl = remain; 73742 entry.start = Date.now(); 73743 } 73744 } 73745 if (this.#sizes) { 73746 entry.size = this.#sizes[i]; 73747 } 73748 return entry; 73749 } 73750 /** 73751 * Return an array of [key, {@link LRUCache.Entry}] tuples which can be 73752 * passed to cache.load() 73753 */ 73754 dump() { 73755 const arr = []; 73756 for (const i of this.#indexes({ allowStale: true })) { 73757 const key = this.#keyList[i]; 73758 const v = this.#valList[i]; 73759 const value = this.#isBackgroundFetch(v) 73760 ? v.__staleWhileFetching 73761 : v; 73762 if (value === undefined || key === undefined) 73763 continue; 73764 const entry = { value }; 73765 if (this.#ttls && this.#starts) { 73766 entry.ttl = this.#ttls[i]; 73767 // always dump the start relative to a portable timestamp 73768 // it's ok for this to be a bit slow, it's a rare operation. 73769 const age = perf.now() - this.#starts[i]; 73770 entry.start = Math.floor(Date.now() - age); 73771 } 73772 if (this.#sizes) { 73773 entry.size = this.#sizes[i]; 73774 } 73775 arr.unshift([key, entry]); 73776 } 73777 return arr; 73778 } 73779 /** 73780 * Reset the cache and load in the items in entries in the order listed. 73781 * Note that the shape of the resulting cache may be different if the 73782 * same options are not used in both caches. 73783 */ 73784 load(arr) { 73785 this.clear(); 73786 for (const [key, entry] of arr) { 73787 if (entry.start) { 73788 // entry.start is a portable timestamp, but we may be using 73789 // node's performance.now(), so calculate the offset, so that 73790 // we get the intended remaining TTL, no matter how long it's 73791 // been on ice. 73792 // 73793 // it's ok for this to be a bit slow, it's a rare operation. 73794 const age = Date.now() - entry.start; 73795 entry.start = perf.now() - age; 73796 } 73797 this.set(key, entry.value, entry); 73798 } 73799 } 73800 /** 73801 * Add a value to the cache. 73802 * 73803 * Note: if `undefined` is specified as a value, this is an alias for 73804 * {@link LRUCache#delete} 73805 */ 73806 set(k, v, setOptions = {}) { 73807 if (v === undefined) { 73808 this.delete(k); 73809 return this; 73810 } 73811 const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; 73812 let { noUpdateTTL = this.noUpdateTTL } = setOptions; 73813 const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); 73814 // if the item doesn't fit, don't do anything 73815 // NB: maxEntrySize set to maxSize by default 73816 if (this.maxEntrySize && size > this.maxEntrySize) { 73817 if (status) { 73818 status.set = 'miss'; 73819 status.maxEntrySizeExceeded = true; 73820 } 73821 // have to delete, in case something is there already. 73822 this.delete(k); 73823 return this; 73824 } 73825 let index = this.#size === 0 ? undefined : this.#keyMap.get(k); 73826 if (index === undefined) { 73827 // addition 73828 index = (this.#size === 0 73829 ? this.#tail 73830 : this.#free.length !== 0 73831 ? this.#free.pop() 73832 : this.#size === this.#max 73833 ? this.#evict(false) 73834 : this.#size); 73835 this.#keyList[index] = k; 73836 this.#valList[index] = v; 73837 this.#keyMap.set(k, index); 73838 this.#next[this.#tail] = index; 73839 this.#prev[index] = this.#tail; 73840 this.#tail = index; 73841 this.#size++; 73842 this.#addItemSize(index, size, status); 73843 if (status) 73844 status.set = 'add'; 73845 noUpdateTTL = false; 73846 } 73847 else { 73848 // update 73849 this.#moveToTail(index); 73850 const oldVal = this.#valList[index]; 73851 if (v !== oldVal) { 73852 if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { 73853 oldVal.__abortController.abort(new Error('replaced')); 73854 const { __staleWhileFetching: s } = oldVal; 73855 if (s !== undefined && !noDisposeOnSet) { 73856 if (this.#hasDispose) { 73857 this.#dispose?.(s, k, 'set'); 73858 } 73859 if (this.#hasDisposeAfter) { 73860 this.#disposed?.push([s, k, 'set']); 73861 } 73862 } 73863 } 73864 else if (!noDisposeOnSet) { 73865 if (this.#hasDispose) { 73866 this.#dispose?.(oldVal, k, 'set'); 73867 } 73868 if (this.#hasDisposeAfter) { 73869 this.#disposed?.push([oldVal, k, 'set']); 73870 } 73871 } 73872 this.#removeItemSize(index); 73873 this.#addItemSize(index, size, status); 73874 this.#valList[index] = v; 73875 if (status) { 73876 status.set = 'replace'; 73877 const oldValue = oldVal && this.#isBackgroundFetch(oldVal) 73878 ? oldVal.__staleWhileFetching 73879 : oldVal; 73880 if (oldValue !== undefined) 73881 status.oldValue = oldValue; 73882 } 73883 } 73884 else if (status) { 73885 status.set = 'update'; 73886 } 73887 } 73888 if (ttl !== 0 && !this.#ttls) { 73889 this.#initializeTTLTracking(); 73890 } 73891 if (this.#ttls) { 73892 if (!noUpdateTTL) { 73893 this.#setItemTTL(index, ttl, start); 73894 } 73895 if (status) 73896 this.#statusTTL(status, index); 73897 } 73898 if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { 73899 const dt = this.#disposed; 73900 let task; 73901 while ((task = dt?.shift())) { 73902 this.#disposeAfter?.(...task); 73903 } 73904 } 73905 return this; 73906 } 73907 /** 73908 * Evict the least recently used item, returning its value or 73909 * `undefined` if cache is empty. 73910 */ 73911 pop() { 73912 try { 73913 while (this.#size) { 73914 const val = this.#valList[this.#head]; 73915 this.#evict(true); 73916 if (this.#isBackgroundFetch(val)) { 73917 if (val.__staleWhileFetching) { 73918 return val.__staleWhileFetching; 73919 } 73920 } 73921 else if (val !== undefined) { 73922 return val; 73923 } 73924 } 73925 } 73926 finally { 73927 if (this.#hasDisposeAfter && this.#disposed) { 73928 const dt = this.#disposed; 73929 let task; 73930 while ((task = dt?.shift())) { 73931 this.#disposeAfter?.(...task); 73932 } 73933 } 73934 } 73935 } 73936 #evict(free) { 73937 const head = this.#head; 73938 const k = this.#keyList[head]; 73939 const v = this.#valList[head]; 73940 if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { 73941 v.__abortController.abort(new Error('evicted')); 73942 } 73943 else if (this.#hasDispose || this.#hasDisposeAfter) { 73944 if (this.#hasDispose) { 73945 this.#dispose?.(v, k, 'evict'); 73946 } 73947 if (this.#hasDisposeAfter) { 73948 this.#disposed?.push([v, k, 'evict']); 73949 } 73950 } 73951 this.#removeItemSize(head); 73952 // if we aren't about to use the index, then null these out 73953 if (free) { 73954 this.#keyList[head] = undefined; 73955 this.#valList[head] = undefined; 73956 this.#free.push(head); 73957 } 73958 if (this.#size === 1) { 73959 this.#head = this.#tail = 0; 73960 this.#free.length = 0; 73961 } 73962 else { 73963 this.#head = this.#next[head]; 73964 } 73965 this.#keyMap.delete(k); 73966 this.#size--; 73967 return head; 73968 } 73969 /** 73970 * Check if a key is in the cache, without updating the recency of use. 73971 * Will return false if the item is stale, even though it is technically 73972 * in the cache. 73973 * 73974 * Will not update item age unless 73975 * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. 73976 */ 73977 has(k, hasOptions = {}) { 73978 const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; 73979 const index = this.#keyMap.get(k); 73980 if (index !== undefined) { 73981 const v = this.#valList[index]; 73982 if (this.#isBackgroundFetch(v) && 73983 v.__staleWhileFetching === undefined) { 73984 return false; 73985 } 73986 if (!this.#isStale(index)) { 73987 if (updateAgeOnHas) { 73988 this.#updateItemAge(index); 73989 } 73990 if (status) { 73991 status.has = 'hit'; 73992 this.#statusTTL(status, index); 73993 } 73994 return true; 73995 } 73996 else if (status) { 73997 status.has = 'stale'; 73998 this.#statusTTL(status, index); 73999 } 74000 } 74001 else if (status) { 74002 status.has = 'miss'; 74003 } 74004 return false; 74005 } 74006 /** 74007 * Like {@link LRUCache#get} but doesn't update recency or delete stale 74008 * items. 74009 * 74010 * Returns `undefined` if the item is stale, unless 74011 * {@link LRUCache.OptionsBase.allowStale} is set. 74012 */ 74013 peek(k, peekOptions = {}) { 74014 const { allowStale = this.allowStale } = peekOptions; 74015 const index = this.#keyMap.get(k); 74016 if (index === undefined || 74017 (!allowStale && this.#isStale(index))) { 74018 return; 74019 } 74020 const v = this.#valList[index]; 74021 // either stale and allowed, or forcing a refresh of non-stale value 74022 return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; 74023 } 74024 #backgroundFetch(k, index, options, context) { 74025 const v = index === undefined ? undefined : this.#valList[index]; 74026 if (this.#isBackgroundFetch(v)) { 74027 return v; 74028 } 74029 const ac = new AC(); 74030 const { signal } = options; 74031 // when/if our AC signals, then stop listening to theirs. 74032 signal?.addEventListener('abort', () => ac.abort(signal.reason), { 74033 signal: ac.signal, 74034 }); 74035 const fetchOpts = { 74036 signal: ac.signal, 74037 options, 74038 context, 74039 }; 74040 const cb = (v, updateCache = false) => { 74041 const { aborted } = ac.signal; 74042 const ignoreAbort = options.ignoreFetchAbort && v !== undefined; 74043 if (options.status) { 74044 if (aborted && !updateCache) { 74045 options.status.fetchAborted = true; 74046 options.status.fetchError = ac.signal.reason; 74047 if (ignoreAbort) 74048 options.status.fetchAbortIgnored = true; 74049 } 74050 else { 74051 options.status.fetchResolved = true; 74052 } 74053 } 74054 if (aborted && !ignoreAbort && !updateCache) { 74055 return fetchFail(ac.signal.reason); 74056 } 74057 // either we didn't abort, and are still here, or we did, and ignored 74058 const bf = p; 74059 if (this.#valList[index] === p) { 74060 if (v === undefined) { 74061 if (bf.__staleWhileFetching) { 74062 this.#valList[index] = bf.__staleWhileFetching; 74063 } 74064 else { 74065 this.delete(k); 74066 } 74067 } 74068 else { 74069 if (options.status) 74070 options.status.fetchUpdated = true; 74071 this.set(k, v, fetchOpts.options); 74072 } 74073 } 74074 return v; 74075 }; 74076 const eb = (er) => { 74077 if (options.status) { 74078 options.status.fetchRejected = true; 74079 options.status.fetchError = er; 74080 } 74081 return fetchFail(er); 74082 }; 74083 const fetchFail = (er) => { 74084 const { aborted } = ac.signal; 74085 const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; 74086 const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; 74087 const noDelete = allowStale || options.noDeleteOnFetchRejection; 74088 const bf = p; 74089 if (this.#valList[index] === p) { 74090 // if we allow stale on fetch rejections, then we need to ensure that 74091 // the stale value is not removed from the cache when the fetch fails. 74092 const del = !noDelete || bf.__staleWhileFetching === undefined; 74093 if (del) { 74094 this.delete(k); 74095 } 74096 else if (!allowStaleAborted) { 74097 // still replace the *promise* with the stale value, 74098 // since we are done with the promise at this point. 74099 // leave it untouched if we're still waiting for an 74100 // aborted background fetch that hasn't yet returned. 74101 this.#valList[index] = bf.__staleWhileFetching; 74102 } 74103 } 74104 if (allowStale) { 74105 if (options.status && bf.__staleWhileFetching !== undefined) { 74106 options.status.returnedStale = true; 74107 } 74108 return bf.__staleWhileFetching; 74109 } 74110 else if (bf.__returned === bf) { 74111 throw er; 74112 } 74113 }; 74114 const pcall = (res, rej) => { 74115 const fmp = this.#fetchMethod?.(k, v, fetchOpts); 74116 if (fmp && fmp instanceof Promise) { 74117 fmp.then(v => res(v === undefined ? undefined : v), rej); 74118 } 74119 // ignored, we go until we finish, regardless. 74120 // defer check until we are actually aborting, 74121 // so fetchMethod can override. 74122 ac.signal.addEventListener('abort', () => { 74123 if (!options.ignoreFetchAbort || 74124 options.allowStaleOnFetchAbort) { 74125 res(undefined); 74126 // when it eventually resolves, update the cache. 74127 if (options.allowStaleOnFetchAbort) { 74128 res = v => cb(v, true); 74129 } 74130 } 74131 }); 74132 }; 74133 if (options.status) 74134 options.status.fetchDispatched = true; 74135 const p = new Promise(pcall).then(cb, eb); 74136 const bf = Object.assign(p, { 74137 __abortController: ac, 74138 __staleWhileFetching: v, 74139 __returned: undefined, 74140 }); 74141 if (index === undefined) { 74142 // internal, don't expose status. 74143 this.set(k, bf, { ...fetchOpts.options, status: undefined }); 74144 index = this.#keyMap.get(k); 74145 } 74146 else { 74147 this.#valList[index] = bf; 74148 } 74149 return bf; 74150 } 74151 #isBackgroundFetch(p) { 74152 if (!this.#hasFetchMethod) 74153 return false; 74154 const b = p; 74155 return (!!b && 74156 b instanceof Promise && 74157 b.hasOwnProperty('__staleWhileFetching') && 74158 b.__abortController instanceof AC); 74159 } 74160 async fetch(k, fetchOptions = {}) { 74161 const { 74162 // get options 74163 allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, 74164 // set options 74165 ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, 74166 // fetch exclusive options 74167 noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; 74168 if (!this.#hasFetchMethod) { 74169 if (status) 74170 status.fetch = 'get'; 74171 return this.get(k, { 74172 allowStale, 74173 updateAgeOnGet, 74174 noDeleteOnStaleGet, 74175 status, 74176 }); 74177 } 74178 const options = { 74179 allowStale, 74180 updateAgeOnGet, 74181 noDeleteOnStaleGet, 74182 ttl, 74183 noDisposeOnSet, 74184 size, 74185 sizeCalculation, 74186 noUpdateTTL, 74187 noDeleteOnFetchRejection, 74188 allowStaleOnFetchRejection, 74189 allowStaleOnFetchAbort, 74190 ignoreFetchAbort, 74191 status, 74192 signal, 74193 }; 74194 let index = this.#keyMap.get(k); 74195 if (index === undefined) { 74196 if (status) 74197 status.fetch = 'miss'; 74198 const p = this.#backgroundFetch(k, index, options, context); 74199 return (p.__returned = p); 74200 } 74201 else { 74202 // in cache, maybe already fetching 74203 const v = this.#valList[index]; 74204 if (this.#isBackgroundFetch(v)) { 74205 const stale = allowStale && v.__staleWhileFetching !== undefined; 74206 if (status) { 74207 status.fetch = 'inflight'; 74208 if (stale) 74209 status.returnedStale = true; 74210 } 74211 return stale ? v.__staleWhileFetching : (v.__returned = v); 74212 } 74213 // if we force a refresh, that means do NOT serve the cached value, 74214 // unless we are already in the process of refreshing the cache. 74215 const isStale = this.#isStale(index); 74216 if (!forceRefresh && !isStale) { 74217 if (status) 74218 status.fetch = 'hit'; 74219 this.#moveToTail(index); 74220 if (updateAgeOnGet) { 74221 this.#updateItemAge(index); 74222 } 74223 if (status) 74224 this.#statusTTL(status, index); 74225 return v; 74226 } 74227 // ok, it is stale or a forced refresh, and not already fetching. 74228 // refresh the cache. 74229 const p = this.#backgroundFetch(k, index, options, context); 74230 const hasStale = p.__staleWhileFetching !== undefined; 74231 const staleVal = hasStale && allowStale; 74232 if (status) { 74233 status.fetch = isStale ? 'stale' : 'refresh'; 74234 if (staleVal && isStale) 74235 status.returnedStale = true; 74236 } 74237 return staleVal ? p.__staleWhileFetching : (p.__returned = p); 74238 } 74239 } 74240 /** 74241 * Return a value from the cache. Will update the recency of the cache 74242 * entry found. 74243 * 74244 * If the key is not found, get() will return `undefined`. 74245 */ 74246 get(k, getOptions = {}) { 74247 const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; 74248 const index = this.#keyMap.get(k); 74249 if (index !== undefined) { 74250 const value = this.#valList[index]; 74251 const fetching = this.#isBackgroundFetch(value); 74252 if (status) 74253 this.#statusTTL(status, index); 74254 if (this.#isStale(index)) { 74255 if (status) 74256 status.get = 'stale'; 74257 // delete only if not an in-flight background fetch 74258 if (!fetching) { 74259 if (!noDeleteOnStaleGet) { 74260 this.delete(k); 74261 } 74262 if (status && allowStale) 74263 status.returnedStale = true; 74264 return allowStale ? value : undefined; 74265 } 74266 else { 74267 if (status && 74268 allowStale && 74269 value.__staleWhileFetching !== undefined) { 74270 status.returnedStale = true; 74271 } 74272 return allowStale ? value.__staleWhileFetching : undefined; 74273 } 74274 } 74275 else { 74276 if (status) 74277 status.get = 'hit'; 74278 // if we're currently fetching it, we don't actually have it yet 74279 // it's not stale, which means this isn't a staleWhileRefetching. 74280 // If it's not stale, and fetching, AND has a __staleWhileFetching 74281 // value, then that means the user fetched with {forceRefresh:true}, 74282 // so it's safe to return that value. 74283 if (fetching) { 74284 return value.__staleWhileFetching; 74285 } 74286 this.#moveToTail(index); 74287 if (updateAgeOnGet) { 74288 this.#updateItemAge(index); 74289 } 74290 return value; 74291 } 74292 } 74293 else if (status) { 74294 status.get = 'miss'; 74295 } 74296 } 74297 #connect(p, n) { 74298 this.#prev[n] = p; 74299 this.#next[p] = n; 74300 } 74301 #moveToTail(index) { 74302 // if tail already, nothing to do 74303 // if head, move head to next[index] 74304 // else 74305 // move next[prev[index]] to next[index] (head has no prev) 74306 // move prev[next[index]] to prev[index] 74307 // prev[index] = tail 74308 // next[tail] = index 74309 // tail = index 74310 if (index !== this.#tail) { 74311 if (index === this.#head) { 74312 this.#head = this.#next[index]; 74313 } 74314 else { 74315 this.#connect(this.#prev[index], this.#next[index]); 74316 } 74317 this.#connect(this.#tail, index); 74318 this.#tail = index; 74319 } 74320 } 74321 /** 74322 * Deletes a key out of the cache. 74323 * Returns true if the key was deleted, false otherwise. 74324 */ 74325 delete(k) { 74326 let deleted = false; 74327 if (this.#size !== 0) { 74328 const index = this.#keyMap.get(k); 74329 if (index !== undefined) { 74330 deleted = true; 74331 if (this.#size === 1) { 74332 this.clear(); 74333 } 74334 else { 74335 this.#removeItemSize(index); 74336 const v = this.#valList[index]; 74337 if (this.#isBackgroundFetch(v)) { 74338 v.__abortController.abort(new Error('deleted')); 74339 } 74340 else if (this.#hasDispose || this.#hasDisposeAfter) { 74341 if (this.#hasDispose) { 74342 this.#dispose?.(v, k, 'delete'); 74343 } 74344 if (this.#hasDisposeAfter) { 74345 this.#disposed?.push([v, k, 'delete']); 74346 } 74347 } 74348 this.#keyMap.delete(k); 74349 this.#keyList[index] = undefined; 74350 this.#valList[index] = undefined; 74351 if (index === this.#tail) { 74352 this.#tail = this.#prev[index]; 74353 } 74354 else if (index === this.#head) { 74355 this.#head = this.#next[index]; 74356 } 74357 else { 74358 const pi = this.#prev[index]; 74359 this.#next[pi] = this.#next[index]; 74360 const ni = this.#next[index]; 74361 this.#prev[ni] = this.#prev[index]; 74362 } 74363 this.#size--; 74364 this.#free.push(index); 74365 } 74366 } 74367 } 74368 if (this.#hasDisposeAfter && this.#disposed?.length) { 74369 const dt = this.#disposed; 74370 let task; 74371 while ((task = dt?.shift())) { 74372 this.#disposeAfter?.(...task); 74373 } 74374 } 74375 return deleted; 74376 } 74377 /** 74378 * Clear the cache entirely, throwing away all values. 74379 */ 74380 clear() { 74381 for (const index of this.#rindexes({ allowStale: true })) { 74382 const v = this.#valList[index]; 74383 if (this.#isBackgroundFetch(v)) { 74384 v.__abortController.abort(new Error('deleted')); 74385 } 74386 else { 74387 const k = this.#keyList[index]; 74388 if (this.#hasDispose) { 74389 this.#dispose?.(v, k, 'delete'); 74390 } 74391 if (this.#hasDisposeAfter) { 74392 this.#disposed?.push([v, k, 'delete']); 74393 } 74394 } 74395 } 74396 this.#keyMap.clear(); 74397 this.#valList.fill(undefined); 74398 this.#keyList.fill(undefined); 74399 if (this.#ttls && this.#starts) { 74400 this.#ttls.fill(0); 74401 this.#starts.fill(0); 74402 } 74403 if (this.#sizes) { 74404 this.#sizes.fill(0); 74405 } 74406 this.#head = 0; 74407 this.#tail = 0; 74408 this.#free.length = 0; 74409 this.#calculatedSize = 0; 74410 this.#size = 0; 74411 if (this.#hasDisposeAfter && this.#disposed) { 74412 const dt = this.#disposed; 74413 let task; 74414 while ((task = dt?.shift())) { 74415 this.#disposeAfter?.(...task); 74416 } 74417 } 74418 } 74419 } 74420 exports.LRUCache = LRUCache; 74421 //# sourceMappingURL=index.js.map 74422 74423 /***/ }), 74424 74425 /***/ 8992: 74426 /***/ ((module) => { 74427 74428 "use strict"; 74429 module.exports = {"i8":"2.3.1"}; 74430 74431 /***/ }), 74432 74433 /***/ 4998: 74434 /***/ ((module) => { 74435 74436 "use strict"; 74437 module.exports = JSON.parse('{"https://tuf-repo-cdn.sigstore.dev":{"root.json":"ewoJInNpZ25lZCI6IHsKCQkiX3R5cGUiOiAicm9vdCIsCgkJInNwZWNfdmVyc2lvbiI6ICIxLjAiLAoJCSJ2ZXJzaW9uIjogOSwKCQkiZXhwaXJlcyI6ICIyMDI0LTA5LTEyVDA2OjUzOjEwWiIsCgkJImtleXMiOiB7CgkJCSIxZTFkNjVjZTk4YjEwYWRkYWQ0NzY0ZmViZjdkZGEyZDA0MzZiM2QzYTM4OTM1NzljMGRkZGFlYTIwZTU0ODQ5IjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXpCelZPbUhDUG9qTVZMU0kzNjRXaWlWOE5QckRcbjZJZ1J4Vmxpc2t6L3YreTNKRVI1bWNWR2NPTmxpRGNXTUM1SjJsZkhtalBOUGhiNEg3eG04THpmU0E9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0sCgkJCSIyMzBlMjEyNjE2Mjc0YTQxOTVjZGMyOGU5Zm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":"ewogICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vdm5kLmRldi5zaWdzdG9yZS50cnVzdGVkcm9vdCtqc29uO3ZlcnNpb249MC4xIiwKICAidGxvZ3MiOiBbCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vcmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUyRzJZKzJ0YWJkVFY1QmNHaUJJeDBhOWZBRndya0JibUxTR3RrczRMM3FYNnlZWTB6dWZCbmhDOFVyL2l5NTVHaFdQLzlBL2JZMkxoQzMwTTkrUll0dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDEtMTJUMTE6NTM6MjcuMDAwWiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAid05JOWF0UUdseitWV2ZPNkxSeWdINFFVZlkvOFc0UkZ3aVQ1aTVXUmdCMD0iCiAgICAgIH0KICAgIH0KICBdLAogICJjZXJ0aWZpY2F0ZUF1dGhvcml0aWVzIjogWwogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly9mdWxjaW8uc2lnc3RvcmUuZGV2IiwKICAgICAgImNlcnRDaGFpbiI6IHsKICAgICAgICAiY2VydGlmaWNhdGVzIjogWwogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0Z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iIsCiAgICAgICJoYXNoQWxnb3JpdGhtIjogIlNIQTJfMjU2IiwKICAgICAgInB1YmxpY0tleSI6IHsKICAgICAgICAicmF3Qnl0ZXMiOiAiTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFaVBTbEZpMENtRlRmRWpDVXFGOUh1Q0VjWVhOS0FhWWFsSUptQlo4eXllelBqVHFoeHJLQnBNbmFvY1Z0TEpCSTFlTTN1WG5RelFHQUpkSjRnczlGeXc9PSIsCiAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICJ2YWxpZEZvciI6IHsKICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEwLTIwVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgfQogICAgICB9LAogICAgICAibG9nSWQiOiB7CiAgICAgICAgImtleUlkIjogIjNUMHdhc2JIRVRKakdSNGNtV2MzQXFKS1hyamVQSzMvaDRweWdDOHA3bzQ9IgogICAgICB9CiAgICB9CiAgXSwKICAidGltZXN0YW1wQXV0aG9yaXRpZXMiOiBbCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAiR2l0SHViLCBJbmMuIiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJJbnRlcm5hbCBTZXJ2aWNlcyBSb290IgogICAgICB9LAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlCM0RDQ0FXS2dBd0lCQWdJVWNoa05zSDM2WGEwNGIxTHFJYytxcjlEVmVjTXdDZ1lJS29aSXpqMEVBd013TWpFVk1CTUdBMVVFQ2hNTVIybDBTSFZpTENCSmJtTXVNUmt3RndZRFZRUURFeEJVVTBFZ2FXNTBaWEp0WldScFlYUmxNQjRYRFRJek1EUXhOREF3TURBd01Gb1hEVEkwTURReE16QXdN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ERjTVR2emFYejR4L0ZDY1hqSi8xcUVLb24vcVBJR25hVVJza0R0eU5iTkRPcGVKVERERnF0NDhpTVBybnpweDZJWndxZW1mVUpONHhCRVpmemErcFl0L2l5b2QrOXRacjIwUlJXU3YvbzBVd1F6QU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VnWURWUjBUQVFIL0JBZ3dCZ0VCL3dJQkFqQWRCZ05WSFE0RUZnUVU5TllZbG9ibkFHNGMwL3FqeHlIL2xxL3d6K1F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl4QUxaTFo4QmdSWHpLeExNTU45VklsTytlNGhyQm5OQmdGN3R6N0hucm93djJOZXRaRXJJQUNLRnltQmx2V0R2dE1BSXdaTytraTZzc1ExYnNabzk4TzhtRUFmMk5aN2lpQ2dERFUwVndqZWNvNnp5ZWgwekJUczkvN2dWNkFITlE1M3hEIgogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfSwKICAgICAgInZhbGlkRm9yIjogewogICAgICAgICJzdGFydCI6ICIyMDIzLTA0LTE0VDAwOjAwOjAwLjAwMFoiCiAgICAgIH0KICAgIH0KICBdCn0K","registry.npmjs.org%2Fkeys.json":"ewogICAgImtleXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OmpsM2J3c3d1ODBQampva0NnaDBvMnc1YzJVNExoUUFFNTdnajljejFrekEiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIxOTk5LTAxLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHsKICAgICAgICAgICAgImtleUlkIjogIlNIQTI1NjpqbDNid3N3dTgwUGpqb2tDZ2gwbzJ3NWMyVTRMaFFBRTU3Z2o5Y3oxa3pBIiwKICAgICAgICAgICAgImtleVVzYWdlIjogIm5wbTphdHRlc3RhdGlvbnMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEyLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICBdCn0K"}}}'); 74438 74439 /***/ }), 74440 74441 /***/ 1526: 74442 /***/ ((module) => { 74443 74444 "use strict"; 74445 module.exports = JSON.parse('{"Jw":{"k":"2","K":"5"}}'); 74446 74447 /***/ }), 74448 74449 /***/ 557: 74450 /***/ ((module) => { 74451 74452 "use strict"; 74453 module.exports = JSON.parse('{"name":"make-fetch-happen","version":"13.0.1","description":"Opinionated, caching, retrying fetch client","main":"lib/index.js","files":["bin/","lib/"],"scripts":{"test":"tap","posttest":"npm run lint","eslint":"eslint","lint":"eslint \\"**/*.{js,cjs,ts,mjs,jsx,tsx}\\"","lintfix":"npm run lint -- --fix","postlint":"template-oss-check","snap":"tap","template-oss-apply":"template-oss-apply --force"},"repository":{"type":"git","url":"https://github.com/npm/make-fetch-happen.git"},"keywords":["http","request","fetch","mean girls","caching","cache","subresource integrity"],"author":"GitHub Inc.","license":"ISC","dependencies":{"@npmcli/agent":"^2.0.0","cacache":"^18.0.0","http-cache-semantics":"^4.1.1","is-lambda":"^1.0.1","minipass":"^7.0.2","minipass-fetch":"^3.0.0","minipass-flush":"^1.0.5","minipass-pipeline":"^1.2.4","negotiator":"^0.6.3","proc-log":"^4.2.0","promise-retry":"^2.0.1","ssri":"^10.0.0"},"devDependencies":{"@npmcli/eslint-config":"^4.0.0","@npmcli/template-oss":"4.21.4","nock":"^13.2.4","safe-buffer":"^5.2.1","standard-version":"^9.3.2","tap":"^16.0.0"},"engines":{"node":"^16.14.0 || >=18.0.0"},"tap":{"color":1,"files":"test/*.js","check-coverage":true,"timeout":60,"nyc-arg":["--exclude","tap-snapshots/**"]},"templateOSS":{"//@npmcli/template-oss":"This file is partially managed by @npmcli/template-oss. Edits may be overwritten.","version":"4.21.4","publish":"true"}}'); 74454 74455 /***/ }), 74456 74457 /***/ 500: 74458 /***/ ((module) => { 74459 74460 "use strict"; 74461 module.exports = {"i8":"3.0.4"}; 74462 74463 /***/ }) 74464 74465 /******/ }); 74466 /************************************************************************/ 74467 /******/ // The module cache 74468 /******/ var __webpack_module_cache__ = {}; 74469 /******/ 74470 /******/ // The require function 74471 /******/ function __nccwpck_require__(moduleId) { 74472 /******/ // Check if module is in cache 74473 /******/ var cachedModule = __webpack_module_cache__[moduleId]; 74474 /******/ if (cachedModule !== undefined) { 74475 /******/ return cachedModule.exports; 74476 /******/ } 74477 /******/ // Create a new module (and put it into the cache) 74478 /******/ var module = __webpack_module_cache__[moduleId] = { 74479 /******/ // no module.id needed 74480 /******/ // no module.loaded needed 74481 /******/ exports: {} 74482 /******/ }; 74483 /******/ 74484 /******/ // Execute the module function 74485 /******/ var threw = true; 74486 /******/ try { 74487 /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); 74488 /******/ threw = false; 74489 /******/ } finally { 74490 /******/ if(threw) delete __webpack_module_cache__[moduleId]; 74491 /******/ } 74492 /******/ 74493 /******/ // Return the exports of the module 74494 /******/ return module.exports; 74495 /******/ } 74496 /******/ 74497 /************************************************************************/ 74498 /******/ /* webpack/runtime/compat */ 74499 /******/ 74500 /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; 74501 /******/ 74502 /************************************************************************/ 74503 /******/ 74504 /******/ // startup 74505 /******/ // Load entry module and return exports 74506 /******/ // This entry module is referenced by other modules so it can't be inlined 74507 /******/ var __webpack_exports__ = __nccwpck_require__(3109); 74508 /******/ module.exports = __webpack_exports__; 74509 /******/ 74510 /******/ })() 74511 ; 74512 //# sourceMappingURL=index.js.map